cast enum expressions to enum type if needed
[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                         expression_t *value = parse_constant_expression();
1574
1575                         value = create_implicit_cast(value, enum_type);
1576                         entry->init.enum_value = value;
1577
1578                         /* TODO semantic */
1579                 }
1580
1581                 record_declaration(entry);
1582
1583                 if(token.type != ',')
1584                         break;
1585                 next_token();
1586         } while(token.type != '}');
1587
1588         expect_void('}');
1589 }
1590
1591 static type_t *parse_enum_specifier(void)
1592 {
1593         eat(T_enum);
1594
1595         declaration_t *declaration;
1596         symbol_t      *symbol;
1597
1598         if(token.type == T_IDENTIFIER) {
1599                 symbol = token.v.symbol;
1600                 next_token();
1601
1602                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1603         } else if(token.type != '{') {
1604                 parse_error_expected("while parsing enum type specifier",
1605                                      T_IDENTIFIER, '{', 0);
1606                 return NULL;
1607         } else {
1608                 declaration = NULL;
1609                 symbol      = NULL;
1610         }
1611
1612         if(declaration == NULL) {
1613                 declaration = allocate_declaration_zero();
1614                 declaration->namespc         = NAMESPACE_ENUM;
1615                 declaration->source_position = token.source_position;
1616                 declaration->symbol          = symbol;
1617                 declaration->parent_scope  = scope;
1618         }
1619
1620         type_t *const type      = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1621         type->enumt.declaration = declaration;
1622
1623         if(token.type == '{') {
1624                 if(declaration->init.is_defined) {
1625                         errorf(HERE, "multiple definitions of enum %Y", symbol);
1626                 }
1627                 if (symbol != NULL) {
1628                         environment_push(declaration);
1629                 }
1630                 append_declaration(declaration);
1631                 declaration->init.is_defined = 1;
1632
1633                 parse_enum_entries(type);
1634                 parse_attributes();
1635         }
1636
1637         return type;
1638 }
1639
1640 /**
1641  * if a symbol is a typedef to another type, return true
1642  */
1643 static bool is_typedef_symbol(symbol_t *symbol)
1644 {
1645         const declaration_t *const declaration =
1646                 get_declaration(symbol, NAMESPACE_NORMAL);
1647         return
1648                 declaration != NULL &&
1649                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1650 }
1651
1652 static type_t *parse_typeof(void)
1653 {
1654         eat(T___typeof__);
1655
1656         type_t *type;
1657
1658         expect('(');
1659
1660         expression_t *expression  = NULL;
1661
1662 restart:
1663         switch(token.type) {
1664         case T___extension__:
1665                 /* this can be a prefix to a typename or an expression */
1666                 /* we simply eat it now. */
1667                 do {
1668                         next_token();
1669                 } while(token.type == T___extension__);
1670                 goto restart;
1671
1672         case T_IDENTIFIER:
1673                 if(is_typedef_symbol(token.v.symbol)) {
1674                         type = parse_typename();
1675                 } else {
1676                         expression = parse_expression();
1677                         type       = expression->base.type;
1678                 }
1679                 break;
1680
1681         TYPENAME_START
1682                 type = parse_typename();
1683                 break;
1684
1685         default:
1686                 expression = parse_expression();
1687                 type       = expression->base.type;
1688                 break;
1689         }
1690
1691         expect(')');
1692
1693         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1694         typeof_type->typeoft.expression  = expression;
1695         typeof_type->typeoft.typeof_type = type;
1696
1697         return typeof_type;
1698 }
1699
1700 typedef enum {
1701         SPECIFIER_SIGNED    = 1 << 0,
1702         SPECIFIER_UNSIGNED  = 1 << 1,
1703         SPECIFIER_LONG      = 1 << 2,
1704         SPECIFIER_INT       = 1 << 3,
1705         SPECIFIER_DOUBLE    = 1 << 4,
1706         SPECIFIER_CHAR      = 1 << 5,
1707         SPECIFIER_SHORT     = 1 << 6,
1708         SPECIFIER_LONG_LONG = 1 << 7,
1709         SPECIFIER_FLOAT     = 1 << 8,
1710         SPECIFIER_BOOL      = 1 << 9,
1711         SPECIFIER_VOID      = 1 << 10,
1712 #ifdef PROVIDE_COMPLEX
1713         SPECIFIER_COMPLEX   = 1 << 11,
1714         SPECIFIER_IMAGINARY = 1 << 12,
1715 #endif
1716 } specifiers_t;
1717
1718 static type_t *create_builtin_type(symbol_t *const symbol,
1719                                    type_t *const real_type)
1720 {
1721         type_t *type            = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1722         type->builtin.symbol    = symbol;
1723         type->builtin.real_type = real_type;
1724
1725         type_t *result = typehash_insert(type);
1726         if (type != result) {
1727                 free_type(type);
1728         }
1729
1730         return result;
1731 }
1732
1733 static type_t *get_typedef_type(symbol_t *symbol)
1734 {
1735         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1736         if(declaration == NULL
1737                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1738                 return NULL;
1739
1740         type_t *type               = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1741         type->typedeft.declaration = declaration;
1742
1743         return type;
1744 }
1745
1746 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1747 {
1748         type_t   *type            = NULL;
1749         unsigned  type_qualifiers = 0;
1750         unsigned  type_specifiers = 0;
1751         int       newtype         = 0;
1752
1753         specifiers->source_position = token.source_position;
1754
1755         while(true) {
1756                 switch(token.type) {
1757
1758                 /* storage class */
1759 #define MATCH_STORAGE_CLASS(token, class)                                \
1760                 case token:                                                      \
1761                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1762                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
1763                         }                                                            \
1764                         specifiers->storage_class = class;                           \
1765                         next_token();                                                \
1766                         break;
1767
1768                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1769                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1770                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1771                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1772                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1773
1774                 case T___thread:
1775                         switch (specifiers->storage_class) {
1776                                 case STORAGE_CLASS_NONE:
1777                                         specifiers->storage_class = STORAGE_CLASS_THREAD;
1778                                         break;
1779
1780                                 case STORAGE_CLASS_EXTERN:
1781                                         specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
1782                                         break;
1783
1784                                 case STORAGE_CLASS_STATIC:
1785                                         specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
1786                                         break;
1787
1788                                 default:
1789                                         errorf(HERE, "multiple storage classes in declaration specifiers");
1790                                         break;
1791                         }
1792                         next_token();
1793                         break;
1794
1795                 /* type qualifiers */
1796 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1797                 case token:                                                     \
1798                         type_qualifiers |= qualifier;                               \
1799                         next_token();                                               \
1800                         break;
1801
1802                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1803                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1804                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1805
1806                 case T___extension__:
1807                         /* TODO */
1808                         next_token();
1809                         break;
1810
1811                 /* type specifiers */
1812 #define MATCH_SPECIFIER(token, specifier, name)                         \
1813                 case token:                                                     \
1814                         next_token();                                               \
1815                         if(type_specifiers & specifier) {                           \
1816                                 errorf(HERE, "multiple " name " type specifiers given"); \
1817                         } else {                                                    \
1818                                 type_specifiers |= specifier;                           \
1819                         }                                                           \
1820                         break;
1821
1822                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1823                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1824                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1825                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1826                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1827                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1828                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1829                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1830                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1831 #ifdef PROVIDE_COMPLEX
1832                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1833                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1834 #endif
1835                 case T_forceinline:
1836                         /* only in microsoft mode */
1837                         specifiers->decl_modifiers |= DM_FORCEINLINE;
1838
1839                 case T_inline:
1840                         next_token();
1841                         specifiers->is_inline = true;
1842                         break;
1843
1844                 case T_long:
1845                         next_token();
1846                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1847                                 errorf(HERE, "multiple type specifiers given");
1848                         } else if(type_specifiers & SPECIFIER_LONG) {
1849                                 type_specifiers |= SPECIFIER_LONG_LONG;
1850                         } else {
1851                                 type_specifiers |= SPECIFIER_LONG;
1852                         }
1853                         break;
1854
1855                 case T_struct: {
1856                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
1857
1858                         type->compound.declaration = parse_compound_type_specifier(true);
1859                         break;
1860                 }
1861                 case T_union: {
1862                         type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
1863
1864                         type->compound.declaration = parse_compound_type_specifier(false);
1865                         break;
1866                 }
1867                 case T_enum:
1868                         type = parse_enum_specifier();
1869                         break;
1870                 case T___typeof__:
1871                         type = parse_typeof();
1872                         break;
1873                 case T___builtin_va_list:
1874                         type = duplicate_type(type_valist);
1875                         next_token();
1876                         break;
1877
1878                 case T___attribute__:
1879                         parse_attributes();
1880                         break;
1881
1882                 case T_IDENTIFIER: {
1883                         /* only parse identifier if we haven't found a type yet */
1884                         if(type != NULL || type_specifiers != 0)
1885                                 goto finish_specifiers;
1886
1887                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1888
1889                         if(typedef_type == NULL)
1890                                 goto finish_specifiers;
1891
1892                         next_token();
1893                         type = typedef_type;
1894                         break;
1895                 }
1896
1897                 /* function specifier */
1898                 default:
1899                         goto finish_specifiers;
1900                 }
1901         }
1902
1903 finish_specifiers:
1904
1905         if(type == NULL) {
1906                 atomic_type_kind_t atomic_type;
1907
1908                 /* match valid basic types */
1909                 switch(type_specifiers) {
1910                 case SPECIFIER_VOID:
1911                         atomic_type = ATOMIC_TYPE_VOID;
1912                         break;
1913                 case SPECIFIER_CHAR:
1914                         atomic_type = ATOMIC_TYPE_CHAR;
1915                         break;
1916                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1917                         atomic_type = ATOMIC_TYPE_SCHAR;
1918                         break;
1919                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1920                         atomic_type = ATOMIC_TYPE_UCHAR;
1921                         break;
1922                 case SPECIFIER_SHORT:
1923                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1924                 case SPECIFIER_SHORT | SPECIFIER_INT:
1925                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1926                         atomic_type = ATOMIC_TYPE_SHORT;
1927                         break;
1928                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1929                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1930                         atomic_type = ATOMIC_TYPE_USHORT;
1931                         break;
1932                 case SPECIFIER_INT:
1933                 case SPECIFIER_SIGNED:
1934                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1935                         atomic_type = ATOMIC_TYPE_INT;
1936                         break;
1937                 case SPECIFIER_UNSIGNED:
1938                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1939                         atomic_type = ATOMIC_TYPE_UINT;
1940                         break;
1941                 case SPECIFIER_LONG:
1942                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1943                 case SPECIFIER_LONG | SPECIFIER_INT:
1944                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1945                         atomic_type = ATOMIC_TYPE_LONG;
1946                         break;
1947                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1948                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1949                         atomic_type = ATOMIC_TYPE_ULONG;
1950                         break;
1951                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1952                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1953                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1954                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1955                         | SPECIFIER_INT:
1956                         atomic_type = ATOMIC_TYPE_LONGLONG;
1957                         break;
1958                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1959                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1960                         | SPECIFIER_INT:
1961                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1962                         break;
1963                 case SPECIFIER_FLOAT:
1964                         atomic_type = ATOMIC_TYPE_FLOAT;
1965                         break;
1966                 case SPECIFIER_DOUBLE:
1967                         atomic_type = ATOMIC_TYPE_DOUBLE;
1968                         break;
1969                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1970                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1971                         break;
1972                 case SPECIFIER_BOOL:
1973                         atomic_type = ATOMIC_TYPE_BOOL;
1974                         break;
1975 #ifdef PROVIDE_COMPLEX
1976                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1977                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1978                         break;
1979                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1980                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1981                         break;
1982                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1983                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1984                         break;
1985                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1986                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1987                         break;
1988                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1989                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1990                         break;
1991                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1992                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1993                         break;
1994 #endif
1995                 default:
1996                         /* invalid specifier combination, give an error message */
1997                         if(type_specifiers == 0) {
1998                                 if (! strict_mode) {
1999                                         if (warning.implicit_int) {
2000                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
2001                                         }
2002                                         atomic_type = ATOMIC_TYPE_INT;
2003                                         break;
2004                                 } else {
2005                                         errorf(HERE, "no type specifiers given in declaration");
2006                                 }
2007                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
2008                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
2009                                 errorf(HERE, "signed and unsigned specifiers gives");
2010                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2011                                 errorf(HERE, "only integer types can be signed or unsigned");
2012                         } else {
2013                                 errorf(HERE, "multiple datatypes in declaration");
2014                         }
2015                         atomic_type = ATOMIC_TYPE_INVALID;
2016                 }
2017
2018                 type               = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2019                 type->atomic.akind = atomic_type;
2020                 newtype            = 1;
2021         } else {
2022                 if(type_specifiers != 0) {
2023                         errorf(HERE, "multiple datatypes in declaration");
2024                 }
2025         }
2026
2027         type->base.qualifiers = type_qualifiers;
2028
2029         type_t *result = typehash_insert(type);
2030         if(newtype && result != type) {
2031                 free_type(type);
2032         }
2033
2034         specifiers->type = result;
2035 }
2036
2037 static type_qualifiers_t parse_type_qualifiers(void)
2038 {
2039         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2040
2041         while(true) {
2042                 switch(token.type) {
2043                 /* type qualifiers */
2044                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2045                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2046                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2047
2048                 default:
2049                         return type_qualifiers;
2050                 }
2051         }
2052 }
2053
2054 static declaration_t *parse_identifier_list(void)
2055 {
2056         declaration_t *declarations     = NULL;
2057         declaration_t *last_declaration = NULL;
2058         do {
2059                 declaration_t *const declaration = allocate_declaration_zero();
2060                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
2061                 declaration->source_position = token.source_position;
2062                 declaration->symbol          = token.v.symbol;
2063                 next_token();
2064
2065                 if(last_declaration != NULL) {
2066                         last_declaration->next = declaration;
2067                 } else {
2068                         declarations = declaration;
2069                 }
2070                 last_declaration = declaration;
2071
2072                 if(token.type != ',')
2073                         break;
2074                 next_token();
2075         } while(token.type == T_IDENTIFIER);
2076
2077         return declarations;
2078 }
2079
2080 static void semantic_parameter(declaration_t *declaration)
2081 {
2082         /* TODO: improve error messages */
2083
2084         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
2085                 errorf(HERE, "typedef not allowed in parameter list");
2086         } else if(declaration->storage_class != STORAGE_CLASS_NONE
2087                         && declaration->storage_class != STORAGE_CLASS_REGISTER) {
2088                 errorf(HERE, "parameter may only have none or register storage class");
2089         }
2090
2091         type_t *const orig_type = declaration->type;
2092         type_t *      type      = skip_typeref(orig_type);
2093
2094         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
2095          * into a pointer. Â§ 6.7.5.3 (7) */
2096         if (is_type_array(type)) {
2097                 type_t *const element_type = type->array.element_type;
2098
2099                 type = make_pointer_type(element_type, type->base.qualifiers);
2100
2101                 declaration->type = type;
2102         }
2103
2104         if(is_type_incomplete(type)) {
2105                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2106                        orig_type, declaration->symbol);
2107         }
2108 }
2109
2110 static declaration_t *parse_parameter(void)
2111 {
2112         declaration_specifiers_t specifiers;
2113         memset(&specifiers, 0, sizeof(specifiers));
2114
2115         parse_declaration_specifiers(&specifiers);
2116
2117         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2118
2119         semantic_parameter(declaration);
2120
2121         return declaration;
2122 }
2123
2124 static declaration_t *parse_parameters(function_type_t *type)
2125 {
2126         if(token.type == T_IDENTIFIER) {
2127                 symbol_t *symbol = token.v.symbol;
2128                 if(!is_typedef_symbol(symbol)) {
2129                         type->kr_style_parameters = true;
2130                         return parse_identifier_list();
2131                 }
2132         }
2133
2134         if(token.type == ')') {
2135                 type->unspecified_parameters = 1;
2136                 return NULL;
2137         }
2138         if(token.type == T_void && look_ahead(1)->type == ')') {
2139                 next_token();
2140                 return NULL;
2141         }
2142
2143         declaration_t        *declarations = NULL;
2144         declaration_t        *declaration;
2145         declaration_t        *last_declaration = NULL;
2146         function_parameter_t *parameter;
2147         function_parameter_t *last_parameter = NULL;
2148
2149         while(true) {
2150                 switch(token.type) {
2151                 case T_DOTDOTDOT:
2152                         next_token();
2153                         type->variadic = 1;
2154                         return declarations;
2155
2156                 case T_IDENTIFIER:
2157                 case T___extension__:
2158                 DECLARATION_START
2159                         declaration = parse_parameter();
2160
2161                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
2162                         memset(parameter, 0, sizeof(parameter[0]));
2163                         parameter->type = declaration->type;
2164
2165                         if(last_parameter != NULL) {
2166                                 last_declaration->next = declaration;
2167                                 last_parameter->next   = parameter;
2168                         } else {
2169                                 type->parameters = parameter;
2170                                 declarations     = declaration;
2171                         }
2172                         last_parameter   = parameter;
2173                         last_declaration = declaration;
2174                         break;
2175
2176                 default:
2177                         return declarations;
2178                 }
2179                 if(token.type != ',')
2180                         return declarations;
2181                 next_token();
2182         }
2183 }
2184
2185 typedef enum {
2186         CONSTRUCT_INVALID,
2187         CONSTRUCT_POINTER,
2188         CONSTRUCT_FUNCTION,
2189         CONSTRUCT_ARRAY
2190 } construct_type_kind_t;
2191
2192 typedef struct construct_type_t construct_type_t;
2193 struct construct_type_t {
2194         construct_type_kind_t  kind;
2195         construct_type_t      *next;
2196 };
2197
2198 typedef struct parsed_pointer_t parsed_pointer_t;
2199 struct parsed_pointer_t {
2200         construct_type_t  construct_type;
2201         type_qualifiers_t type_qualifiers;
2202 };
2203
2204 typedef struct construct_function_type_t construct_function_type_t;
2205 struct construct_function_type_t {
2206         construct_type_t  construct_type;
2207         type_t           *function_type;
2208 };
2209
2210 typedef struct parsed_array_t parsed_array_t;
2211 struct parsed_array_t {
2212         construct_type_t  construct_type;
2213         type_qualifiers_t type_qualifiers;
2214         bool              is_static;
2215         bool              is_variable;
2216         expression_t     *size;
2217 };
2218
2219 typedef struct construct_base_type_t construct_base_type_t;
2220 struct construct_base_type_t {
2221         construct_type_t  construct_type;
2222         type_t           *type;
2223 };
2224
2225 static construct_type_t *parse_pointer_declarator(void)
2226 {
2227         eat('*');
2228
2229         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2230         memset(pointer, 0, sizeof(pointer[0]));
2231         pointer->construct_type.kind = CONSTRUCT_POINTER;
2232         pointer->type_qualifiers     = parse_type_qualifiers();
2233
2234         return (construct_type_t*) pointer;
2235 }
2236
2237 static construct_type_t *parse_array_declarator(void)
2238 {
2239         eat('[');
2240
2241         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2242         memset(array, 0, sizeof(array[0]));
2243         array->construct_type.kind = CONSTRUCT_ARRAY;
2244
2245         if(token.type == T_static) {
2246                 array->is_static = true;
2247                 next_token();
2248         }
2249
2250         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2251         if(type_qualifiers != 0) {
2252                 if(token.type == T_static) {
2253                         array->is_static = true;
2254                         next_token();
2255                 }
2256         }
2257         array->type_qualifiers = type_qualifiers;
2258
2259         if(token.type == '*' && look_ahead(1)->type == ']') {
2260                 array->is_variable = true;
2261                 next_token();
2262         } else if(token.type != ']') {
2263                 array->size = parse_assignment_expression();
2264         }
2265
2266         expect(']');
2267
2268         return (construct_type_t*) array;
2269 }
2270
2271 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2272 {
2273         eat('(');
2274
2275         type_t *type;
2276         if(declaration != NULL) {
2277                 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2278         } else {
2279                 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2280         }
2281
2282         declaration_t *parameters = parse_parameters(&type->function);
2283         if(declaration != NULL) {
2284                 declaration->scope.declarations = parameters;
2285         }
2286
2287         construct_function_type_t *construct_function_type =
2288                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2289         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2290         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2291         construct_function_type->function_type       = type;
2292
2293         expect(')');
2294
2295         return (construct_type_t*) construct_function_type;
2296 }
2297
2298 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2299                 bool may_be_abstract)
2300 {
2301         /* construct a single linked list of construct_type_t's which describe
2302          * how to construct the final declarator type */
2303         construct_type_t *first = NULL;
2304         construct_type_t *last  = NULL;
2305
2306         /* pointers */
2307         while(token.type == '*') {
2308                 construct_type_t *type = parse_pointer_declarator();
2309
2310                 if(last == NULL) {
2311                         first = type;
2312                         last  = type;
2313                 } else {
2314                         last->next = type;
2315                         last       = type;
2316                 }
2317         }
2318
2319         /* TODO: find out if this is correct */
2320         parse_attributes();
2321
2322         construct_type_t *inner_types = NULL;
2323
2324         switch(token.type) {
2325         case T_IDENTIFIER:
2326                 if(declaration == NULL) {
2327                         errorf(HERE, "no identifier expected in typename");
2328                 } else {
2329                         declaration->symbol          = token.v.symbol;
2330                         declaration->source_position = token.source_position;
2331                 }
2332                 next_token();
2333                 break;
2334         case '(':
2335                 next_token();
2336                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2337                 expect(')');
2338                 break;
2339         default:
2340                 if(may_be_abstract)
2341                         break;
2342                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2343                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2344                  * eat '}' */
2345                 if(token.type == '}' && current_function == NULL) {
2346                         next_token();
2347                 } else {
2348                         eat_statement();
2349                 }
2350                 return NULL;
2351         }
2352
2353         construct_type_t *p = last;
2354
2355         while(true) {
2356                 construct_type_t *type;
2357                 switch(token.type) {
2358                 case '(':
2359                         type = parse_function_declarator(declaration);
2360                         break;
2361                 case '[':
2362                         type = parse_array_declarator();
2363                         break;
2364                 default:
2365                         goto declarator_finished;
2366                 }
2367
2368                 /* insert in the middle of the list (behind p) */
2369                 if(p != NULL) {
2370                         type->next = p->next;
2371                         p->next    = type;
2372                 } else {
2373                         type->next = first;
2374                         first      = type;
2375                 }
2376                 if(last == p) {
2377                         last = type;
2378                 }
2379         }
2380
2381 declarator_finished:
2382         parse_attributes();
2383
2384         /* append inner_types at the end of the list, we don't to set last anymore
2385          * as it's not needed anymore */
2386         if(last == NULL) {
2387                 assert(first == NULL);
2388                 first = inner_types;
2389         } else {
2390                 last->next = inner_types;
2391         }
2392
2393         return first;
2394 }
2395
2396 static type_t *construct_declarator_type(construct_type_t *construct_list,
2397                                          type_t *type)
2398 {
2399         construct_type_t *iter = construct_list;
2400         for( ; iter != NULL; iter = iter->next) {
2401                 switch(iter->kind) {
2402                 case CONSTRUCT_INVALID:
2403                         panic("invalid type construction found");
2404                 case CONSTRUCT_FUNCTION: {
2405                         construct_function_type_t *construct_function_type
2406                                 = (construct_function_type_t*) iter;
2407
2408                         type_t *function_type = construct_function_type->function_type;
2409
2410                         function_type->function.return_type = type;
2411
2412                         type_t *skipped_return_type = skip_typeref(type);
2413                         if (is_type_function(skipped_return_type)) {
2414                                 errorf(HERE, "function returning function is not allowed");
2415                                 type = type_error_type;
2416                         } else if (is_type_array(skipped_return_type)) {
2417                                 errorf(HERE, "function returning array is not allowed");
2418                                 type = type_error_type;
2419                         } else {
2420                                 type = function_type;
2421                         }
2422                         break;
2423                 }
2424
2425                 case CONSTRUCT_POINTER: {
2426                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2427                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2428                         pointer_type->pointer.points_to  = type;
2429                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2430
2431                         type = pointer_type;
2432                         break;
2433                 }
2434
2435                 case CONSTRUCT_ARRAY: {
2436                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2437                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2438
2439                         expression_t *size_expression = parsed_array->size;
2440
2441                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
2442                         array_type->array.element_type    = type;
2443                         array_type->array.is_static       = parsed_array->is_static;
2444                         array_type->array.is_variable     = parsed_array->is_variable;
2445                         array_type->array.size_expression = size_expression;
2446
2447                         if(size_expression != NULL &&
2448                                         is_constant_expression(size_expression)) {
2449                                 array_type->array.size_constant = true;
2450                                 array_type->array.size
2451                                         = fold_constant(size_expression);
2452                         }
2453
2454                         type_t *skipped_type = skip_typeref(type);
2455                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2456                                 errorf(HERE, "array of void is not allowed");
2457                                 type = type_error_type;
2458                         } else {
2459                                 type = array_type;
2460                         }
2461                         break;
2462                 }
2463                 }
2464
2465                 type_t *hashed_type = typehash_insert(type);
2466                 if(hashed_type != type) {
2467                         /* the function type was constructed earlier freeing it here will
2468                          * destroy other types... */
2469                         if(iter->kind != CONSTRUCT_FUNCTION) {
2470                                 free_type(type);
2471                         }
2472                         type = hashed_type;
2473                 }
2474         }
2475
2476         return type;
2477 }
2478
2479 static declaration_t *parse_declarator(
2480                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2481 {
2482         declaration_t *const declaration = allocate_declaration_zero();
2483         declaration->storage_class  = specifiers->storage_class;
2484         declaration->modifiers      = specifiers->decl_modifiers;
2485         declaration->is_inline      = specifiers->is_inline;
2486
2487         construct_type_t *construct_type
2488                 = parse_inner_declarator(declaration, may_be_abstract);
2489         type_t *const type = specifiers->type;
2490         declaration->type = construct_declarator_type(construct_type, type);
2491
2492         if(construct_type != NULL) {
2493                 obstack_free(&temp_obst, construct_type);
2494         }
2495
2496         return declaration;
2497 }
2498
2499 static type_t *parse_abstract_declarator(type_t *base_type)
2500 {
2501         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2502
2503         type_t *result = construct_declarator_type(construct_type, base_type);
2504         if(construct_type != NULL) {
2505                 obstack_free(&temp_obst, construct_type);
2506         }
2507
2508         return result;
2509 }
2510
2511 static declaration_t *append_declaration(declaration_t* const declaration)
2512 {
2513         if (last_declaration != NULL) {
2514                 last_declaration->next = declaration;
2515         } else {
2516                 scope->declarations = declaration;
2517         }
2518         last_declaration = declaration;
2519         return declaration;
2520 }
2521
2522 /**
2523  * Check if the declaration of main is suspicious.  main should be a
2524  * function with external linkage, returning int, taking either zero
2525  * arguments, two, or three arguments of appropriate types, ie.
2526  *
2527  * int main([ int argc, char **argv [, char **env ] ]).
2528  *
2529  * @param decl    the declaration to check
2530  * @param type    the function type of the declaration
2531  */
2532 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2533 {
2534         if (decl->storage_class == STORAGE_CLASS_STATIC) {
2535                 warningf(decl->source_position, "'main' is normally a non-static function");
2536         }
2537         if (skip_typeref(func_type->return_type) != type_int) {
2538                 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2539         }
2540         const function_parameter_t *parm = func_type->parameters;
2541         if (parm != NULL) {
2542                 type_t *const first_type = parm->type;
2543                 if (!types_compatible(skip_typeref(first_type), type_int)) {
2544                         warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2545                 }
2546                 parm = parm->next;
2547                 if (parm != NULL) {
2548                         type_t *const second_type = parm->type;
2549                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2550                                 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2551                         }
2552                         parm = parm->next;
2553                         if (parm != NULL) {
2554                                 type_t *const third_type = parm->type;
2555                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2556                                         warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2557                                 }
2558                                 parm = parm->next;
2559                                 if (parm != NULL) {
2560                                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2561                                 }
2562                         }
2563                 } else {
2564                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2565                 }
2566         }
2567 }
2568
2569 /**
2570  * Check if a symbol is the equal to "main".
2571  */
2572 static bool is_sym_main(const symbol_t *const sym)
2573 {
2574         return strcmp(sym->string, "main") == 0;
2575 }
2576
2577 static declaration_t *internal_record_declaration(
2578         declaration_t *const declaration,
2579         const bool is_function_definition)
2580 {
2581         const symbol_t *const symbol  = declaration->symbol;
2582         const namespace_t     namespc = (namespace_t)declaration->namespc;
2583
2584         type_t *const orig_type = declaration->type;
2585         type_t *const type      = skip_typeref(orig_type);
2586         if (is_type_function(type) &&
2587                         type->function.unspecified_parameters &&
2588                         warning.strict_prototypes) {
2589                 warningf(declaration->source_position,
2590                          "function declaration '%#T' is not a prototype",
2591                          orig_type, declaration->symbol);
2592         }
2593
2594         if (is_function_definition && warning.main && is_sym_main(symbol)) {
2595                 check_type_of_main(declaration, &type->function);
2596         }
2597
2598         assert(declaration->symbol != NULL);
2599         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2600
2601         assert(declaration != previous_declaration);
2602         if (previous_declaration != NULL) {
2603                 if (previous_declaration->parent_scope == scope) {
2604                         /* can happen for K&R style declarations */
2605                         if(previous_declaration->type == NULL) {
2606                                 previous_declaration->type = declaration->type;
2607                         }
2608
2609                         const type_t *prev_type = skip_typeref(previous_declaration->type);
2610                         if (!types_compatible(type, prev_type)) {
2611                                 errorf(declaration->source_position,
2612                                        "declaration '%#T' is incompatible with "
2613                                        "previous declaration '%#T'",
2614                                        orig_type, symbol, previous_declaration->type, symbol);
2615                                 errorf(previous_declaration->source_position,
2616                                        "previous declaration of '%Y' was here", symbol);
2617                         } else {
2618                                 unsigned old_storage_class
2619                                         = previous_declaration->storage_class;
2620                                 unsigned new_storage_class = declaration->storage_class;
2621
2622                                 if(is_type_incomplete(prev_type)) {
2623                                         previous_declaration->type = type;
2624                                         prev_type                  = type;
2625                                 }
2626
2627                                 /* pretend no storage class means extern for function
2628                                  * declarations (except if the previous declaration is neither
2629                                  * none nor extern) */
2630                                 if (is_type_function(type)) {
2631                                         switch (old_storage_class) {
2632                                                 case STORAGE_CLASS_NONE:
2633                                                         old_storage_class = STORAGE_CLASS_EXTERN;
2634
2635                                                 case STORAGE_CLASS_EXTERN:
2636                                                         if (is_function_definition) {
2637                                                                 if (warning.missing_prototypes &&
2638                                                                     prev_type->function.unspecified_parameters &&
2639                                                                     !is_sym_main(symbol)) {
2640                                                                         warningf(declaration->source_position,
2641                                                                                  "no previous prototype for '%#T'",
2642                                                                                  orig_type, symbol);
2643                                                                 }
2644                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
2645                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
2646                                                         }
2647                                                         break;
2648
2649                                                 default: break;
2650                                         }
2651                                 }
2652
2653                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
2654                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
2655 warn_redundant_declaration:
2656                                         if (warning.redundant_decls) {
2657                                                 warningf(declaration->source_position,
2658                                                          "redundant declaration for '%Y'", symbol);
2659                                                 warningf(previous_declaration->source_position,
2660                                                          "previous declaration of '%Y' was here",
2661                                                          symbol);
2662                                         }
2663                                 } else if (current_function == NULL) {
2664                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
2665                                                         new_storage_class == STORAGE_CLASS_STATIC) {
2666                                                 errorf(declaration->source_position,
2667                                                        "static declaration of '%Y' follows non-static declaration",
2668                                                        symbol);
2669                                                 errorf(previous_declaration->source_position,
2670                                                        "previous declaration of '%Y' was here", symbol);
2671                                         } else {
2672                                                 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
2673                                                         goto warn_redundant_declaration;
2674                                                 }
2675                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
2676                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
2677                                                 }
2678                                         }
2679                                 } else {
2680                                         if (old_storage_class == new_storage_class) {
2681                                                 errorf(declaration->source_position,
2682                                                        "redeclaration of '%Y'", symbol);
2683                                         } else {
2684                                                 errorf(declaration->source_position,
2685                                                        "redeclaration of '%Y' with different linkage",
2686                                                        symbol);
2687                                         }
2688                                         errorf(previous_declaration->source_position,
2689                                                "previous declaration of '%Y' was here", symbol);
2690                                 }
2691                         }
2692                         return previous_declaration;
2693                 }
2694         } else if (is_function_definition) {
2695                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
2696                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
2697                                 warningf(declaration->source_position,
2698                                          "no previous prototype for '%#T'", orig_type, symbol);
2699                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
2700                                 warningf(declaration->source_position,
2701                                          "no previous declaration for '%#T'", orig_type,
2702                                          symbol);
2703                         }
2704                 }
2705         } else if (warning.missing_declarations &&
2706             scope == global_scope &&
2707             !is_type_function(type) && (
2708               declaration->storage_class == STORAGE_CLASS_NONE ||
2709               declaration->storage_class == STORAGE_CLASS_THREAD
2710             )) {
2711                 warningf(declaration->source_position,
2712                          "no previous declaration for '%#T'", orig_type, symbol);
2713         }
2714
2715         assert(declaration->parent_scope == NULL);
2716         assert(scope != NULL);
2717
2718         declaration->parent_scope = scope;
2719
2720         environment_push(declaration);
2721         return append_declaration(declaration);
2722 }
2723
2724 static declaration_t *record_declaration(declaration_t *declaration)
2725 {
2726         return internal_record_declaration(declaration, false);
2727 }
2728
2729 static declaration_t *record_function_definition(declaration_t *declaration)
2730 {
2731         return internal_record_declaration(declaration, true);
2732 }
2733
2734 static void parser_error_multiple_definition(declaration_t *declaration,
2735                 const source_position_t source_position)
2736 {
2737         errorf(source_position, "multiple definition of symbol '%Y'",
2738                declaration->symbol);
2739         errorf(declaration->source_position,
2740                "this is the location of the previous definition.");
2741 }
2742
2743 static bool is_declaration_specifier(const token_t *token,
2744                                      bool only_type_specifiers)
2745 {
2746         switch(token->type) {
2747                 TYPE_SPECIFIERS
2748                         return true;
2749                 case T_IDENTIFIER:
2750                         return is_typedef_symbol(token->v.symbol);
2751
2752                 case T___extension__:
2753                 STORAGE_CLASSES
2754                 TYPE_QUALIFIERS
2755                         return !only_type_specifiers;
2756
2757                 default:
2758                         return false;
2759         }
2760 }
2761
2762 static void parse_init_declarator_rest(declaration_t *declaration)
2763 {
2764         eat('=');
2765
2766         type_t *orig_type = declaration->type;
2767         type_t *type      = type = skip_typeref(orig_type);
2768
2769         if(declaration->init.initializer != NULL) {
2770                 parser_error_multiple_definition(declaration, token.source_position);
2771         }
2772
2773         initializer_t *initializer = parse_initializer(type);
2774
2775         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
2776          * the array type size */
2777         if(is_type_array(type) && initializer != NULL) {
2778                 array_type_t *array_type = &type->array;
2779
2780                 if(array_type->size_expression == NULL) {
2781                         size_t size;
2782                         switch (initializer->kind) {
2783                                 case INITIALIZER_LIST: {
2784                                         /* TODO */
2785                                         size = initializer->list.len;
2786                                         break;
2787                                 }
2788
2789                                 case INITIALIZER_STRING: {
2790                                         size = initializer->string.string.size;
2791                                         break;
2792                                 }
2793
2794                                 case INITIALIZER_WIDE_STRING: {
2795                                         size = initializer->wide_string.string.size;
2796                                         break;
2797                                 }
2798
2799                                 default: {
2800                                         panic("invalid initializer type");
2801                                         break;
2802                                 }
2803                         }
2804
2805                         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2806                         cnst->base.type          = type_size_t;
2807                         cnst->conste.v.int_value = size;
2808
2809                         array_type->size_expression = cnst;
2810                         array_type->size_constant   = true;
2811                         array_type->size            = size;
2812                 }
2813         }
2814
2815         if(is_type_function(type)) {
2816                 errorf(declaration->source_position,
2817                        "initializers not allowed for function types at declator '%Y' (type '%T')",
2818                        declaration->symbol, orig_type);
2819         } else {
2820                 declaration->init.initializer = initializer;
2821         }
2822 }
2823
2824 /* parse rest of a declaration without any declarator */
2825 static void parse_anonymous_declaration_rest(
2826                 const declaration_specifiers_t *specifiers,
2827                 parsed_declaration_func finished_declaration)
2828 {
2829         eat(';');
2830
2831         declaration_t *const declaration = allocate_declaration_zero();
2832         declaration->type            = specifiers->type;
2833         declaration->storage_class   = specifiers->storage_class;
2834         declaration->source_position = specifiers->source_position;
2835
2836         if (declaration->storage_class != STORAGE_CLASS_NONE) {
2837                 warningf(declaration->source_position, "useless storage class in empty declaration");
2838         }
2839
2840         type_t *type = declaration->type;
2841         switch (type->kind) {
2842                 case TYPE_COMPOUND_STRUCT:
2843                 case TYPE_COMPOUND_UNION: {
2844                         if (type->compound.declaration->symbol == NULL) {
2845                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
2846                         }
2847                         break;
2848                 }
2849
2850                 case TYPE_ENUM:
2851                         break;
2852
2853                 default:
2854                         warningf(declaration->source_position, "empty declaration");
2855                         break;
2856         }
2857
2858         finished_declaration(declaration);
2859 }
2860
2861 static void parse_declaration_rest(declaration_t *ndeclaration,
2862                 const declaration_specifiers_t *specifiers,
2863                 parsed_declaration_func finished_declaration)
2864 {
2865         while(true) {
2866                 declaration_t *declaration = finished_declaration(ndeclaration);
2867
2868                 type_t *orig_type = declaration->type;
2869                 type_t *type      = skip_typeref(orig_type);
2870
2871                 if (type->kind != TYPE_FUNCTION &&
2872                     declaration->is_inline &&
2873                     is_type_valid(type)) {
2874                         warningf(declaration->source_position,
2875                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2876                 }
2877
2878                 if(token.type == '=') {
2879                         parse_init_declarator_rest(declaration);
2880                 }
2881
2882                 if(token.type != ',')
2883                         break;
2884                 eat(',');
2885
2886                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2887         }
2888         expect_void(';');
2889 }
2890
2891 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2892 {
2893         symbol_t *symbol  = declaration->symbol;
2894         if(symbol == NULL) {
2895                 errorf(HERE, "anonymous declaration not valid as function parameter");
2896                 return declaration;
2897         }
2898         namespace_t namespc = (namespace_t) declaration->namespc;
2899         if(namespc != NAMESPACE_NORMAL) {
2900                 return record_declaration(declaration);
2901         }
2902
2903         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2904         if(previous_declaration == NULL ||
2905                         previous_declaration->parent_scope != scope) {
2906                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2907                        symbol);
2908                 return declaration;
2909         }
2910
2911         if(previous_declaration->type == NULL) {
2912                 previous_declaration->type          = declaration->type;
2913                 previous_declaration->storage_class = declaration->storage_class;
2914                 previous_declaration->parent_scope  = scope;
2915                 return previous_declaration;
2916         } else {
2917                 return record_declaration(declaration);
2918         }
2919 }
2920
2921 static void parse_declaration(parsed_declaration_func finished_declaration)
2922 {
2923         declaration_specifiers_t specifiers;
2924         memset(&specifiers, 0, sizeof(specifiers));
2925         parse_declaration_specifiers(&specifiers);
2926
2927         if(token.type == ';') {
2928                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
2929         } else {
2930                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2931                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2932         }
2933 }
2934
2935 static void parse_kr_declaration_list(declaration_t *declaration)
2936 {
2937         type_t *type = skip_typeref(declaration->type);
2938         if(!is_type_function(type))
2939                 return;
2940
2941         if(!type->function.kr_style_parameters)
2942                 return;
2943
2944         /* push function parameters */
2945         int       top        = environment_top();
2946         scope_t  *last_scope = scope;
2947         set_scope(&declaration->scope);
2948
2949         declaration_t *parameter = declaration->scope.declarations;
2950         for( ; parameter != NULL; parameter = parameter->next) {
2951                 assert(parameter->parent_scope == NULL);
2952                 parameter->parent_scope = scope;
2953                 environment_push(parameter);
2954         }
2955
2956         /* parse declaration list */
2957         while(is_declaration_specifier(&token, false)) {
2958                 parse_declaration(finished_kr_declaration);
2959         }
2960
2961         /* pop function parameters */
2962         assert(scope == &declaration->scope);
2963         set_scope(last_scope);
2964         environment_pop_to(top);
2965
2966         /* update function type */
2967         type_t *new_type = duplicate_type(type);
2968         new_type->function.kr_style_parameters = false;
2969
2970         function_parameter_t *parameters     = NULL;
2971         function_parameter_t *last_parameter = NULL;
2972
2973         declaration_t *parameter_declaration = declaration->scope.declarations;
2974         for( ; parameter_declaration != NULL;
2975                         parameter_declaration = parameter_declaration->next) {
2976                 type_t *parameter_type = parameter_declaration->type;
2977                 if(parameter_type == NULL) {
2978                         if (strict_mode) {
2979                                 errorf(HERE, "no type specified for function parameter '%Y'",
2980                                        parameter_declaration->symbol);
2981                         } else {
2982                                 if (warning.implicit_int) {
2983                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
2984                                                 parameter_declaration->symbol);
2985                                 }
2986                                 parameter_type              = type_int;
2987                                 parameter_declaration->type = parameter_type;
2988                         }
2989                 }
2990
2991                 semantic_parameter(parameter_declaration);
2992                 parameter_type = parameter_declaration->type;
2993
2994                 function_parameter_t *function_parameter
2995                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2996                 memset(function_parameter, 0, sizeof(function_parameter[0]));
2997
2998                 function_parameter->type = parameter_type;
2999                 if(last_parameter != NULL) {
3000                         last_parameter->next = function_parameter;
3001                 } else {
3002                         parameters = function_parameter;
3003                 }
3004                 last_parameter = function_parameter;
3005         }
3006         new_type->function.parameters = parameters;
3007
3008         type = typehash_insert(new_type);
3009         if(type != new_type) {
3010                 obstack_free(type_obst, new_type);
3011         }
3012
3013         declaration->type = type;
3014 }
3015
3016 static bool first_err = true;
3017
3018 /**
3019  * When called with first_err set, prints the name of the current function,
3020  * else does noting.
3021  */
3022 static void print_in_function(void) {
3023         if (first_err) {
3024                 first_err = false;
3025                 diagnosticf("%s: In function '%Y':\n",
3026                         current_function->source_position.input_name,
3027                         current_function->symbol);
3028         }
3029 }
3030
3031 /**
3032  * Check if all labels are defined in the current function.
3033  * Check if all labels are used in the current function.
3034  */
3035 static void check_labels(void)
3036 {
3037         for (const goto_statement_t *goto_statement = goto_first;
3038             goto_statement != NULL;
3039             goto_statement = goto_statement->next) {
3040                 declaration_t *label = goto_statement->label;
3041
3042                 label->used = true;
3043                 if (label->source_position.input_name == NULL) {
3044                         print_in_function();
3045                         errorf(goto_statement->base.source_position,
3046                                "label '%Y' used but not defined", label->symbol);
3047                  }
3048         }
3049         goto_first = goto_last = NULL;
3050
3051         if (warning.unused_label) {
3052                 for (const label_statement_t *label_statement = label_first;
3053                          label_statement != NULL;
3054                          label_statement = label_statement->next) {
3055                         const declaration_t *label = label_statement->label;
3056
3057                         if (! label->used) {
3058                                 print_in_function();
3059                                 warningf(label_statement->base.source_position,
3060                                         "label '%Y' defined but not used", label->symbol);
3061                         }
3062                 }
3063         }
3064         label_first = label_last = NULL;
3065 }
3066
3067 /**
3068  * Check declarations of current_function for unused entities.
3069  */
3070 static void check_declarations(void)
3071 {
3072         if (warning.unused_parameter) {
3073                 const scope_t *scope = &current_function->scope;
3074
3075                 const declaration_t *parameter = scope->declarations;
3076                 for (; parameter != NULL; parameter = parameter->next) {
3077                         if (! parameter->used) {
3078                                 print_in_function();
3079                                 warningf(parameter->source_position,
3080                                         "unused parameter '%Y'", parameter->symbol);
3081                         }
3082                 }
3083         }
3084         if (warning.unused_variable) {
3085         }
3086 }
3087
3088 static void parse_external_declaration(void)
3089 {
3090         /* function-definitions and declarations both start with declaration
3091          * specifiers */
3092         declaration_specifiers_t specifiers;
3093         memset(&specifiers, 0, sizeof(specifiers));
3094         parse_declaration_specifiers(&specifiers);
3095
3096         /* must be a declaration */
3097         if(token.type == ';') {
3098                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3099                 return;
3100         }
3101
3102         /* declarator is common to both function-definitions and declarations */
3103         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3104
3105         /* must be a declaration */
3106         if(token.type == ',' || token.type == '=' || token.type == ';') {
3107                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3108                 return;
3109         }
3110
3111         /* must be a function definition */
3112         parse_kr_declaration_list(ndeclaration);
3113
3114         if(token.type != '{') {
3115                 parse_error_expected("while parsing function definition", '{', 0);
3116                 eat_statement();
3117                 return;
3118         }
3119
3120         type_t *type = ndeclaration->type;
3121
3122         /* note that we don't skip typerefs: the standard doesn't allow them here
3123          * (so we can't use is_type_function here) */
3124         if(type->kind != TYPE_FUNCTION) {
3125                 if (is_type_valid(type)) {
3126                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
3127                                type, ndeclaration->symbol);
3128                 }
3129                 eat_block();
3130                 return;
3131         }
3132
3133         /* Â§ 6.7.5.3 (14) a function definition with () means no
3134          * parameters (and not unspecified parameters) */
3135         if(type->function.unspecified_parameters) {
3136                 type_t *duplicate = duplicate_type(type);
3137                 duplicate->function.unspecified_parameters = false;
3138
3139                 type = typehash_insert(duplicate);
3140                 if(type != duplicate) {
3141                         obstack_free(type_obst, duplicate);
3142                 }
3143                 ndeclaration->type = type;
3144         }
3145
3146         declaration_t *const declaration = record_function_definition(ndeclaration);
3147         if(ndeclaration != declaration) {
3148                 declaration->scope = ndeclaration->scope;
3149         }
3150         type = skip_typeref(declaration->type);
3151
3152         /* push function parameters and switch scope */
3153         int       top        = environment_top();
3154         scope_t  *last_scope = scope;
3155         set_scope(&declaration->scope);
3156
3157         declaration_t *parameter = declaration->scope.declarations;
3158         for( ; parameter != NULL; parameter = parameter->next) {
3159                 if(parameter->parent_scope == &ndeclaration->scope) {
3160                         parameter->parent_scope = scope;
3161                 }
3162                 assert(parameter->parent_scope == NULL
3163                                 || parameter->parent_scope == scope);
3164                 parameter->parent_scope = scope;
3165                 environment_push(parameter);
3166         }
3167
3168         if(declaration->init.statement != NULL) {
3169                 parser_error_multiple_definition(declaration, token.source_position);
3170                 eat_block();
3171                 goto end_of_parse_external_declaration;
3172         } else {
3173                 /* parse function body */
3174                 int            label_stack_top      = label_top();
3175                 declaration_t *old_current_function = current_function;
3176                 current_function                    = declaration;
3177
3178                 declaration->init.statement = parse_compound_statement();
3179                 first_err = true;
3180                 check_labels();
3181                 check_declarations();
3182
3183                 assert(current_function == declaration);
3184                 current_function = old_current_function;
3185                 label_pop_to(label_stack_top);
3186         }
3187
3188 end_of_parse_external_declaration:
3189         assert(scope == &declaration->scope);
3190         set_scope(last_scope);
3191         environment_pop_to(top);
3192 }
3193
3194 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3195                                   source_position_t source_position)
3196 {
3197         type_t *type        = allocate_type_zero(TYPE_BITFIELD, source_position);
3198         type->bitfield.base = base;
3199         type->bitfield.size = size;
3200
3201         return type;
3202 }
3203
3204 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3205                                           symbol_t *symbol)
3206 {
3207         declaration_t *iter = compound_declaration->scope.declarations;
3208         for( ; iter != NULL; iter = iter->next) {
3209                 if(iter->namespc != NAMESPACE_NORMAL)
3210                         continue;
3211
3212                 if(iter->symbol == NULL) {
3213                         type_t *type = skip_typeref(iter->type);
3214                         if(is_type_compound(type)) {
3215                                 declaration_t *result
3216                                         = find_compound_entry(type->compound.declaration, symbol);
3217                                 if(result != NULL)
3218                                         return result;
3219                         }
3220                         continue;
3221                 }
3222
3223                 if(iter->symbol == symbol) {
3224                         return iter;
3225                 }
3226         }
3227
3228         return NULL;
3229 }
3230
3231 static void parse_compound_declarators(declaration_t *struct_declaration,
3232                 const declaration_specifiers_t *specifiers)
3233 {
3234         declaration_t *last_declaration = struct_declaration->scope.declarations;
3235         if(last_declaration != NULL) {
3236                 while(last_declaration->next != NULL) {
3237                         last_declaration = last_declaration->next;
3238                 }
3239         }
3240
3241         while(1) {
3242                 declaration_t *declaration;
3243
3244                 if(token.type == ':') {
3245                         source_position_t source_position = HERE;
3246                         next_token();
3247
3248                         type_t *base_type = specifiers->type;
3249                         expression_t *size = parse_constant_expression();
3250
3251                         if(!is_type_integer(skip_typeref(base_type))) {
3252                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
3253                                        base_type);
3254                         }
3255
3256                         type_t *type = make_bitfield_type(base_type, size, source_position);
3257
3258                         declaration                  = allocate_declaration_zero();
3259                         declaration->namespc         = NAMESPACE_NORMAL;
3260                         declaration->storage_class   = STORAGE_CLASS_NONE;
3261                         declaration->source_position = source_position;
3262                         declaration->modifiers       = specifiers->decl_modifiers;
3263                         declaration->type            = type;
3264                 } else {
3265                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3266
3267                         type_t *orig_type = declaration->type;
3268                         type_t *type      = skip_typeref(orig_type);
3269
3270                         if(token.type == ':') {
3271                                 source_position_t source_position = HERE;
3272                                 next_token();
3273                                 expression_t *size = parse_constant_expression();
3274
3275                                 if(!is_type_integer(type)) {
3276                                         errorf(HERE, "bitfield base type '%T' is not an "
3277                                                "integer type", orig_type);
3278                                 }
3279
3280                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3281                                 declaration->type = bitfield_type;
3282                         } else {
3283                                 /* TODO we ignore arrays for now... what is missing is a check
3284                                  * that they're at the end of the struct */
3285                                 if(is_type_incomplete(type) && !is_type_array(type)) {
3286                                         errorf(HERE,
3287                                                "compound member '%Y' has incomplete type '%T'",
3288                                                declaration->symbol, orig_type);
3289                                 } else if(is_type_function(type)) {
3290                                         errorf(HERE, "compound member '%Y' must not have function "
3291                                                "type '%T'", declaration->symbol, orig_type);
3292                                 }
3293                         }
3294                 }
3295
3296                 /* make sure we don't define a symbol multiple times */
3297                 symbol_t *symbol = declaration->symbol;
3298                 if(symbol != NULL) {
3299                         declaration_t *prev_decl
3300                                 = find_compound_entry(struct_declaration, symbol);
3301
3302                         if(prev_decl != NULL) {
3303                                 assert(prev_decl->symbol == symbol);
3304                                 errorf(declaration->source_position,
3305                                        "multiple declarations of symbol '%Y'", symbol);
3306                                 errorf(prev_decl->source_position,
3307                                        "previous declaration of '%Y' was here", symbol);
3308                         }
3309                 }
3310
3311                 /* append declaration */
3312                 if(last_declaration != NULL) {
3313                         last_declaration->next = declaration;
3314                 } else {
3315                         struct_declaration->scope.declarations = declaration;
3316                 }
3317                 last_declaration = declaration;
3318
3319                 if(token.type != ',')
3320                         break;
3321                 next_token();
3322         }
3323         expect_void(';');
3324 }
3325
3326 static void parse_compound_type_entries(declaration_t *compound_declaration)
3327 {
3328         eat('{');
3329
3330         while(token.type != '}' && token.type != T_EOF) {
3331                 declaration_specifiers_t specifiers;
3332                 memset(&specifiers, 0, sizeof(specifiers));
3333                 parse_declaration_specifiers(&specifiers);
3334
3335                 parse_compound_declarators(compound_declaration, &specifiers);
3336         }
3337         if(token.type == T_EOF) {
3338                 errorf(HERE, "EOF while parsing struct");
3339         }
3340         next_token();
3341 }
3342
3343 static type_t *parse_typename(void)
3344 {
3345         declaration_specifiers_t specifiers;
3346         memset(&specifiers, 0, sizeof(specifiers));
3347         parse_declaration_specifiers(&specifiers);
3348         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
3349                 /* TODO: improve error message, user does probably not know what a
3350                  * storage class is...
3351                  */
3352                 errorf(HERE, "typename may not have a storage class");
3353         }
3354
3355         type_t *result = parse_abstract_declarator(specifiers.type);
3356
3357         return result;
3358 }
3359
3360
3361
3362
3363 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3364 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3365                                                           expression_t *left);
3366
3367 typedef struct expression_parser_function_t expression_parser_function_t;
3368 struct expression_parser_function_t {
3369         unsigned                         precedence;
3370         parse_expression_function        parser;
3371         unsigned                         infix_precedence;
3372         parse_expression_infix_function  infix_parser;
3373 };
3374
3375 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3376
3377 /**
3378  * Creates a new invalid expression.
3379  */
3380 static expression_t *create_invalid_expression(void)
3381 {
3382         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
3383         expression->base.source_position = token.source_position;
3384         return expression;
3385 }
3386
3387 /**
3388  * Prints an error message if an expression was expected but not read
3389  */
3390 static expression_t *expected_expression_error(void)
3391 {
3392         /* skip the error message if the error token was read */
3393         if (token.type != T_ERROR) {
3394                 errorf(HERE, "expected expression, got token '%K'", &token);
3395         }
3396         next_token();
3397
3398         return create_invalid_expression();
3399 }
3400
3401 /**
3402  * Parse a string constant.
3403  */
3404 static expression_t *parse_string_const(void)
3405 {
3406         wide_string_t wres;
3407         if (token.type == T_STRING_LITERAL) {
3408                 string_t res = token.v.string;
3409                 next_token();
3410                 while (token.type == T_STRING_LITERAL) {
3411                         res = concat_strings(&res, &token.v.string);
3412                         next_token();
3413                 }
3414                 if (token.type != T_WIDE_STRING_LITERAL) {
3415                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3416                         cnst->base.type    = type_char_ptr;
3417                         cnst->string.value = res;
3418                         return cnst;
3419                 }
3420
3421                 wres = concat_string_wide_string(&res, &token.v.wide_string);
3422         } else {
3423                 wres = token.v.wide_string;
3424         }
3425         next_token();
3426
3427         for (;;) {
3428                 switch (token.type) {
3429                         case T_WIDE_STRING_LITERAL:
3430                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
3431                                 break;
3432
3433                         case T_STRING_LITERAL:
3434                                 wres = concat_wide_string_string(&wres, &token.v.string);
3435                                 break;
3436
3437                         default: {
3438                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3439                                 cnst->base.type         = type_wchar_t_ptr;
3440                                 cnst->wide_string.value = wres;
3441                                 return cnst;
3442                         }
3443                 }
3444                 next_token();
3445         }
3446 }
3447
3448 /**
3449  * Parse an integer constant.
3450  */
3451 static expression_t *parse_int_const(void)
3452 {
3453         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3454         cnst->base.source_position = HERE;
3455         cnst->base.type            = token.datatype;
3456         cnst->conste.v.int_value   = token.v.intvalue;
3457
3458         next_token();
3459
3460         return cnst;
3461 }
3462
3463 /**
3464  * Parse a character constant.
3465  */
3466 static expression_t *parse_char_const(void)
3467 {
3468         expression_t *cnst         = allocate_expression_zero(EXPR_CHAR_CONST);
3469         cnst->base.source_position = HERE;
3470         cnst->base.type            = token.datatype;
3471         cnst->conste.v.chars.begin = token.v.string.begin;
3472         cnst->conste.v.chars.size  = token.v.string.size;
3473
3474         if (cnst->conste.v.chars.size != 1) {
3475                 if (warning.multichar && (c_mode & _GNUC)) {
3476                         /* TODO */
3477                         warningf(HERE, "multi-character character constant");
3478                 } else {
3479                         errorf(HERE, "more than 1 characters in character constant");
3480                 }
3481         }
3482         next_token();
3483
3484         return cnst;
3485 }
3486
3487 /**
3488  * Parse a float constant.
3489  */
3490 static expression_t *parse_float_const(void)
3491 {
3492         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3493         cnst->base.type            = token.datatype;
3494         cnst->conste.v.float_value = token.v.floatvalue;
3495
3496         next_token();
3497
3498         return cnst;
3499 }
3500
3501 static declaration_t *create_implicit_function(symbol_t *symbol,
3502                 const source_position_t source_position)
3503 {
3504         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
3505         ntype->function.return_type            = type_int;
3506         ntype->function.unspecified_parameters = true;
3507
3508         type_t *type = typehash_insert(ntype);
3509         if(type != ntype) {
3510                 free_type(ntype);
3511         }
3512
3513         declaration_t *const declaration = allocate_declaration_zero();
3514         declaration->storage_class   = STORAGE_CLASS_EXTERN;
3515         declaration->type            = type;
3516         declaration->symbol          = symbol;
3517         declaration->source_position = source_position;
3518         declaration->parent_scope  = global_scope;
3519
3520         scope_t *old_scope = scope;
3521         set_scope(global_scope);
3522
3523         environment_push(declaration);
3524         /* prepends the declaration to the global declarations list */
3525         declaration->next   = scope->declarations;
3526         scope->declarations = declaration;
3527
3528         assert(scope == global_scope);
3529         set_scope(old_scope);
3530
3531         return declaration;
3532 }
3533
3534 /**
3535  * Creates a return_type (func)(argument_type) function type if not
3536  * already exists.
3537  *
3538  * @param return_type    the return type
3539  * @param argument_type  the argument type
3540  */
3541 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3542 {
3543         function_parameter_t *parameter
3544                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3545         memset(parameter, 0, sizeof(parameter[0]));
3546         parameter->type = argument_type;
3547
3548         type_t *type               = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3549         type->function.return_type = return_type;
3550         type->function.parameters  = parameter;
3551
3552         type_t *result = typehash_insert(type);
3553         if(result != type) {
3554                 free_type(type);
3555         }
3556
3557         return result;
3558 }
3559
3560 /**
3561  * Creates a function type for some function like builtins.
3562  *
3563  * @param symbol   the symbol describing the builtin
3564  */
3565 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3566 {
3567         switch(symbol->ID) {
3568         case T___builtin_alloca:
3569                 return make_function_1_type(type_void_ptr, type_size_t);
3570         case T___builtin_nan:
3571                 return make_function_1_type(type_double, type_char_ptr);
3572         case T___builtin_nanf:
3573                 return make_function_1_type(type_float, type_char_ptr);
3574         case T___builtin_nand:
3575                 return make_function_1_type(type_long_double, type_char_ptr);
3576         case T___builtin_va_end:
3577                 return make_function_1_type(type_void, type_valist);
3578         default:
3579                 panic("not implemented builtin symbol found");
3580         }
3581 }
3582
3583 /**
3584  * Performs automatic type cast as described in Â§ 6.3.2.1.
3585  *
3586  * @param orig_type  the original type
3587  */
3588 static type_t *automatic_type_conversion(type_t *orig_type)
3589 {
3590         type_t *type = skip_typeref(orig_type);
3591         if(is_type_array(type)) {
3592                 array_type_t *array_type   = &type->array;
3593                 type_t       *element_type = array_type->element_type;
3594                 unsigned      qualifiers   = array_type->type.qualifiers;
3595
3596                 return make_pointer_type(element_type, qualifiers);
3597         }
3598
3599         if(is_type_function(type)) {
3600                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3601         }
3602
3603         return orig_type;
3604 }
3605
3606 /**
3607  * reverts the automatic casts of array to pointer types and function
3608  * to function-pointer types as defined Â§ 6.3.2.1
3609  */
3610 type_t *revert_automatic_type_conversion(const expression_t *expression)
3611 {
3612         switch (expression->kind) {
3613                 case EXPR_REFERENCE: return expression->reference.declaration->type;
3614                 case EXPR_SELECT:    return expression->select.compound_entry->type;
3615
3616                 case EXPR_UNARY_DEREFERENCE: {
3617                         const expression_t *const value = expression->unary.value;
3618                         type_t             *const type  = skip_typeref(value->base.type);
3619                         assert(is_type_pointer(type));
3620                         return type->pointer.points_to;
3621                 }
3622
3623                 case EXPR_BUILTIN_SYMBOL:
3624                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3625
3626                 case EXPR_ARRAY_ACCESS: {
3627                         const expression_t *array_ref = expression->array_access.array_ref;
3628                         type_t             *type_left = skip_typeref(array_ref->base.type);
3629                         if (!is_type_valid(type_left))
3630                                 return type_left;
3631                         assert(is_type_pointer(type_left));
3632                         return type_left->pointer.points_to;
3633                 }
3634
3635                 default: break;
3636         }
3637
3638         return expression->base.type;
3639 }
3640
3641 static expression_t *parse_reference(void)
3642 {
3643         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3644
3645         reference_expression_t *ref = &expression->reference;
3646         ref->symbol = token.v.symbol;
3647
3648         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3649
3650         source_position_t source_position = token.source_position;
3651         next_token();
3652
3653         if(declaration == NULL) {
3654                 if (! strict_mode && token.type == '(') {
3655                         /* an implicitly defined function */
3656                         if (warning.implicit_function_declaration) {
3657                                 warningf(HERE, "implicit declaration of function '%Y'",
3658                                         ref->symbol);
3659                         }
3660
3661                         declaration = create_implicit_function(ref->symbol,
3662                                                                source_position);
3663                 } else {
3664                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3665                         return create_invalid_expression();
3666                 }
3667         }
3668
3669         type_t *type         = declaration->type;
3670
3671         /* we always do the auto-type conversions; the & and sizeof parser contains
3672          * code to revert this! */
3673         type = automatic_type_conversion(type);
3674
3675         ref->declaration = declaration;
3676         ref->base.type   = type;
3677
3678         /* this declaration is used */
3679         declaration->used = true;
3680
3681         return expression;
3682 }
3683
3684 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3685 {
3686         (void) expression;
3687         (void) dest_type;
3688         /* TODO check if explicit cast is allowed and issue warnings/errors */
3689 }
3690
3691 static expression_t *parse_compound_literal(type_t *type)
3692 {
3693         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
3694
3695         expression->compound_literal.type        = type;
3696         expression->compound_literal.initializer = parse_initializer(type);
3697         expression->base.type                    = automatic_type_conversion(type);
3698
3699         return expression;
3700 }
3701
3702 static expression_t *parse_cast(void)
3703 {
3704         source_position_t source_position = token.source_position;
3705
3706         type_t *type  = parse_typename();
3707
3708         expect(')');
3709
3710         if(token.type == '{') {
3711                 return parse_compound_literal(type);
3712         }
3713
3714         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3715         cast->base.source_position = source_position;
3716
3717         expression_t *value = parse_sub_expression(20);
3718
3719         check_cast_allowed(value, type);
3720
3721         cast->base.type   = type;
3722         cast->unary.value = value;
3723
3724         return cast;
3725 }
3726
3727 static expression_t *parse_statement_expression(void)
3728 {
3729         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3730
3731         statement_t *statement           = parse_compound_statement();
3732         expression->statement.statement  = statement;
3733         expression->base.source_position = statement->base.source_position;
3734
3735         /* find last statement and use its type */
3736         type_t *type = type_void;
3737         const statement_t *stmt = statement->compound.statements;
3738         if (stmt != NULL) {
3739                 while (stmt->base.next != NULL)
3740                         stmt = stmt->base.next;
3741
3742                 if (stmt->kind == STATEMENT_EXPRESSION) {
3743                         type = stmt->expression.expression->base.type;
3744                 }
3745         } else {
3746                 warningf(expression->base.source_position, "empty statement expression ({})");
3747         }
3748         expression->base.type = type;
3749
3750         expect(')');
3751
3752         return expression;
3753 }
3754
3755 static expression_t *parse_brace_expression(void)
3756 {
3757         eat('(');
3758
3759         switch(token.type) {
3760         case '{':
3761                 /* gcc extension: a statement expression */
3762                 return parse_statement_expression();
3763
3764         TYPE_QUALIFIERS
3765         TYPE_SPECIFIERS
3766                 return parse_cast();
3767         case T_IDENTIFIER:
3768                 if(is_typedef_symbol(token.v.symbol)) {
3769                         return parse_cast();
3770                 }
3771         }
3772
3773         expression_t *result = parse_expression();
3774         expect(')');
3775
3776         return result;
3777 }
3778
3779 static expression_t *parse_function_keyword(void)
3780 {
3781         next_token();
3782         /* TODO */
3783
3784         if (current_function == NULL) {
3785                 errorf(HERE, "'__func__' used outside of a function");
3786         }
3787
3788         expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
3789         expression->base.type    = type_char_ptr;
3790
3791         return expression;
3792 }
3793
3794 static expression_t *parse_pretty_function_keyword(void)
3795 {
3796         eat(T___PRETTY_FUNCTION__);
3797         /* TODO */
3798
3799         if (current_function == NULL) {
3800                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3801         }
3802
3803         expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
3804         expression->base.type    = type_char_ptr;
3805
3806         return expression;
3807 }
3808
3809 static designator_t *parse_designator(void)
3810 {
3811         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
3812         result->source_position = HERE;
3813
3814         if(token.type != T_IDENTIFIER) {
3815                 parse_error_expected("while parsing member designator",
3816                                      T_IDENTIFIER, 0);
3817                 eat_paren();
3818                 return NULL;
3819         }
3820         result->symbol = token.v.symbol;
3821         next_token();
3822
3823         designator_t *last_designator = result;
3824         while(true) {
3825                 if(token.type == '.') {
3826                         next_token();
3827                         if(token.type != T_IDENTIFIER) {
3828                                 parse_error_expected("while parsing member designator",
3829                                                      T_IDENTIFIER, 0);
3830                                 eat_paren();
3831                                 return NULL;
3832                         }
3833                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3834                         designator->source_position = HERE;
3835                         designator->symbol          = token.v.symbol;
3836                         next_token();
3837
3838                         last_designator->next = designator;
3839                         last_designator       = designator;
3840                         continue;
3841                 }
3842                 if(token.type == '[') {
3843                         next_token();
3844                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3845                         designator->source_position = HERE;
3846                         designator->array_index     = parse_expression();
3847                         if(designator->array_index == NULL) {
3848                                 eat_paren();
3849                                 return NULL;
3850                         }
3851                         expect(']');
3852
3853                         last_designator->next = designator;
3854                         last_designator       = designator;
3855                         continue;
3856                 }
3857                 break;
3858         }
3859
3860         return result;
3861 }
3862
3863 static expression_t *parse_offsetof(void)
3864 {
3865         eat(T___builtin_offsetof);
3866
3867         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
3868         expression->base.type    = type_size_t;
3869
3870         expect('(');
3871         type_t *type = parse_typename();
3872         expect(',');
3873         designator_t *designator = parse_designator();
3874         expect(')');
3875
3876         expression->offsetofe.type       = type;
3877         expression->offsetofe.designator = designator;
3878
3879         type_path_t path;
3880         memset(&path, 0, sizeof(path));
3881         path.top_type = type;
3882         path.path     = NEW_ARR_F(type_path_entry_t, 0);
3883
3884         descend_into_subtype(&path);
3885
3886         if(!walk_designator(&path, designator, true)) {
3887                 return create_invalid_expression();
3888         }
3889
3890         DEL_ARR_F(path.path);
3891
3892         return expression;
3893 }
3894
3895 static expression_t *parse_va_start(void)
3896 {
3897         eat(T___builtin_va_start);
3898
3899         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3900
3901         expect('(');
3902         expression->va_starte.ap = parse_assignment_expression();
3903         expect(',');
3904         expression_t *const expr = parse_assignment_expression();
3905         if (expr->kind == EXPR_REFERENCE) {
3906                 declaration_t *const decl = expr->reference.declaration;
3907                 if (decl == NULL)
3908                         return create_invalid_expression();
3909                 if (decl->parent_scope == &current_function->scope &&
3910                     decl->next == NULL) {
3911                         expression->va_starte.parameter = decl;
3912                         expect(')');
3913                         return expression;
3914                 }
3915         }
3916         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3917
3918         return create_invalid_expression();
3919 }
3920
3921 static expression_t *parse_va_arg(void)
3922 {
3923         eat(T___builtin_va_arg);
3924
3925         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3926
3927         expect('(');
3928         expression->va_arge.ap = parse_assignment_expression();
3929         expect(',');
3930         expression->base.type = parse_typename();
3931         expect(')');
3932
3933         return expression;
3934 }
3935
3936 static expression_t *parse_builtin_symbol(void)
3937 {
3938         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3939
3940         symbol_t *symbol = token.v.symbol;
3941
3942         expression->builtin_symbol.symbol = symbol;
3943         next_token();
3944
3945         type_t *type = get_builtin_symbol_type(symbol);
3946         type = automatic_type_conversion(type);
3947
3948         expression->base.type = type;
3949         return expression;
3950 }
3951
3952 static expression_t *parse_builtin_constant(void)
3953 {
3954         eat(T___builtin_constant_p);
3955
3956         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3957
3958         expect('(');
3959         expression->builtin_constant.value = parse_assignment_expression();
3960         expect(')');
3961         expression->base.type = type_int;
3962
3963         return expression;
3964 }
3965
3966 static expression_t *parse_builtin_prefetch(void)
3967 {
3968         eat(T___builtin_prefetch);
3969
3970         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3971
3972         expect('(');
3973         expression->builtin_prefetch.adr = parse_assignment_expression();
3974         if (token.type == ',') {
3975                 next_token();
3976                 expression->builtin_prefetch.rw = parse_assignment_expression();
3977         }
3978         if (token.type == ',') {
3979                 next_token();
3980                 expression->builtin_prefetch.locality = parse_assignment_expression();
3981         }
3982         expect(')');
3983         expression->base.type = type_void;
3984
3985         return expression;
3986 }
3987
3988 static expression_t *parse_compare_builtin(void)
3989 {
3990         expression_t *expression;
3991
3992         switch(token.type) {
3993         case T___builtin_isgreater:
3994                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3995                 break;
3996         case T___builtin_isgreaterequal:
3997                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3998                 break;
3999         case T___builtin_isless:
4000                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4001                 break;
4002         case T___builtin_islessequal:
4003                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4004                 break;
4005         case T___builtin_islessgreater:
4006                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4007                 break;
4008         case T___builtin_isunordered:
4009                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4010                 break;
4011         default:
4012                 panic("invalid compare builtin found");
4013                 break;
4014         }
4015         expression->base.source_position = HERE;
4016         next_token();
4017
4018         expect('(');
4019         expression->binary.left = parse_assignment_expression();
4020         expect(',');
4021         expression->binary.right = parse_assignment_expression();
4022         expect(')');
4023
4024         type_t *const orig_type_left  = expression->binary.left->base.type;
4025         type_t *const orig_type_right = expression->binary.right->base.type;
4026
4027         type_t *const type_left  = skip_typeref(orig_type_left);
4028         type_t *const type_right = skip_typeref(orig_type_right);
4029         if(!is_type_float(type_left) && !is_type_float(type_right)) {
4030                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4031                         type_error_incompatible("invalid operands in comparison",
4032                                 expression->base.source_position, orig_type_left, orig_type_right);
4033                 }
4034         } else {
4035                 semantic_comparison(&expression->binary);
4036         }
4037
4038         return expression;
4039 }
4040
4041 static expression_t *parse_builtin_expect(void)
4042 {
4043         eat(T___builtin_expect);
4044
4045         expression_t *expression
4046                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4047
4048         expect('(');
4049         expression->binary.left = parse_assignment_expression();
4050         expect(',');
4051         expression->binary.right = parse_constant_expression();
4052         expect(')');
4053
4054         expression->base.type = expression->binary.left->base.type;
4055
4056         return expression;
4057 }
4058
4059 static expression_t *parse_assume(void) {
4060         eat(T_assume);
4061
4062         expression_t *expression
4063                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4064
4065         expect('(');
4066         expression->unary.value = parse_assignment_expression();
4067         expect(')');
4068
4069         expression->base.type = type_void;
4070         return expression;
4071 }
4072
4073 static expression_t *parse_primary_expression(void)
4074 {
4075         switch (token.type) {
4076                 case T_INTEGER:                  return parse_int_const();
4077                 case T_CHARS:                    return parse_char_const();
4078                 case T_FLOATINGPOINT:            return parse_float_const();
4079                 case T_STRING_LITERAL:
4080                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
4081                 case T_IDENTIFIER:               return parse_reference();
4082                 case T___FUNCTION__:
4083                 case T___func__:                 return parse_function_keyword();
4084                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
4085                 case T___builtin_offsetof:       return parse_offsetof();
4086                 case T___builtin_va_start:       return parse_va_start();
4087                 case T___builtin_va_arg:         return parse_va_arg();
4088                 case T___builtin_expect:         return parse_builtin_expect();
4089                 case T___builtin_alloca:
4090                 case T___builtin_nan:
4091                 case T___builtin_nand:
4092                 case T___builtin_nanf:
4093                 case T___builtin_va_end:         return parse_builtin_symbol();
4094                 case T___builtin_isgreater:
4095                 case T___builtin_isgreaterequal:
4096                 case T___builtin_isless:
4097                 case T___builtin_islessequal:
4098                 case T___builtin_islessgreater:
4099                 case T___builtin_isunordered:    return parse_compare_builtin();
4100                 case T___builtin_constant_p:     return parse_builtin_constant();
4101                 case T___builtin_prefetch:       return parse_builtin_prefetch();
4102                 case T_assume:                   return parse_assume();
4103
4104                 case '(':                        return parse_brace_expression();
4105         }
4106
4107         errorf(HERE, "unexpected token %K, expected an expression", &token);
4108         eat_statement();
4109
4110         return create_invalid_expression();
4111 }
4112
4113 /**
4114  * Check if the expression has the character type and issue a warning then.
4115  */
4116 static void check_for_char_index_type(const expression_t *expression) {
4117         type_t       *const type      = expression->base.type;
4118         const type_t *const base_type = skip_typeref(type);
4119
4120         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4121                         warning.char_subscripts) {
4122                 warningf(expression->base.source_position,
4123                         "array subscript has type '%T'", type);
4124         }
4125 }
4126
4127 static expression_t *parse_array_expression(unsigned precedence,
4128                                             expression_t *left)
4129 {
4130         (void) precedence;
4131
4132         eat('[');
4133
4134         expression_t *inside = parse_expression();
4135
4136         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4137
4138         array_access_expression_t *array_access = &expression->array_access;
4139
4140         type_t *const orig_type_left   = left->base.type;
4141         type_t *const orig_type_inside = inside->base.type;
4142
4143         type_t *const type_left   = skip_typeref(orig_type_left);
4144         type_t *const type_inside = skip_typeref(orig_type_inside);
4145
4146         type_t *return_type;
4147         if (is_type_pointer(type_left)) {
4148                 return_type             = type_left->pointer.points_to;
4149                 array_access->array_ref = left;
4150                 array_access->index     = inside;
4151                 check_for_char_index_type(inside);
4152         } else if (is_type_pointer(type_inside)) {
4153                 return_type             = type_inside->pointer.points_to;
4154                 array_access->array_ref = inside;
4155                 array_access->index     = left;
4156                 array_access->flipped   = true;
4157                 check_for_char_index_type(left);
4158         } else {
4159                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4160                         errorf(HERE,
4161                                 "array access on object with non-pointer types '%T', '%T'",
4162                                 orig_type_left, orig_type_inside);
4163                 }
4164                 return_type             = type_error_type;
4165                 array_access->array_ref = create_invalid_expression();
4166         }
4167
4168         if(token.type != ']') {
4169                 parse_error_expected("Problem while parsing array access", ']', 0);
4170                 return expression;
4171         }
4172         next_token();
4173
4174         return_type           = automatic_type_conversion(return_type);
4175         expression->base.type = return_type;
4176
4177         return expression;
4178 }
4179
4180 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4181 {
4182         expression_t *tp_expression = allocate_expression_zero(kind);
4183         tp_expression->base.type    = type_size_t;
4184
4185         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4186                 next_token();
4187                 tp_expression->typeprop.type = parse_typename();
4188                 expect(')');
4189         } else {
4190                 expression_t *expression = parse_sub_expression(precedence);
4191                 expression->base.type    = revert_automatic_type_conversion(expression);
4192
4193                 tp_expression->typeprop.type          = expression->base.type;
4194                 tp_expression->typeprop.tp_expression = expression;
4195         }
4196
4197         return tp_expression;
4198 }
4199
4200 static expression_t *parse_sizeof(unsigned precedence)
4201 {
4202         eat(T_sizeof);
4203         return parse_typeprop(EXPR_SIZEOF, precedence);
4204 }
4205
4206 static expression_t *parse_alignof(unsigned precedence)
4207 {
4208         eat(T___alignof__);
4209         return parse_typeprop(EXPR_SIZEOF, precedence);
4210 }
4211
4212 static expression_t *parse_select_expression(unsigned precedence,
4213                                              expression_t *compound)
4214 {
4215         (void) precedence;
4216         assert(token.type == '.' || token.type == T_MINUSGREATER);
4217
4218         bool is_pointer = (token.type == T_MINUSGREATER);
4219         next_token();
4220
4221         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
4222         select->select.compound = compound;
4223
4224         if(token.type != T_IDENTIFIER) {
4225                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4226                 return select;
4227         }
4228         symbol_t *symbol      = token.v.symbol;
4229         select->select.symbol = symbol;
4230         next_token();
4231
4232         type_t *const orig_type = compound->base.type;
4233         type_t *const type      = skip_typeref(orig_type);
4234
4235         type_t *type_left = type;
4236         if(is_pointer) {
4237                 if (!is_type_pointer(type)) {
4238                         if (is_type_valid(type)) {
4239                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4240                         }
4241                         return create_invalid_expression();
4242                 }
4243                 type_left = type->pointer.points_to;
4244         }
4245         type_left = skip_typeref(type_left);
4246
4247         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4248             type_left->kind != TYPE_COMPOUND_UNION) {
4249                 if (is_type_valid(type_left)) {
4250                         errorf(HERE, "request for member '%Y' in something not a struct or "
4251                                "union, but '%T'", symbol, type_left);
4252                 }
4253                 return create_invalid_expression();
4254         }
4255
4256         declaration_t *const declaration = type_left->compound.declaration;
4257
4258         if(!declaration->init.is_defined) {
4259                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4260                        symbol, type_left);
4261                 return create_invalid_expression();
4262         }
4263
4264         declaration_t *iter = find_compound_entry(declaration, symbol);
4265         if(iter == NULL) {
4266                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4267                 return create_invalid_expression();
4268         }
4269
4270         /* we always do the auto-type conversions; the & and sizeof parser contains
4271          * code to revert this! */
4272         type_t *expression_type = automatic_type_conversion(iter->type);
4273
4274         select->select.compound_entry = iter;
4275         select->base.type             = expression_type;
4276
4277         if(expression_type->kind == TYPE_BITFIELD) {
4278                 expression_t *extract
4279                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4280                 extract->unary.value = select;
4281                 extract->base.type   = expression_type->bitfield.base;
4282
4283                 return extract;
4284         }
4285
4286         return select;
4287 }
4288
4289 /**
4290  * Parse a call expression, ie. expression '( ... )'.
4291  *
4292  * @param expression  the function address
4293  */
4294 static expression_t *parse_call_expression(unsigned precedence,
4295                                            expression_t *expression)
4296 {
4297         (void) precedence;
4298         expression_t *result = allocate_expression_zero(EXPR_CALL);
4299
4300         call_expression_t *call = &result->call;
4301         call->function          = expression;
4302
4303         type_t *const orig_type = expression->base.type;
4304         type_t *const type      = skip_typeref(orig_type);
4305
4306         function_type_t *function_type = NULL;
4307         if (is_type_pointer(type)) {
4308                 type_t *const to_type = skip_typeref(type->pointer.points_to);
4309
4310                 if (is_type_function(to_type)) {
4311                         function_type   = &to_type->function;
4312                         call->base.type = function_type->return_type;
4313                 }
4314         }
4315
4316         if (function_type == NULL && is_type_valid(type)) {
4317                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4318         }
4319
4320         /* parse arguments */
4321         eat('(');
4322
4323         if(token.type != ')') {
4324                 call_argument_t *last_argument = NULL;
4325
4326                 while(true) {
4327                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4328
4329                         argument->expression = parse_assignment_expression();
4330                         if(last_argument == NULL) {
4331                                 call->arguments = argument;
4332                         } else {
4333                                 last_argument->next = argument;
4334                         }
4335                         last_argument = argument;
4336
4337                         if(token.type != ',')
4338                                 break;
4339                         next_token();
4340                 }
4341         }
4342         expect(')');
4343
4344         if(function_type != NULL) {
4345                 function_parameter_t *parameter = function_type->parameters;
4346                 call_argument_t      *argument  = call->arguments;
4347                 for( ; parameter != NULL && argument != NULL;
4348                                 parameter = parameter->next, argument = argument->next) {
4349                         type_t *expected_type = parameter->type;
4350                         /* TODO report scope in error messages */
4351                         expression_t *const arg_expr = argument->expression;
4352                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4353                         if (res_type == NULL) {
4354                                 /* TODO improve error message */
4355                                 errorf(arg_expr->base.source_position,
4356                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4357                                         arg_expr, arg_expr->base.type, expected_type);
4358                         } else {
4359                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
4360                         }
4361                 }
4362                 /* too few parameters */
4363                 if(parameter != NULL) {
4364                         errorf(HERE, "too few arguments to function '%E'", expression);
4365                 } else if(argument != NULL) {
4366                         /* too many parameters */
4367                         if(!function_type->variadic
4368                                         && !function_type->unspecified_parameters) {
4369                                 errorf(HERE, "too many arguments to function '%E'", expression);
4370                         } else {
4371                                 /* do default promotion */
4372                                 for( ; argument != NULL; argument = argument->next) {
4373                                         type_t *type = argument->expression->base.type;
4374
4375                                         type = skip_typeref(type);
4376                                         if(is_type_integer(type)) {
4377                                                 type = promote_integer(type);
4378                                         } else if(type == type_float) {
4379                                                 type = type_double;
4380                                         }
4381
4382                                         argument->expression
4383                                                 = create_implicit_cast(argument->expression, type);
4384                                 }
4385
4386                                 check_format(&result->call);
4387                         }
4388                 } else {
4389                         check_format(&result->call);
4390                 }
4391         }
4392
4393         return result;
4394 }
4395
4396 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4397
4398 static bool same_compound_type(const type_t *type1, const type_t *type2)
4399 {
4400         return
4401                 is_type_compound(type1) &&
4402                 type1->kind == type2->kind &&
4403                 type1->compound.declaration == type2->compound.declaration;
4404 }
4405
4406 /**
4407  * Parse a conditional expression, ie. 'expression ? ... : ...'.
4408  *
4409  * @param expression  the conditional expression
4410  */
4411 static expression_t *parse_conditional_expression(unsigned precedence,
4412                                                   expression_t *expression)
4413 {
4414         eat('?');
4415
4416         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4417
4418         conditional_expression_t *conditional = &result->conditional;
4419         conditional->condition = expression;
4420
4421         /* 6.5.15.2 */
4422         type_t *const condition_type_orig = expression->base.type;
4423         type_t *const condition_type      = skip_typeref(condition_type_orig);
4424         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4425                 type_error("expected a scalar type in conditional condition",
4426                            expression->base.source_position, condition_type_orig);
4427         }
4428
4429         expression_t *true_expression = parse_expression();
4430         expect(':');
4431         expression_t *false_expression = parse_sub_expression(precedence);
4432
4433         type_t *const orig_true_type  = true_expression->base.type;
4434         type_t *const orig_false_type = false_expression->base.type;
4435         type_t *const true_type       = skip_typeref(orig_true_type);
4436         type_t *const false_type      = skip_typeref(orig_false_type);
4437
4438         /* 6.5.15.3 */
4439         type_t *result_type;
4440         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4441                 result_type = semantic_arithmetic(true_type, false_type);
4442
4443                 true_expression  = create_implicit_cast(true_expression, result_type);
4444                 false_expression = create_implicit_cast(false_expression, result_type);
4445
4446                 conditional->true_expression  = true_expression;
4447                 conditional->false_expression = false_expression;
4448                 conditional->base.type        = result_type;
4449         } else if (same_compound_type(true_type, false_type) || (
4450             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4451             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4452                 )) {
4453                 /* just take 1 of the 2 types */
4454                 result_type = true_type;
4455         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4456                         && pointers_compatible(true_type, false_type)) {
4457                 /* ok */
4458                 result_type = true_type;
4459         } else if (is_type_pointer(true_type)
4460                         && is_null_pointer_constant(false_expression)) {
4461                 result_type = true_type;
4462         } else if (is_type_pointer(false_type)
4463                         && is_null_pointer_constant(true_expression)) {
4464                 result_type = false_type;
4465         } else {
4466                 /* TODO: one pointer to void*, other some pointer */
4467
4468                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4469                         type_error_incompatible("while parsing conditional",
4470                                                 expression->base.source_position, true_type,
4471                                                 false_type);
4472                 }
4473                 result_type = type_error_type;
4474         }
4475
4476         conditional->true_expression
4477                 = create_implicit_cast(true_expression, result_type);
4478         conditional->false_expression
4479                 = create_implicit_cast(false_expression, result_type);
4480         conditional->base.type = result_type;
4481         return result;
4482 }
4483
4484 /**
4485  * Parse an extension expression.
4486  */
4487 static expression_t *parse_extension(unsigned precedence)
4488 {
4489         eat(T___extension__);
4490
4491         /* TODO enable extensions */
4492         expression_t *expression = parse_sub_expression(precedence);
4493         /* TODO disable extensions */
4494         return expression;
4495 }
4496
4497 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4498 {
4499         eat(T___builtin_classify_type);
4500
4501         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4502         result->base.type    = type_int;
4503
4504         expect('(');
4505         expression_t *expression = parse_sub_expression(precedence);
4506         expect(')');
4507         result->classify_type.type_expression = expression;
4508
4509         return result;
4510 }
4511
4512 static void semantic_incdec(unary_expression_t *expression)
4513 {
4514         type_t *const orig_type = expression->value->base.type;
4515         type_t *const type      = skip_typeref(orig_type);
4516         /* TODO !is_type_real && !is_type_pointer */
4517         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4518                 if (is_type_valid(type)) {
4519                         /* TODO: improve error message */
4520                         errorf(HERE, "operation needs an arithmetic or pointer type");
4521                 }
4522                 return;
4523         }
4524
4525         expression->base.type = orig_type;
4526 }
4527
4528 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4529 {
4530         type_t *const orig_type = expression->value->base.type;
4531         type_t *const type      = skip_typeref(orig_type);
4532         if(!is_type_arithmetic(type)) {
4533                 if (is_type_valid(type)) {
4534                         /* TODO: improve error message */
4535                         errorf(HERE, "operation needs an arithmetic type");
4536                 }
4537                 return;
4538         }
4539
4540         expression->base.type = orig_type;
4541 }
4542
4543 static void semantic_unexpr_scalar(unary_expression_t *expression)
4544 {
4545         type_t *const orig_type = expression->value->base.type;
4546         type_t *const type      = skip_typeref(orig_type);
4547         if (!is_type_scalar(type)) {
4548                 if (is_type_valid(type)) {
4549                         errorf(HERE, "operand of ! must be of scalar type");
4550                 }
4551                 return;
4552         }
4553
4554         expression->base.type = orig_type;
4555 }
4556
4557 static void semantic_unexpr_integer(unary_expression_t *expression)
4558 {
4559         type_t *const orig_type = expression->value->base.type;
4560         type_t *const type      = skip_typeref(orig_type);
4561         if (!is_type_integer(type)) {
4562                 if (is_type_valid(type)) {
4563                         errorf(HERE, "operand of ~ must be of integer type");
4564                 }
4565                 return;
4566         }
4567
4568         expression->base.type = orig_type;
4569 }
4570
4571 static void semantic_dereference(unary_expression_t *expression)
4572 {
4573         type_t *const orig_type = expression->value->base.type;
4574         type_t *const type      = skip_typeref(orig_type);
4575         if(!is_type_pointer(type)) {
4576                 if (is_type_valid(type)) {
4577                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4578                 }
4579                 return;
4580         }
4581
4582         type_t *result_type   = type->pointer.points_to;
4583         result_type           = automatic_type_conversion(result_type);
4584         expression->base.type = result_type;
4585 }
4586
4587 /**
4588  * Check the semantic of the address taken expression.
4589  */
4590 static void semantic_take_addr(unary_expression_t *expression)
4591 {
4592         expression_t *value = expression->value;
4593         value->base.type    = revert_automatic_type_conversion(value);
4594
4595         type_t *orig_type = value->base.type;
4596         if(!is_type_valid(orig_type))
4597                 return;
4598
4599         if(value->kind == EXPR_REFERENCE) {
4600                 declaration_t *const declaration = value->reference.declaration;
4601                 if(declaration != NULL) {
4602                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4603                                 errorf(expression->base.source_position,
4604                                         "address of register variable '%Y' requested",
4605                                         declaration->symbol);
4606                         }
4607                         declaration->address_taken = 1;
4608                 }
4609         }
4610
4611         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4612 }
4613
4614 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4615 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4616 {                                                                              \
4617         eat(token_type);                                                           \
4618                                                                                    \
4619         expression_t *unary_expression                                             \
4620                 = allocate_expression_zero(unexpression_type);                         \
4621         unary_expression->base.source_position = HERE;                             \
4622         unary_expression->unary.value = parse_sub_expression(precedence);          \
4623                                                                                    \
4624         sfunc(&unary_expression->unary);                                           \
4625                                                                                    \
4626         return unary_expression;                                                   \
4627 }
4628
4629 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4630                                semantic_unexpr_arithmetic)
4631 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4632                                semantic_unexpr_arithmetic)
4633 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4634                                semantic_unexpr_scalar)
4635 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4636                                semantic_dereference)
4637 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4638                                semantic_take_addr)
4639 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4640                                semantic_unexpr_integer)
4641 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4642                                semantic_incdec)
4643 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4644                                semantic_incdec)
4645
4646 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4647                                                sfunc)                         \
4648 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4649                                                expression_t *left)            \
4650 {                                                                             \
4651         (void) precedence;                                                        \
4652         eat(token_type);                                                          \
4653                                                                               \
4654         expression_t *unary_expression                                            \
4655                 = allocate_expression_zero(unexpression_type);                        \
4656         unary_expression->unary.value = left;                                     \
4657                                                                                   \
4658         sfunc(&unary_expression->unary);                                          \
4659                                                                               \
4660         return unary_expression;                                                  \
4661 }
4662
4663 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4664                                        EXPR_UNARY_POSTFIX_INCREMENT,
4665                                        semantic_incdec)
4666 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4667                                        EXPR_UNARY_POSTFIX_DECREMENT,
4668                                        semantic_incdec)
4669
4670 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4671 {
4672         /* TODO: handle complex + imaginary types */
4673
4674         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4675         if(type_left == type_long_double || type_right == type_long_double) {
4676                 return type_long_double;
4677         } else if(type_left == type_double || type_right == type_double) {
4678                 return type_double;
4679         } else if(type_left == type_float || type_right == type_float) {
4680                 return type_float;
4681         }
4682
4683         type_right = promote_integer(type_right);
4684         type_left  = promote_integer(type_left);
4685
4686         if(type_left == type_right)
4687                 return type_left;
4688
4689         bool signed_left  = is_type_signed(type_left);
4690         bool signed_right = is_type_signed(type_right);
4691         int  rank_left    = get_rank(type_left);
4692         int  rank_right   = get_rank(type_right);
4693         if(rank_left < rank_right) {
4694                 if(signed_left == signed_right || !signed_right) {
4695                         return type_right;
4696                 } else {
4697                         return type_left;
4698                 }
4699         } else {
4700                 if(signed_left == signed_right || !signed_left) {
4701                         return type_left;
4702                 } else {
4703                         return type_right;
4704                 }
4705         }
4706 }
4707
4708 /**
4709  * Check the semantic restrictions for a binary expression.
4710  */
4711 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4712 {
4713         expression_t *const left            = expression->left;
4714         expression_t *const right           = expression->right;
4715         type_t       *const orig_type_left  = left->base.type;
4716         type_t       *const orig_type_right = right->base.type;
4717         type_t       *const type_left       = skip_typeref(orig_type_left);
4718         type_t       *const type_right      = skip_typeref(orig_type_right);
4719
4720         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4721                 /* TODO: improve error message */
4722                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4723                         errorf(HERE, "operation needs arithmetic types");
4724                 }
4725                 return;
4726         }
4727
4728         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4729         expression->left      = create_implicit_cast(left, arithmetic_type);
4730         expression->right     = create_implicit_cast(right, arithmetic_type);
4731         expression->base.type = arithmetic_type;
4732 }
4733
4734 static void semantic_shift_op(binary_expression_t *expression)
4735 {
4736         expression_t *const left            = expression->left;
4737         expression_t *const right           = expression->right;
4738         type_t       *const orig_type_left  = left->base.type;
4739         type_t       *const orig_type_right = right->base.type;
4740         type_t       *      type_left       = skip_typeref(orig_type_left);
4741         type_t       *      type_right      = skip_typeref(orig_type_right);
4742
4743         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4744                 /* TODO: improve error message */
4745                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4746                         errorf(HERE, "operation needs integer types");
4747                 }
4748                 return;
4749         }
4750
4751         type_left  = promote_integer(type_left);
4752         type_right = promote_integer(type_right);
4753
4754         expression->left      = create_implicit_cast(left, type_left);
4755         expression->right     = create_implicit_cast(right, type_right);
4756         expression->base.type = type_left;
4757 }
4758
4759 static void semantic_add(binary_expression_t *expression)
4760 {
4761         expression_t *const left            = expression->left;
4762         expression_t *const right           = expression->right;
4763         type_t       *const orig_type_left  = left->base.type;
4764         type_t       *const orig_type_right = right->base.type;
4765         type_t       *const type_left       = skip_typeref(orig_type_left);
4766         type_t       *const type_right      = skip_typeref(orig_type_right);
4767
4768         /* Â§ 5.6.5 */
4769         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4770                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4771                 expression->left  = create_implicit_cast(left, arithmetic_type);
4772                 expression->right = create_implicit_cast(right, arithmetic_type);
4773                 expression->base.type = arithmetic_type;
4774                 return;
4775         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4776                 expression->base.type = type_left;
4777         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4778                 expression->base.type = type_right;
4779         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4780                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4781         }
4782 }
4783
4784 static void semantic_sub(binary_expression_t *expression)
4785 {
4786         expression_t *const left            = expression->left;
4787         expression_t *const right           = expression->right;
4788         type_t       *const orig_type_left  = left->base.type;
4789         type_t       *const orig_type_right = right->base.type;
4790         type_t       *const type_left       = skip_typeref(orig_type_left);
4791         type_t       *const type_right      = skip_typeref(orig_type_right);
4792
4793         /* Â§ 5.6.5 */
4794         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4795                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4796                 expression->left        = create_implicit_cast(left, arithmetic_type);
4797                 expression->right       = create_implicit_cast(right, arithmetic_type);
4798                 expression->base.type =  arithmetic_type;
4799                 return;
4800         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4801                 expression->base.type = type_left;
4802         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4803                 if(!pointers_compatible(type_left, type_right)) {
4804                         errorf(HERE,
4805                                "pointers to incompatible objects to binary '-' ('%T', '%T')",
4806                                orig_type_left, orig_type_right);
4807                 } else {
4808                         expression->base.type = type_ptrdiff_t;
4809                 }
4810         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4811                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
4812                        orig_type_left, orig_type_right);
4813         }
4814 }
4815
4816 /**
4817  * Check the semantics of comparison expressions.
4818  *
4819  * @param expression   The expression to check.
4820  */
4821 static void semantic_comparison(binary_expression_t *expression)
4822 {
4823         expression_t *left            = expression->left;
4824         expression_t *right           = expression->right;
4825         type_t       *orig_type_left  = left->base.type;
4826         type_t       *orig_type_right = right->base.type;
4827
4828         type_t *type_left  = skip_typeref(orig_type_left);
4829         type_t *type_right = skip_typeref(orig_type_right);
4830
4831         /* TODO non-arithmetic types */
4832         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4833                 if (warning.sign_compare &&
4834                     (expression->base.kind != EXPR_BINARY_EQUAL &&
4835                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
4836                     (is_type_signed(type_left) != is_type_signed(type_right))) {
4837                         warningf(expression->base.source_position,
4838                                  "comparison between signed and unsigned");
4839                 }
4840                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4841                 expression->left        = create_implicit_cast(left, arithmetic_type);
4842                 expression->right       = create_implicit_cast(right, arithmetic_type);
4843                 expression->base.type   = arithmetic_type;
4844                 if (warning.float_equal &&
4845                     (expression->base.kind == EXPR_BINARY_EQUAL ||
4846                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
4847                     is_type_float(arithmetic_type)) {
4848                         warningf(expression->base.source_position,
4849                                  "comparing floating point with == or != is unsafe");
4850                 }
4851         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4852                 /* TODO check compatibility */
4853         } else if (is_type_pointer(type_left)) {
4854                 expression->right = create_implicit_cast(right, type_left);
4855         } else if (is_type_pointer(type_right)) {
4856                 expression->left = create_implicit_cast(left, type_right);
4857         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4858                 type_error_incompatible("invalid operands in comparison",
4859                                         expression->base.source_position,
4860                                         type_left, type_right);
4861         }
4862         expression->base.type = type_int;
4863 }
4864
4865 static void semantic_arithmetic_assign(binary_expression_t *expression)
4866 {
4867         expression_t *left            = expression->left;
4868         expression_t *right           = expression->right;
4869         type_t       *orig_type_left  = left->base.type;
4870         type_t       *orig_type_right = right->base.type;
4871
4872         type_t *type_left  = skip_typeref(orig_type_left);
4873         type_t *type_right = skip_typeref(orig_type_right);
4874
4875         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4876                 /* TODO: improve error message */
4877                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4878                         errorf(HERE, "operation needs arithmetic types");
4879                 }
4880                 return;
4881         }
4882
4883         /* combined instructions are tricky. We can't create an implicit cast on
4884          * the left side, because we need the uncasted form for the store.
4885          * The ast2firm pass has to know that left_type must be right_type
4886          * for the arithmetic operation and create a cast by itself */
4887         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4888         expression->right       = create_implicit_cast(right, arithmetic_type);
4889         expression->base.type   = type_left;
4890 }
4891
4892 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4893 {
4894         expression_t *const left            = expression->left;
4895         expression_t *const right           = expression->right;
4896         type_t       *const orig_type_left  = left->base.type;
4897         type_t       *const orig_type_right = right->base.type;
4898         type_t       *const type_left       = skip_typeref(orig_type_left);
4899         type_t       *const type_right      = skip_typeref(orig_type_right);
4900
4901         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4902                 /* combined instructions are tricky. We can't create an implicit cast on
4903                  * the left side, because we need the uncasted form for the store.
4904                  * The ast2firm pass has to know that left_type must be right_type
4905                  * for the arithmetic operation and create a cast by itself */
4906                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4907                 expression->right     = create_implicit_cast(right, arithmetic_type);
4908                 expression->base.type = type_left;
4909         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4910                 expression->base.type = type_left;
4911         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4912                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4913         }
4914 }
4915
4916 /**
4917  * Check the semantic restrictions of a logical expression.
4918  */
4919 static void semantic_logical_op(binary_expression_t *expression)
4920 {
4921         expression_t *const left            = expression->left;
4922         expression_t *const right           = expression->right;
4923         type_t       *const orig_type_left  = left->base.type;
4924         type_t       *const orig_type_right = right->base.type;
4925         type_t       *const type_left       = skip_typeref(orig_type_left);
4926         type_t       *const type_right      = skip_typeref(orig_type_right);
4927
4928         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4929                 /* TODO: improve error message */
4930                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4931                         errorf(HERE, "operation needs scalar types");
4932                 }
4933                 return;
4934         }
4935
4936         expression->base.type = type_int;
4937 }
4938
4939 /**
4940  * Checks if a compound type has constant fields.
4941  */
4942 static bool has_const_fields(const compound_type_t *type)
4943 {
4944         const scope_t       *scope       = &type->declaration->scope;
4945         const declaration_t *declaration = scope->declarations;
4946
4947         for (; declaration != NULL; declaration = declaration->next) {
4948                 if (declaration->namespc != NAMESPACE_NORMAL)
4949                         continue;
4950
4951                 const type_t *decl_type = skip_typeref(declaration->type);
4952                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4953                         return true;
4954         }
4955         /* TODO */
4956         return false;
4957 }
4958
4959 /**
4960  * Check the semantic restrictions of a binary assign expression.
4961  */
4962 static void semantic_binexpr_assign(binary_expression_t *expression)
4963 {
4964         expression_t *left           = expression->left;
4965         type_t       *orig_type_left = left->base.type;
4966
4967         type_t *type_left = revert_automatic_type_conversion(left);
4968         type_left         = skip_typeref(orig_type_left);
4969
4970         /* must be a modifiable lvalue */
4971         if (is_type_array(type_left)) {
4972                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4973                 return;
4974         }
4975         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4976                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
4977                        orig_type_left);
4978                 return;
4979         }
4980         if(is_type_incomplete(type_left)) {
4981                 errorf(HERE,
4982                        "left-hand side of assignment '%E' has incomplete type '%T'",
4983                        left, orig_type_left);
4984                 return;
4985         }
4986         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4987                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
4988                        left, orig_type_left);
4989                 return;
4990         }
4991
4992         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
4993                                                  "assignment");
4994         if (res_type == NULL) {
4995                 errorf(expression->base.source_position,
4996                         "cannot assign to '%T' from '%T'",
4997                         orig_type_left, expression->right->base.type);
4998         } else {
4999                 expression->right = create_implicit_cast(expression->right, res_type);
5000         }
5001
5002         expression->base.type = orig_type_left;
5003 }
5004
5005 static bool expression_has_effect(const expression_t *const expr)
5006 {
5007         switch (expr->kind) {
5008                 case EXPR_UNKNOWN:                   break;
5009                 case EXPR_INVALID:                   break;
5010                 case EXPR_REFERENCE:                 return false;
5011                 case EXPR_CONST:                     return false;
5012                 case EXPR_CHAR_CONST:                return false;
5013                 case EXPR_STRING_LITERAL:            return false;
5014                 case EXPR_WIDE_STRING_LITERAL:       return false;
5015                 case EXPR_CALL: {
5016                         const call_expression_t *const call = &expr->call;
5017                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5018                                 return true;
5019
5020                         switch (call->function->builtin_symbol.symbol->ID) {
5021                                 case T___builtin_va_end: return true;
5022                                 default:                 return false;
5023                         }
5024                 }
5025                 case EXPR_CONDITIONAL: {
5026                         const conditional_expression_t *const cond = &expr->conditional;
5027                         return
5028                                 expression_has_effect(cond->true_expression) &&
5029                                 expression_has_effect(cond->false_expression);
5030                 }
5031                 case EXPR_SELECT:                    return false;
5032                 case EXPR_ARRAY_ACCESS:              return false;
5033                 case EXPR_SIZEOF:                    return false;
5034                 case EXPR_CLASSIFY_TYPE:             return false;
5035                 case EXPR_ALIGNOF:                   return false;
5036
5037                 case EXPR_FUNCTION:                  return false;
5038                 case EXPR_PRETTY_FUNCTION:           return false;
5039                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
5040                 case EXPR_BUILTIN_CONSTANT_P:        return false;
5041                 case EXPR_BUILTIN_PREFETCH:          return true;
5042                 case EXPR_OFFSETOF:                  return false;
5043                 case EXPR_VA_START:                  return true;
5044                 case EXPR_VA_ARG:                    return true;
5045                 case EXPR_STATEMENT:                 return true; // TODO
5046                 case EXPR_COMPOUND_LITERAL:          return false;
5047
5048                 case EXPR_UNARY_NEGATE:              return false;
5049                 case EXPR_UNARY_PLUS:                return false;
5050                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
5051                 case EXPR_UNARY_NOT:                 return false;
5052                 case EXPR_UNARY_DEREFERENCE:         return false;
5053                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
5054                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
5055                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
5056                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
5057                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
5058                 case EXPR_UNARY_CAST: {
5059                         type_t *type = skip_typeref(expr->base.type);
5060                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
5061                 }
5062                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
5063                 case EXPR_UNARY_ASSUME:              return true;
5064                 case EXPR_UNARY_BITFIELD_EXTRACT:    return false;
5065
5066                 case EXPR_BINARY_ADD:                return false;
5067                 case EXPR_BINARY_SUB:                return false;
5068                 case EXPR_BINARY_MUL:                return false;
5069                 case EXPR_BINARY_DIV:                return false;
5070                 case EXPR_BINARY_MOD:                return false;
5071                 case EXPR_BINARY_EQUAL:              return false;
5072                 case EXPR_BINARY_NOTEQUAL:           return false;
5073                 case EXPR_BINARY_LESS:               return false;
5074                 case EXPR_BINARY_LESSEQUAL:          return false;
5075                 case EXPR_BINARY_GREATER:            return false;
5076                 case EXPR_BINARY_GREATEREQUAL:       return false;
5077                 case EXPR_BINARY_BITWISE_AND:        return false;
5078                 case EXPR_BINARY_BITWISE_OR:         return false;
5079                 case EXPR_BINARY_BITWISE_XOR:        return false;
5080                 case EXPR_BINARY_SHIFTLEFT:          return false;
5081                 case EXPR_BINARY_SHIFTRIGHT:         return false;
5082                 case EXPR_BINARY_ASSIGN:             return true;
5083                 case EXPR_BINARY_MUL_ASSIGN:         return true;
5084                 case EXPR_BINARY_DIV_ASSIGN:         return true;
5085                 case EXPR_BINARY_MOD_ASSIGN:         return true;
5086                 case EXPR_BINARY_ADD_ASSIGN:         return true;
5087                 case EXPR_BINARY_SUB_ASSIGN:         return true;
5088                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
5089                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
5090                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5091                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5092                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
5093                 case EXPR_BINARY_LOGICAL_AND:
5094                 case EXPR_BINARY_LOGICAL_OR:
5095                 case EXPR_BINARY_COMMA:
5096                         return expression_has_effect(expr->binary.right);
5097
5098                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
5099                 case EXPR_BINARY_ISGREATER:          return false;
5100                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
5101                 case EXPR_BINARY_ISLESS:             return false;
5102                 case EXPR_BINARY_ISLESSEQUAL:        return false;
5103                 case EXPR_BINARY_ISLESSGREATER:      return false;
5104                 case EXPR_BINARY_ISUNORDERED:        return false;
5105         }
5106
5107         panic("unexpected statement");
5108 }
5109
5110 static void semantic_comma(binary_expression_t *expression)
5111 {
5112         if (warning.unused_value) {
5113                 const expression_t *const left = expression->left;
5114                 if (!expression_has_effect(left)) {
5115                         warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5116                 }
5117         }
5118         expression->base.type = expression->right->base.type;
5119 }
5120
5121 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
5122 static expression_t *parse_##binexpression_type(unsigned precedence,      \
5123                                                 expression_t *left)       \
5124 {                                                                         \
5125         eat(token_type);                                                      \
5126         source_position_t pos = HERE;                                         \
5127                                                                           \
5128         expression_t *right = parse_sub_expression(precedence + lr);          \
5129                                                                           \
5130         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5131         binexpr->base.source_position = pos;                                  \
5132         binexpr->binary.left  = left;                                         \
5133         binexpr->binary.right = right;                                        \
5134         sfunc(&binexpr->binary);                                              \
5135                                                                           \
5136         return binexpr;                                                       \
5137 }
5138
5139 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
5140 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
5141 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
5142 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
5143 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
5144 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
5145 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
5146 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
5147 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
5148
5149 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
5150                       semantic_comparison, 1)
5151 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5152                       semantic_comparison, 1)
5153 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
5154                       semantic_comparison, 1)
5155 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
5156                       semantic_comparison, 1)
5157
5158 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5159                       semantic_binexpr_arithmetic, 1)
5160 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5161                       semantic_binexpr_arithmetic, 1)
5162 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5163                       semantic_binexpr_arithmetic, 1)
5164 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5165                       semantic_logical_op, 1)
5166 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5167                       semantic_logical_op, 1)
5168 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5169                       semantic_shift_op, 1)
5170 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5171                       semantic_shift_op, 1)
5172 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5173                       semantic_arithmetic_addsubb_assign, 0)
5174 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5175                       semantic_arithmetic_addsubb_assign, 0)
5176 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5177                       semantic_arithmetic_assign, 0)
5178 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5179                       semantic_arithmetic_assign, 0)
5180 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5181                       semantic_arithmetic_assign, 0)
5182 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5183                       semantic_arithmetic_assign, 0)
5184 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5185                       semantic_arithmetic_assign, 0)
5186 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5187                       semantic_arithmetic_assign, 0)
5188 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5189                       semantic_arithmetic_assign, 0)
5190 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5191                       semantic_arithmetic_assign, 0)
5192
5193 static expression_t *parse_sub_expression(unsigned precedence)
5194 {
5195         if(token.type < 0) {
5196                 return expected_expression_error();
5197         }
5198
5199         expression_parser_function_t *parser
5200                 = &expression_parsers[token.type];
5201         source_position_t             source_position = token.source_position;
5202         expression_t                 *left;
5203
5204         if(parser->parser != NULL) {
5205                 left = parser->parser(parser->precedence);
5206         } else {
5207                 left = parse_primary_expression();
5208         }
5209         assert(left != NULL);
5210         left->base.source_position = source_position;
5211
5212         while(true) {
5213                 if(token.type < 0) {
5214                         return expected_expression_error();
5215                 }
5216
5217                 parser = &expression_parsers[token.type];
5218                 if(parser->infix_parser == NULL)
5219                         break;
5220                 if(parser->infix_precedence < precedence)
5221                         break;
5222
5223                 left = parser->infix_parser(parser->infix_precedence, left);
5224
5225                 assert(left != NULL);
5226                 assert(left->kind != EXPR_UNKNOWN);
5227                 left->base.source_position = source_position;
5228         }
5229
5230         return left;
5231 }
5232
5233 /**
5234  * Parse an expression.
5235  */
5236 static expression_t *parse_expression(void)
5237 {
5238         return parse_sub_expression(1);
5239 }
5240
5241 /**
5242  * Register a parser for a prefix-like operator with given precedence.
5243  *
5244  * @param parser      the parser function
5245  * @param token_type  the token type of the prefix token
5246  * @param precedence  the precedence of the operator
5247  */
5248 static void register_expression_parser(parse_expression_function parser,
5249                                        int token_type, unsigned precedence)
5250 {
5251         expression_parser_function_t *entry = &expression_parsers[token_type];
5252
5253         if(entry->parser != NULL) {
5254                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5255                 panic("trying to register multiple expression parsers for a token");
5256         }
5257         entry->parser     = parser;
5258         entry->precedence = precedence;
5259 }
5260
5261 /**
5262  * Register a parser for an infix operator with given precedence.
5263  *
5264  * @param parser      the parser function
5265  * @param token_type  the token type of the infix operator
5266  * @param precedence  the precedence of the operator
5267  */
5268 static void register_infix_parser(parse_expression_infix_function parser,
5269                 int token_type, unsigned precedence)
5270 {
5271         expression_parser_function_t *entry = &expression_parsers[token_type];
5272
5273         if(entry->infix_parser != NULL) {
5274                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5275                 panic("trying to register multiple infix expression parsers for a "
5276                       "token");
5277         }
5278         entry->infix_parser     = parser;
5279         entry->infix_precedence = precedence;
5280 }
5281
5282 /**
5283  * Initialize the expression parsers.
5284  */
5285 static void init_expression_parsers(void)
5286 {
5287         memset(&expression_parsers, 0, sizeof(expression_parsers));
5288
5289         register_infix_parser(parse_array_expression,         '[',              30);
5290         register_infix_parser(parse_call_expression,          '(',              30);
5291         register_infix_parser(parse_select_expression,        '.',              30);
5292         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
5293         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5294                                                               T_PLUSPLUS,       30);
5295         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5296                                                               T_MINUSMINUS,     30);
5297
5298         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
5299         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
5300         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
5301         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
5302         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
5303         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
5304         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
5305         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
5306         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
5307         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
5308         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
5309         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
5310         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5311                                                     T_EXCLAMATIONMARKEQUAL, 13);
5312         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
5313         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
5314         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
5315         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
5316         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
5317         register_infix_parser(parse_conditional_expression,   '?',               7);
5318         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
5319         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
5320         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
5321         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
5322         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
5323         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
5324         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5325                                                                 T_LESSLESSEQUAL, 2);
5326         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5327                                                           T_GREATERGREATEREQUAL, 2);
5328         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5329                                                                      T_ANDEQUAL, 2);
5330         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5331                                                                     T_PIPEEQUAL, 2);
5332         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5333                                                                    T_CARETEQUAL, 2);
5334
5335         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
5336
5337         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
5338         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
5339         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
5340         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
5341         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
5342         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
5343         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5344                                                                   T_PLUSPLUS,   25);
5345         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5346                                                                   T_MINUSMINUS, 25);
5347         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
5348         register_expression_parser(parse_alignof,                T___alignof__, 25);
5349         register_expression_parser(parse_extension,            T___extension__, 25);
5350         register_expression_parser(parse_builtin_classify_type,
5351                                                      T___builtin_classify_type, 25);
5352 }
5353
5354 /**
5355  * Parse a asm statement constraints specification.
5356  */
5357 static asm_constraint_t *parse_asm_constraints(void)
5358 {
5359         asm_constraint_t *result = NULL;
5360         asm_constraint_t *last   = NULL;
5361
5362         while(token.type == T_STRING_LITERAL || token.type == '[') {
5363                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5364                 memset(constraint, 0, sizeof(constraint[0]));
5365
5366                 if(token.type == '[') {
5367                         eat('[');
5368                         if(token.type != T_IDENTIFIER) {
5369                                 parse_error_expected("while parsing asm constraint",
5370                                                      T_IDENTIFIER, 0);
5371                                 return NULL;
5372                         }
5373                         constraint->symbol = token.v.symbol;
5374
5375                         expect(']');
5376                 }
5377
5378                 constraint->constraints = parse_string_literals();
5379                 expect('(');
5380                 constraint->expression = parse_expression();
5381                 expect(')');
5382
5383                 if(last != NULL) {
5384                         last->next = constraint;
5385                 } else {
5386                         result = constraint;
5387                 }
5388                 last = constraint;
5389
5390                 if(token.type != ',')
5391                         break;
5392                 eat(',');
5393         }
5394
5395         return result;
5396 }
5397
5398 /**
5399  * Parse a asm statement clobber specification.
5400  */
5401 static asm_clobber_t *parse_asm_clobbers(void)
5402 {
5403         asm_clobber_t *result = NULL;
5404         asm_clobber_t *last   = NULL;
5405
5406         while(token.type == T_STRING_LITERAL) {
5407                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5408                 clobber->clobber       = parse_string_literals();
5409
5410                 if(last != NULL) {
5411                         last->next = clobber;
5412                 } else {
5413                         result = clobber;
5414                 }
5415                 last = clobber;
5416
5417                 if(token.type != ',')
5418                         break;
5419                 eat(',');
5420         }
5421
5422         return result;
5423 }
5424
5425 /**
5426  * Parse an asm statement.
5427  */
5428 static statement_t *parse_asm_statement(void)
5429 {
5430         eat(T_asm);
5431
5432         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
5433         statement->base.source_position = token.source_position;
5434
5435         asm_statement_t *asm_statement = &statement->asms;
5436
5437         if(token.type == T_volatile) {
5438                 next_token();
5439                 asm_statement->is_volatile = true;
5440         }
5441
5442         expect('(');
5443         asm_statement->asm_text = parse_string_literals();
5444
5445         if(token.type != ':')
5446                 goto end_of_asm;
5447         eat(':');
5448
5449         asm_statement->inputs = parse_asm_constraints();
5450         if(token.type != ':')
5451                 goto end_of_asm;
5452         eat(':');
5453
5454         asm_statement->outputs = parse_asm_constraints();
5455         if(token.type != ':')
5456                 goto end_of_asm;
5457         eat(':');
5458
5459         asm_statement->clobbers = parse_asm_clobbers();
5460
5461 end_of_asm:
5462         expect(')');
5463         expect(';');
5464         return statement;
5465 }
5466
5467 /**
5468  * Parse a case statement.
5469  */
5470 static statement_t *parse_case_statement(void)
5471 {
5472         eat(T_case);
5473
5474         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5475
5476         statement->base.source_position  = token.source_position;
5477         statement->case_label.expression = parse_expression();
5478
5479         if (c_mode & _GNUC) {
5480                 if (token.type == T_DOTDOTDOT) {
5481                         next_token();
5482                         statement->case_label.end_range = parse_expression();
5483                 }
5484         }
5485
5486         expect(':');
5487
5488         if (! is_constant_expression(statement->case_label.expression)) {
5489                 errorf(statement->base.source_position,
5490                         "case label does not reduce to an integer constant");
5491         } else {
5492                 /* TODO: check if the case label is already known */
5493                 if (current_switch != NULL) {
5494                         /* link all cases into the switch statement */
5495                         if (current_switch->last_case == NULL) {
5496                                 current_switch->first_case =
5497                                 current_switch->last_case  = &statement->case_label;
5498                         } else {
5499                                 current_switch->last_case->next = &statement->case_label;
5500                         }
5501                 } else {
5502                         errorf(statement->base.source_position,
5503                                 "case label not within a switch statement");
5504                 }
5505         }
5506         statement->case_label.statement = parse_statement();
5507
5508         return statement;
5509 }
5510
5511 /**
5512  * Finds an existing default label of a switch statement.
5513  */
5514 static case_label_statement_t *
5515 find_default_label(const switch_statement_t *statement)
5516 {
5517         case_label_statement_t *label = statement->first_case;
5518         for ( ; label != NULL; label = label->next) {
5519                 if (label->expression == NULL)
5520                         return label;
5521         }
5522         return NULL;
5523 }
5524
5525 /**
5526  * Parse a default statement.
5527  */
5528 static statement_t *parse_default_statement(void)
5529 {
5530         eat(T_default);
5531
5532         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5533
5534         statement->base.source_position = token.source_position;
5535
5536         expect(':');
5537         if (current_switch != NULL) {
5538                 const case_label_statement_t *def_label = find_default_label(current_switch);
5539                 if (def_label != NULL) {
5540                         errorf(HERE, "multiple default labels in one switch");
5541                         errorf(def_label->base.source_position,
5542                                 "this is the first default label");
5543                 } else {
5544                         /* link all cases into the switch statement */
5545                         if (current_switch->last_case == NULL) {
5546                                 current_switch->first_case =
5547                                         current_switch->last_case  = &statement->case_label;
5548                         } else {
5549                                 current_switch->last_case->next = &statement->case_label;
5550                         }
5551                 }
5552         } else {
5553                 errorf(statement->base.source_position,
5554                         "'default' label not within a switch statement");
5555         }
5556         statement->case_label.statement = parse_statement();
5557
5558         return statement;
5559 }
5560
5561 /**
5562  * Return the declaration for a given label symbol or create a new one.
5563  */
5564 static declaration_t *get_label(symbol_t *symbol)
5565 {
5566         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
5567         assert(current_function != NULL);
5568         /* if we found a label in the same function, then we already created the
5569          * declaration */
5570         if(candidate != NULL
5571                         && candidate->parent_scope == &current_function->scope) {
5572                 return candidate;
5573         }
5574
5575         /* otherwise we need to create a new one */
5576         declaration_t *const declaration = allocate_declaration_zero();
5577         declaration->namespc       = NAMESPACE_LABEL;
5578         declaration->symbol        = symbol;
5579
5580         label_push(declaration);
5581
5582         return declaration;
5583 }
5584
5585 /**
5586  * Parse a label statement.
5587  */
5588 static statement_t *parse_label_statement(void)
5589 {
5590         assert(token.type == T_IDENTIFIER);
5591         symbol_t *symbol = token.v.symbol;
5592         next_token();
5593
5594         declaration_t *label = get_label(symbol);
5595
5596         /* if source position is already set then the label is defined twice,
5597          * otherwise it was just mentioned in a goto so far */
5598         if(label->source_position.input_name != NULL) {
5599                 errorf(HERE, "duplicate label '%Y'", symbol);
5600                 errorf(label->source_position, "previous definition of '%Y' was here",
5601                        symbol);
5602         } else {
5603                 label->source_position = token.source_position;
5604         }
5605
5606         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
5607
5608         statement->base.source_position = token.source_position;
5609         statement->label.label          = label;
5610
5611         eat(':');
5612
5613         if(token.type == '}') {
5614                 /* TODO only warn? */
5615                 errorf(HERE, "label at end of compound statement");
5616                 return statement;
5617         } else {
5618                 if (token.type == ';') {
5619                         /* eat an empty statement here, to avoid the warning about an empty
5620                          * after a label.  label:; is commonly used to have a label before
5621                          * a }. */
5622                         next_token();
5623                 } else {
5624                         statement->label.statement = parse_statement();
5625                 }
5626         }
5627
5628         /* remember the labels's in a list for later checking */
5629         if (label_last == NULL) {
5630                 label_first = &statement->label;
5631         } else {
5632                 label_last->next = &statement->label;
5633         }
5634         label_last = &statement->label;
5635
5636         return statement;
5637 }
5638
5639 /**
5640  * Parse an if statement.
5641  */
5642 static statement_t *parse_if(void)
5643 {
5644         eat(T_if);
5645
5646         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
5647         statement->base.source_position = token.source_position;
5648
5649         expect('(');
5650         statement->ifs.condition = parse_expression();
5651         expect(')');
5652
5653         statement->ifs.true_statement = parse_statement();
5654         if(token.type == T_else) {
5655                 next_token();
5656                 statement->ifs.false_statement = parse_statement();
5657         }
5658
5659         return statement;
5660 }
5661
5662 /**
5663  * Parse a switch statement.
5664  */
5665 static statement_t *parse_switch(void)
5666 {
5667         eat(T_switch);
5668
5669         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
5670         statement->base.source_position = token.source_position;
5671
5672         expect('(');
5673         expression_t *const expr = parse_expression();
5674         type_t       *      type = skip_typeref(expr->base.type);
5675         if (is_type_integer(type)) {
5676                 type = promote_integer(type);
5677         } else if (is_type_valid(type)) {
5678                 errorf(expr->base.source_position,
5679                        "switch quantity is not an integer, but '%T'", type);
5680                 type = type_error_type;
5681         }
5682         statement->switchs.expression = create_implicit_cast(expr, type);
5683         expect(')');
5684
5685         switch_statement_t *rem = current_switch;
5686         current_switch          = &statement->switchs;
5687         statement->switchs.body = parse_statement();
5688         current_switch          = rem;
5689
5690         if (warning.switch_default
5691                         && find_default_label(&statement->switchs) == NULL) {
5692                 warningf(statement->base.source_position, "switch has no default case");
5693         }
5694
5695         return statement;
5696 }
5697
5698 static statement_t *parse_loop_body(statement_t *const loop)
5699 {
5700         statement_t *const rem = current_loop;
5701         current_loop = loop;
5702
5703         statement_t *const body = parse_statement();
5704
5705         current_loop = rem;
5706         return body;
5707 }
5708
5709 /**
5710  * Parse a while statement.
5711  */
5712 static statement_t *parse_while(void)
5713 {
5714         eat(T_while);
5715
5716         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
5717         statement->base.source_position = token.source_position;
5718
5719         expect('(');
5720         statement->whiles.condition = parse_expression();
5721         expect(')');
5722
5723         statement->whiles.body = parse_loop_body(statement);
5724
5725         return statement;
5726 }
5727
5728 /**
5729  * Parse a do statement.
5730  */
5731 static statement_t *parse_do(void)
5732 {
5733         eat(T_do);
5734
5735         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
5736
5737         statement->base.source_position = token.source_position;
5738
5739         statement->do_while.body = parse_loop_body(statement);
5740
5741         expect(T_while);
5742         expect('(');
5743         statement->do_while.condition = parse_expression();
5744         expect(')');
5745         expect(';');
5746
5747         return statement;
5748 }
5749
5750 /**
5751  * Parse a for statement.
5752  */
5753 static statement_t *parse_for(void)
5754 {
5755         eat(T_for);
5756
5757         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
5758         statement->base.source_position = token.source_position;
5759
5760         expect('(');
5761
5762         int      top        = environment_top();
5763         scope_t *last_scope = scope;
5764         set_scope(&statement->fors.scope);
5765
5766         if(token.type != ';') {
5767                 if(is_declaration_specifier(&token, false)) {
5768                         parse_declaration(record_declaration);
5769                 } else {
5770                         expression_t *const init = parse_expression();
5771                         statement->fors.initialisation = init;
5772                         if (warning.unused_value  && !expression_has_effect(init)) {
5773                                 warningf(init->base.source_position, "initialisation of 'for'-statement has no effect");
5774                         }
5775                         expect(';');
5776                 }
5777         } else {
5778                 expect(';');
5779         }
5780
5781         if(token.type != ';') {
5782                 statement->fors.condition = parse_expression();
5783         }
5784         expect(';');
5785         if(token.type != ')') {
5786                 expression_t *const step = parse_expression();
5787                 statement->fors.step = step;
5788                 if (warning.unused_value  && !expression_has_effect(step)) {
5789                         warningf(step->base.source_position, "step of 'for'-statement has no effect");
5790                 }
5791         }
5792         expect(')');
5793         statement->fors.body = parse_loop_body(statement);
5794
5795         assert(scope == &statement->fors.scope);
5796         set_scope(last_scope);
5797         environment_pop_to(top);
5798
5799         return statement;
5800 }
5801
5802 /**
5803  * Parse a goto statement.
5804  */
5805 static statement_t *parse_goto(void)
5806 {
5807         eat(T_goto);
5808
5809         if(token.type != T_IDENTIFIER) {
5810                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5811                 eat_statement();
5812                 return NULL;
5813         }
5814         symbol_t *symbol = token.v.symbol;
5815         next_token();
5816
5817         declaration_t *label = get_label(symbol);
5818
5819         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
5820         statement->base.source_position = token.source_position;
5821
5822         statement->gotos.label = label;
5823
5824         /* remember the goto's in a list for later checking */
5825         if (goto_last == NULL) {
5826                 goto_first = &statement->gotos;
5827         } else {
5828                 goto_last->next = &statement->gotos;
5829         }
5830         goto_last = &statement->gotos;
5831
5832         expect(';');
5833
5834         return statement;
5835 }
5836
5837 /**
5838  * Parse a continue statement.
5839  */
5840 static statement_t *parse_continue(void)
5841 {
5842         statement_t *statement;
5843         if (current_loop == NULL) {
5844                 errorf(HERE, "continue statement not within loop");
5845                 statement = NULL;
5846         } else {
5847                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
5848
5849                 statement->base.source_position = token.source_position;
5850         }
5851
5852         eat(T_continue);
5853         expect(';');
5854
5855         return statement;
5856 }
5857
5858 /**
5859  * Parse a break statement.
5860  */
5861 static statement_t *parse_break(void)
5862 {
5863         statement_t *statement;
5864         if (current_switch == NULL && current_loop == NULL) {
5865                 errorf(HERE, "break statement not within loop or switch");
5866                 statement = NULL;
5867         } else {
5868                 statement = allocate_statement_zero(STATEMENT_BREAK);
5869
5870                 statement->base.source_position = token.source_position;
5871         }
5872
5873         eat(T_break);
5874         expect(';');
5875
5876         return statement;
5877 }
5878
5879 /**
5880  * Check if a given declaration represents a local variable.
5881  */
5882 static bool is_local_var_declaration(const declaration_t *declaration) {
5883         switch ((storage_class_tag_t) declaration->storage_class) {
5884         case STORAGE_CLASS_NONE:
5885         case STORAGE_CLASS_AUTO:
5886         case STORAGE_CLASS_REGISTER: {
5887                 const type_t *type = skip_typeref(declaration->type);
5888                 if(is_type_function(type)) {
5889                         return false;
5890                 } else {
5891                         return true;
5892                 }
5893         }
5894         default:
5895                 return false;
5896         }
5897 }
5898
5899 /**
5900  * Check if a given declaration represents a variable.
5901  */
5902 static bool is_var_declaration(const declaration_t *declaration) {
5903         switch ((storage_class_tag_t) declaration->storage_class) {
5904         case STORAGE_CLASS_NONE:
5905         case STORAGE_CLASS_EXTERN:
5906         case STORAGE_CLASS_STATIC:
5907         case STORAGE_CLASS_AUTO:
5908         case STORAGE_CLASS_REGISTER:
5909         case STORAGE_CLASS_THREAD:
5910         case STORAGE_CLASS_THREAD_EXTERN:
5911         case STORAGE_CLASS_THREAD_STATIC: {
5912                 const type_t *type = skip_typeref(declaration->type);
5913                 if(is_type_function(type)) {
5914                         return false;
5915                 } else {
5916                         return true;
5917                 }
5918         }
5919         default:
5920                 return false;
5921         }
5922 }
5923
5924 /**
5925  * Check if a given expression represents a local variable.
5926  */
5927 static bool is_local_variable(const expression_t *expression)
5928 {
5929         if (expression->base.kind != EXPR_REFERENCE) {
5930                 return false;
5931         }
5932         const declaration_t *declaration = expression->reference.declaration;
5933         return is_local_var_declaration(declaration);
5934 }
5935
5936 /**
5937  * Check if a given expression represents a local variable and
5938  * return its declaration then, else return NULL.
5939  */
5940 declaration_t *expr_is_variable(const expression_t *expression)
5941 {
5942         if (expression->base.kind != EXPR_REFERENCE) {
5943                 return NULL;
5944         }
5945         declaration_t *declaration = expression->reference.declaration;
5946         if (is_var_declaration(declaration))
5947                 return declaration;
5948         return NULL;
5949 }
5950
5951 /**
5952  * Parse a return statement.
5953  */
5954 static statement_t *parse_return(void)
5955 {
5956         eat(T_return);
5957
5958         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
5959         statement->base.source_position = token.source_position;
5960
5961         expression_t *return_value = NULL;
5962         if(token.type != ';') {
5963                 return_value = parse_expression();
5964         }
5965         expect(';');
5966
5967         const type_t *const func_type = current_function->type;
5968         assert(is_type_function(func_type));
5969         type_t *const return_type = skip_typeref(func_type->function.return_type);
5970
5971         if(return_value != NULL) {
5972                 type_t *return_value_type = skip_typeref(return_value->base.type);
5973
5974                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5975                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5976                         warningf(statement->base.source_position,
5977                                  "'return' with a value, in function returning void");
5978                         return_value = NULL;
5979                 } else {
5980                         type_t *const res_type = semantic_assign(return_type,
5981                                 return_value, "'return'");
5982                         if (res_type == NULL) {
5983                                 errorf(statement->base.source_position,
5984                                        "cannot return something of type '%T' in function returning '%T'",
5985                                        return_value->base.type, return_type);
5986                         } else {
5987                                 return_value = create_implicit_cast(return_value, res_type);
5988                         }
5989                 }
5990                 /* check for returning address of a local var */
5991                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
5992                         const expression_t *expression = return_value->unary.value;
5993                         if (is_local_variable(expression)) {
5994                                 warningf(statement->base.source_position,
5995                                          "function returns address of local variable");
5996                         }
5997                 }
5998         } else {
5999                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6000                         warningf(statement->base.source_position,
6001                                  "'return' without value, in function returning non-void");
6002                 }
6003         }
6004         statement->returns.value = return_value;
6005
6006         return statement;
6007 }
6008
6009 /**
6010  * Parse a declaration statement.
6011  */
6012 static statement_t *parse_declaration_statement(void)
6013 {
6014         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6015
6016         statement->base.source_position = token.source_position;
6017
6018         declaration_t *before = last_declaration;
6019         parse_declaration(record_declaration);
6020
6021         if(before == NULL) {
6022                 statement->declaration.declarations_begin = scope->declarations;
6023         } else {
6024                 statement->declaration.declarations_begin = before->next;
6025         }
6026         statement->declaration.declarations_end = last_declaration;
6027
6028         return statement;
6029 }
6030
6031 /**
6032  * Parse an expression statement, ie. expr ';'.
6033  */
6034 static statement_t *parse_expression_statement(void)
6035 {
6036         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6037
6038         statement->base.source_position  = token.source_position;
6039         expression_t *const expr         = parse_expression();
6040         statement->expression.expression = expr;
6041
6042         if (warning.unused_value  && !expression_has_effect(expr)) {
6043                 warningf(expr->base.source_position, "statement has no effect");
6044         }
6045
6046         expect(';');
6047
6048         return statement;
6049 }
6050
6051 /**
6052  * Parse a statement.
6053  */
6054 static statement_t *parse_statement(void)
6055 {
6056         statement_t   *statement = NULL;
6057
6058         /* declaration or statement */
6059         switch(token.type) {
6060         case T_asm:
6061                 statement = parse_asm_statement();
6062                 break;
6063
6064         case T_case:
6065                 statement = parse_case_statement();
6066                 break;
6067
6068         case T_default:
6069                 statement = parse_default_statement();
6070                 break;
6071
6072         case '{':
6073                 statement = parse_compound_statement();
6074                 break;
6075
6076         case T_if:
6077                 statement = parse_if();
6078                 break;
6079
6080         case T_switch:
6081                 statement = parse_switch();
6082                 break;
6083
6084         case T_while:
6085                 statement = parse_while();
6086                 break;
6087
6088         case T_do:
6089                 statement = parse_do();
6090                 break;
6091
6092         case T_for:
6093                 statement = parse_for();
6094                 break;
6095
6096         case T_goto:
6097                 statement = parse_goto();
6098                 break;
6099
6100         case T_continue:
6101                 statement = parse_continue();
6102                 break;
6103
6104         case T_break:
6105                 statement = parse_break();
6106                 break;
6107
6108         case T_return:
6109                 statement = parse_return();
6110                 break;
6111
6112         case ';':
6113                 if (warning.empty_statement) {
6114                         warningf(HERE, "statement is empty");
6115                 }
6116                 next_token();
6117                 statement = NULL;
6118                 break;
6119
6120         case T_IDENTIFIER:
6121                 if(look_ahead(1)->type == ':') {
6122                         statement = parse_label_statement();
6123                         break;
6124                 }
6125
6126                 if(is_typedef_symbol(token.v.symbol)) {
6127                         statement = parse_declaration_statement();
6128                         break;
6129                 }
6130
6131                 statement = parse_expression_statement();
6132                 break;
6133
6134         case T___extension__:
6135                 /* this can be a prefix to a declaration or an expression statement */
6136                 /* we simply eat it now and parse the rest with tail recursion */
6137                 do {
6138                         next_token();
6139                 } while(token.type == T___extension__);
6140                 statement = parse_statement();
6141                 break;
6142
6143         DECLARATION_START
6144                 statement = parse_declaration_statement();
6145                 break;
6146
6147         default:
6148                 statement = parse_expression_statement();
6149                 break;
6150         }
6151
6152         assert(statement == NULL
6153                         || statement->base.source_position.input_name != NULL);
6154
6155         return statement;
6156 }
6157
6158 /**
6159  * Parse a compound statement.
6160  */
6161 static statement_t *parse_compound_statement(void)
6162 {
6163         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6164
6165         statement->base.source_position = token.source_position;
6166
6167         eat('{');
6168
6169         int      top        = environment_top();
6170         scope_t *last_scope = scope;
6171         set_scope(&statement->compound.scope);
6172
6173         statement_t *last_statement = NULL;
6174
6175         while(token.type != '}' && token.type != T_EOF) {
6176                 statement_t *sub_statement = parse_statement();
6177                 if(sub_statement == NULL)
6178                         continue;
6179
6180                 if(last_statement != NULL) {
6181                         last_statement->base.next = sub_statement;
6182                 } else {
6183                         statement->compound.statements = sub_statement;
6184                 }
6185
6186                 while(sub_statement->base.next != NULL)
6187                         sub_statement = sub_statement->base.next;
6188
6189                 last_statement = sub_statement;
6190         }
6191
6192         if(token.type == '}') {
6193                 next_token();
6194         } else {
6195                 errorf(statement->base.source_position,
6196                        "end of file while looking for closing '}'");
6197         }
6198
6199         assert(scope == &statement->compound.scope);
6200         set_scope(last_scope);
6201         environment_pop_to(top);
6202
6203         return statement;
6204 }
6205
6206 /**
6207  * Initialize builtin types.
6208  */
6209 static void initialize_builtin_types(void)
6210 {
6211         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
6212         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
6213         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
6214         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
6215         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
6216         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6217         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
6218         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
6219
6220         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
6221         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6222         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
6223         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
6224 }
6225
6226 /**
6227  * Check for unused global static functions and variables
6228  */
6229 static void check_unused_globals(void)
6230 {
6231         if (!warning.unused_function && !warning.unused_variable)
6232                 return;
6233
6234         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6235                 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6236                         continue;
6237
6238                 type_t *const type = decl->type;
6239                 const char *s;
6240                 if (is_type_function(skip_typeref(type))) {
6241                         if (!warning.unused_function || decl->is_inline)
6242                                 continue;
6243
6244                         s = (decl->init.statement != NULL ? "defined" : "declared");
6245                 } else {
6246                         if (!warning.unused_variable)
6247                                 continue;
6248
6249                         s = "defined";
6250                 }
6251
6252                 warningf(decl->source_position, "'%#T' %s but not used",
6253                         type, decl->symbol, s);
6254         }
6255 }
6256
6257 /**
6258  * Parse a translation unit.
6259  */
6260 static translation_unit_t *parse_translation_unit(void)
6261 {
6262         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6263
6264         assert(global_scope == NULL);
6265         global_scope = &unit->scope;
6266
6267         assert(scope == NULL);
6268         set_scope(&unit->scope);
6269
6270         initialize_builtin_types();
6271
6272         while(token.type != T_EOF) {
6273                 if (token.type == ';') {
6274                         /* TODO error in strict mode */
6275                         warningf(HERE, "stray ';' outside of function");
6276                         next_token();
6277                 } else {
6278                         parse_external_declaration();
6279                 }
6280         }
6281
6282         assert(scope == &unit->scope);
6283         scope          = NULL;
6284         last_declaration = NULL;
6285
6286         assert(global_scope == &unit->scope);
6287         check_unused_globals();
6288         global_scope = NULL;
6289
6290         return unit;
6291 }
6292
6293 /**
6294  * Parse the input.
6295  *
6296  * @return  the translation unit or NULL if errors occurred.
6297  */
6298 translation_unit_t *parse(void)
6299 {
6300         environment_stack = NEW_ARR_F(stack_entry_t, 0);
6301         label_stack       = NEW_ARR_F(stack_entry_t, 0);
6302         diagnostic_count  = 0;
6303         error_count       = 0;
6304         warning_count     = 0;
6305
6306         type_set_output(stderr);
6307         ast_set_output(stderr);
6308
6309         lookahead_bufpos = 0;
6310         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6311                 next_token();
6312         }
6313         translation_unit_t *unit = parse_translation_unit();
6314
6315         DEL_ARR_F(environment_stack);
6316         DEL_ARR_F(label_stack);
6317
6318         if(error_count > 0)
6319                 return NULL;
6320
6321         return unit;
6322 }
6323
6324 /**
6325  * Initialize the parser.
6326  */
6327 void init_parser(void)
6328 {
6329         init_expression_parsers();
6330         obstack_init(&temp_obst);
6331
6332         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6333         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6334 }
6335
6336 /**
6337  * Terminate the parser.
6338  */
6339 void exit_parser(void)
6340 {
6341         obstack_free(&temp_obst, NULL);
6342 }