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