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