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