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