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