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