s/true/false/, fix a typo: a function definition with () means no parameters, not...
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "parser.h"
8 #include "lexer.h"
9 #include "token_t.h"
10 #include "type_t.h"
11 #include "type_hash.h"
12 #include "ast_t.h"
13 #include "adt/bitfiddle.h"
14 #include "adt/error.h"
15 #include "adt/array.h"
16
17 //#define PRINT_TOKENS
18 //#define ABORT_ON_ERROR
19 #define MAX_LOOKAHEAD 2
20 //#define STRICT_C99
21
22 typedef struct {
23         declaration_t *old_declaration;
24         symbol_t      *symbol;
25         unsigned short namespc;
26 } stack_entry_t;
27
28 static token_t         token;
29 static token_t         lookahead_buffer[MAX_LOOKAHEAD];
30 static int             lookahead_bufpos;
31 static stack_entry_t  *environment_stack = NULL;
32 static stack_entry_t  *label_stack       = NULL;
33 static context_t      *global_context    = NULL;
34 static context_t      *context           = NULL;
35 static declaration_t  *last_declaration  = NULL;
36 static declaration_t  *current_function  = NULL;
37 static struct obstack  temp_obst;
38 static bool            found_error;
39
40 static type_t         *type_int         = NULL;
41 static type_t         *type_long_double = NULL;
42 static type_t         *type_double      = NULL;
43 static type_t         *type_float       = NULL;
44 static type_t         *type_char        = NULL;
45 static type_t         *type_string      = NULL;
46 static type_t         *type_void        = NULL;
47 static type_t         *type_void_ptr    = NULL;
48 static type_t         *type_size_t      = NULL;
49 static type_t         *type_ptrdiff_t   = NULL;
50
51 static statement_t *parse_compound_statement(void);
52 static statement_t *parse_statement(void);
53
54 static expression_t *parse_sub_expression(unsigned precedence);
55 static expression_t *parse_expression(void);
56 static type_t       *parse_typename(void);
57
58 #define STORAGE_CLASSES     \
59         case T_typedef:         \
60         case T_extern:          \
61         case T_static:          \
62         case T_auto:            \
63         case T_register:
64
65 #define TYPE_QUALIFIERS     \
66         case T_const:           \
67         case T_restrict:        \
68         case T_volatile:        \
69         case T_inline:
70
71 #ifdef PROVIDE_COMPLEX
72 #define COMPLEX_SPECIFIERS  \
73         case T__Complex:
74 #define IMAGINARY_SPECIFIERS \
75         case T__Imaginary:
76 #else
77 #define COMPLEX_SPECIFIERS
78 #define IMAGINARY_SPECIFIERS
79 #endif
80
81 #define TYPE_SPECIFIERS     \
82         case T_void:            \
83         case T_char:            \
84         case T_short:           \
85         case T_int:             \
86         case T_long:            \
87         case T_float:           \
88         case T_double:          \
89         case T_signed:          \
90         case T_unsigned:        \
91         case T__Bool:           \
92         case T_struct:          \
93         case T_union:           \
94         case T_enum:            \
95         case T___typeof__:      \
96         COMPLEX_SPECIFIERS      \
97         IMAGINARY_SPECIFIERS
98
99 #define DECLARATION_START   \
100         STORAGE_CLASSES         \
101         TYPE_QUALIFIERS         \
102         TYPE_SPECIFIERS
103
104 #define TYPENAME_START      \
105         TYPE_QUALIFIERS         \
106         TYPE_SPECIFIERS
107
108 static void *allocate_ast_zero(size_t size)
109 {
110         void *res = allocate_ast(size);
111         memset(res, 0, size);
112         return res;
113 }
114
115 static size_t get_expression_struct_size(expression_type_t type)
116 {
117         static const size_t sizes[] = {
118                 [EXPR_INVALID]         = sizeof(expression_base_t),
119                 [EXPR_REFERENCE]       = sizeof(reference_expression_t),
120                 [EXPR_CONST]           = sizeof(const_expression_t),
121                 [EXPR_STRING_LITERAL]  = sizeof(string_literal_expression_t),
122                 [EXPR_CALL]            = sizeof(call_expression_t),
123                 [EXPR_UNARY]           = sizeof(unary_expression_t),
124                 [EXPR_BINARY]          = sizeof(binary_expression_t),
125                 [EXPR_CONDITIONAL]     = sizeof(conditional_expression_t),
126                 [EXPR_SELECT]          = sizeof(select_expression_t),
127                 [EXPR_ARRAY_ACCESS]    = sizeof(array_access_expression_t),
128                 [EXPR_SIZEOF]          = sizeof(sizeof_expression_t),
129                 [EXPR_CLASSIFY_TYPE]   = sizeof(classify_type_expression_t),
130                 [EXPR_FUNCTION]        = sizeof(string_literal_expression_t),
131                 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
132                 [EXPR_BUILTIN_SYMBOL]  = sizeof(builtin_symbol_expression_t),
133                 [EXPR_OFFSETOF]        = sizeof(offsetof_expression_t),
134                 [EXPR_VA_ARG]          = sizeof(va_arg_expression_t),
135                 [EXPR_STATEMENT]       = sizeof(statement_expression_t)
136         };
137         assert(sizeof(sizes) / sizeof(sizes[0]) == EXPR_STATEMENT + 1);
138         assert(type <= EXPR_STATEMENT);
139         assert(sizes[type] != 0);
140         return sizes[type];
141 }
142
143 static expression_t *allocate_expression_zero(expression_type_t type)
144 {
145         size_t        size = get_expression_struct_size(type);
146         expression_t *res  = allocate_ast_zero(size);
147
148         res->base.type = type;
149         return res;
150 }
151
152 static size_t get_type_struct_size(type_type_t type)
153 {
154         static const size_t sizes[] = {
155                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
156                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
157                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
158                 [TYPE_ENUM]            = sizeof(enum_type_t),
159                 [TYPE_FUNCTION]        = sizeof(function_type_t),
160                 [TYPE_POINTER]         = sizeof(pointer_type_t),
161                 [TYPE_ARRAY]           = sizeof(array_type_t),
162                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
163                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
164                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
165         };
166         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
167         assert(type <= TYPE_TYPEOF);
168         assert(sizes[type] != 0);
169         return sizes[type];
170 }
171
172 static type_t *allocate_type_zero(type_type_t type)
173 {
174         size_t  size = get_type_struct_size(type);
175         type_t *res  = obstack_alloc(type_obst, size);
176         memset(res, 0, size);
177
178         res->base.type = type;
179         return res;
180 }
181
182 static size_t get_initializer_size(initializer_type_t type)
183 {
184         static const size_t sizes[] = {
185                 [INITIALIZER_VALUE]  = sizeof(initializer_value_t),
186                 [INITIALIZER_STRING] = sizeof(initializer_string_t),
187                 [INITIALIZER_LIST]   = sizeof(initializer_list_t)
188         };
189         assert(type < INITIALIZER_COUNT);
190         assert(sizes[type] != 0);
191         return sizes[type];
192 }
193
194 static initializer_t *allocate_initializer(initializer_type_t type)
195 {
196         initializer_t *result = allocate_ast_zero(get_initializer_size(type));
197         result->type          = type;
198
199         return result;
200 }
201
202 static void free_type(void *type)
203 {
204         obstack_free(type_obst, type);
205 }
206
207 /**
208  * returns the top element of the environment stack
209  */
210 static size_t environment_top(void)
211 {
212         return ARR_LEN(environment_stack);
213 }
214
215 static size_t label_top(void)
216 {
217         return ARR_LEN(label_stack);
218 }
219
220
221
222 static inline void next_token(void)
223 {
224         token                              = lookahead_buffer[lookahead_bufpos];
225         lookahead_buffer[lookahead_bufpos] = lexer_token;
226         lexer_next_token();
227
228         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
229
230 #ifdef PRINT_TOKENS
231         print_token(stderr, &token);
232         fprintf(stderr, "\n");
233 #endif
234 }
235
236 static inline const token_t *look_ahead(int num)
237 {
238         assert(num > 0 && num <= MAX_LOOKAHEAD);
239         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
240         return & lookahead_buffer[pos];
241 }
242
243 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
244
245 static void error(void)
246 {
247         found_error = true;
248 #ifdef ABORT_ON_ERROR
249         abort();
250 #endif
251 }
252
253 static void parser_print_prefix_pos(const source_position_t source_position)
254 {
255     fputs(source_position.input_name, stderr);
256     fputc(':', stderr);
257     fprintf(stderr, "%u", source_position.linenr);
258     fputs(": ", stderr);
259 }
260
261 static void parser_print_error_prefix_pos(
262                 const source_position_t source_position)
263 {
264         parser_print_prefix_pos(source_position);
265         fputs("error: ", stderr);
266         error();
267 }
268
269 static void parser_print_error_prefix(void)
270 {
271         parser_print_error_prefix_pos(token.source_position);
272 }
273
274 static void parse_error(const char *message)
275 {
276         parser_print_error_prefix();
277         fprintf(stderr, "parse error: %s\n", message);
278 }
279
280 static void parser_print_warning_prefix_pos(
281                 const source_position_t source_position)
282 {
283         parser_print_prefix_pos(source_position);
284         fputs("warning: ", stderr);
285 }
286
287 static void parse_warning_pos(const source_position_t source_position,
288                               const char *const message)
289 {
290         parser_print_prefix_pos(source_position);
291         fprintf(stderr, "warning: %s\n", message);
292 }
293
294 static void parse_warning(const char *message)
295 {
296         parse_warning_pos(token.source_position, message);
297 }
298
299 static void parse_error_expected(const char *message, ...)
300 {
301         va_list args;
302         int first = 1;
303
304         if(message != NULL) {
305                 parser_print_error_prefix();
306                 fprintf(stderr, "%s\n", message);
307         }
308         parser_print_error_prefix();
309         fputs("Parse error: got ", stderr);
310         print_token(stderr, &token);
311         fputs(", expected ", stderr);
312
313         va_start(args, message);
314         token_type_t token_type = va_arg(args, token_type_t);
315         while(token_type != 0) {
316                 if(first == 1) {
317                         first = 0;
318                 } else {
319                         fprintf(stderr, ", ");
320                 }
321                 print_token_type(stderr, token_type);
322                 token_type = va_arg(args, token_type_t);
323         }
324         va_end(args);
325         fprintf(stderr, "\n");
326 }
327
328 static void print_type_quoted(type_t *type)
329 {
330         fputc('\'', stderr);
331         print_type(type);
332         fputc('\'', stderr);
333 }
334
335 static void type_error(const char *msg, const source_position_t source_position,
336                        type_t *type)
337 {
338         parser_print_error_prefix_pos(source_position);
339         fprintf(stderr, "%s, but found type ", msg);
340         print_type_quoted(type);
341         fputc('\n', stderr);
342 }
343
344 static void type_error_incompatible(const char *msg,
345                 const source_position_t source_position, type_t *type1, type_t *type2)
346 {
347         parser_print_error_prefix_pos(source_position);
348         fprintf(stderr, "%s, incompatible types: ", msg);
349         print_type_quoted(type1);
350         fprintf(stderr, " - ");
351         print_type_quoted(type2);
352         fprintf(stderr, ")\n");
353 }
354
355 static void eat_block(void)
356 {
357         if(token.type == '{')
358                 next_token();
359
360         while(token.type != '}') {
361                 if(token.type == T_EOF)
362                         return;
363                 if(token.type == '{') {
364                         eat_block();
365                         continue;
366                 }
367                 next_token();
368         }
369         eat('}');
370 }
371
372 static void eat_statement(void)
373 {
374         while(token.type != ';') {
375                 if(token.type == T_EOF)
376                         return;
377                 if(token.type == '}')
378                         return;
379                 if(token.type == '{') {
380                         eat_block();
381                         continue;
382                 }
383                 next_token();
384         }
385         eat(';');
386 }
387
388 static void eat_brace(void)
389 {
390         if(token.type == '(')
391                 next_token();
392
393         while(token.type != ')') {
394                 if(token.type == T_EOF)
395                         return;
396                 if(token.type == ')' || token.type == ';' || token.type == '}') {
397                         return;
398                 }
399                 if(token.type == '(') {
400                         eat_brace();
401                         continue;
402                 }
403                 if(token.type == '{') {
404                         eat_block();
405                         continue;
406                 }
407                 next_token();
408         }
409         eat(')');
410 }
411
412 #define expect(expected)                           \
413     if(UNLIKELY(token.type != (expected))) {       \
414         parse_error_expected(NULL, (expected), 0); \
415         eat_statement();                           \
416         return NULL;                               \
417     }                                              \
418     next_token();
419
420 #define expect_block(expected)                     \
421     if(UNLIKELY(token.type != (expected))) {       \
422         parse_error_expected(NULL, (expected), 0); \
423         eat_block();                               \
424         return NULL;                               \
425     }                                              \
426     next_token();
427
428 #define expect_void(expected)                      \
429     if(UNLIKELY(token.type != (expected))) {       \
430         parse_error_expected(NULL, (expected), 0); \
431         eat_statement();                           \
432         return;                                    \
433     }                                              \
434     next_token();
435
436 static void set_context(context_t *new_context)
437 {
438         context = new_context;
439
440         last_declaration = new_context->declarations;
441         if(last_declaration != NULL) {
442                 while(last_declaration->next != NULL) {
443                         last_declaration = last_declaration->next;
444                 }
445         }
446 }
447
448 /**
449  * called when we find a 2nd declarator for an identifier we already have a
450  * declarator for
451  */
452 static bool is_compatible_declaration (declaration_t *declaration,
453                                       declaration_t *previous)
454 {
455         if (declaration->type->type == TYPE_FUNCTION &&
456                         previous->type->type    == TYPE_FUNCTION &&
457                         previous->type->function.unspecified_parameters) {
458                 function_type_t* const prev_func = &previous->type->function;
459                 function_type_t* const decl_func = &declaration->type->function;
460                 if (prev_func->unspecified_parameters &&
461                                 prev_func->result_type == decl_func->result_type) {
462                         declaration->type = previous->type;
463                         return true;
464                 }
465         }
466         /* TODO: not correct yet */
467         return declaration->type == previous->type;
468 }
469
470 static declaration_t *get_declaration(symbol_t *symbol, namespace_t namespc)
471 {
472         declaration_t *declaration = symbol->declaration;
473         for( ; declaration != NULL; declaration = declaration->symbol_next) {
474                 if(declaration->namespc == namespc)
475                         return declaration;
476         }
477
478         return NULL;
479 }
480
481 static const char *get_namespace_prefix(namespace_t namespc)
482 {
483         switch(namespc) {
484         case NAMESPACE_NORMAL:
485                 return "";
486         case NAMESPACE_UNION:
487                 return "union ";
488         case NAMESPACE_STRUCT:
489                 return "struct ";
490         case NAMESPACE_ENUM:
491                 return "enum ";
492         case NAMESPACE_LABEL:
493                 return "label ";
494         }
495         panic("invalid namespace found");
496 }
497
498 /**
499  * pushs an environment_entry on the environment stack and links the
500  * corresponding symbol to the new entry
501  */
502 static declaration_t *stack_push(stack_entry_t **stack_ptr,
503                                  declaration_t *declaration,
504                                  context_t *parent_context)
505 {
506         symbol_t    *symbol    = declaration->symbol;
507         namespace_t  namespc = (namespace_t)declaration->namespc;
508
509         /* a declaration should be only pushed once */
510         assert(declaration->parent_context == NULL);
511         declaration->parent_context = parent_context;
512
513         declaration_t *previous_declaration = get_declaration(symbol, namespc);
514         assert(declaration != previous_declaration);
515         if(previous_declaration != NULL
516                         && previous_declaration->parent_context == context) {
517                 if(!is_compatible_declaration(declaration, previous_declaration)) {
518                         parser_print_error_prefix_pos(declaration->source_position);
519                         fprintf(stderr, "definition of symbol %s%s with type ",
520                                         get_namespace_prefix(namespc), symbol->string);
521                         print_type_quoted(declaration->type);
522                         fputc('\n', stderr);
523                         parser_print_error_prefix_pos(
524                                         previous_declaration->source_position);
525                         fprintf(stderr, "is incompatible with previous declaration "
526                                         "of type ");
527                         print_type_quoted(previous_declaration->type);
528                         fputc('\n', stderr);
529                 } else {
530                         unsigned old_storage_class = previous_declaration->storage_class;
531                         unsigned new_storage_class = declaration->storage_class;
532                         if (current_function == NULL) {
533                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
534                                     new_storage_class == STORAGE_CLASS_STATIC) {
535                                         parser_print_error_prefix_pos(declaration->source_position);
536                                         fprintf(stderr,
537                                                 "static declaration of '%s' follows non-static declaration\n",
538                                                 symbol->string);
539                                         parser_print_error_prefix_pos(previous_declaration->source_position);
540                                         fprintf(stderr, "previous declaration of '%s' was here\n",
541                                                 symbol->string);
542                                 } else {
543                                         if (old_storage_class == STORAGE_CLASS_EXTERN) {
544                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
545                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
546                                                 }
547                                         } else {
548                                                 parser_print_warning_prefix_pos(declaration->source_position);
549                                                 fprintf(stderr, "redundant declaration for '%s'\n",
550                                                                                 symbol->string);
551                                                 parser_print_warning_prefix_pos(previous_declaration->source_position);
552                                                 fprintf(stderr, "previous declaration of '%s' was here\n",
553                                                                                 symbol->string);
554                                         }
555                                 }
556                         } else {
557                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
558                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
559                                         parser_print_warning_prefix_pos(declaration->source_position);
560                                         fprintf(stderr, "redundant extern declaration for '%s'\n",
561                                                 symbol->string);
562                                         parser_print_warning_prefix_pos(previous_declaration->source_position);
563                                         fprintf(stderr, "previous declaration of '%s' was here\n",
564                                                 symbol->string);
565                                 } else {
566                                         parser_print_error_prefix_pos(declaration->source_position);
567                                         if (old_storage_class == new_storage_class) {
568                                                 fprintf(stderr, "redeclaration of '%s'\n", symbol->string);
569                                         } else {
570                                                 fprintf(stderr, "redeclaration of '%s' with different linkage\n", symbol->string);
571                                         }
572                                         parser_print_error_prefix_pos(previous_declaration->source_position);
573                                         fprintf(stderr, "previous declaration of '%s' was here\n",
574                                                 symbol->string);
575                                 }
576                         }
577                 }
578                 return previous_declaration;
579         }
580
581         /* remember old declaration */
582         stack_entry_t entry;
583         entry.symbol          = symbol;
584         entry.old_declaration = symbol->declaration;
585         entry.namespc         = (unsigned short) namespc;
586         ARR_APP1(stack_entry_t, *stack_ptr, entry);
587
588         /* replace/add declaration into declaration list of the symbol */
589         if(symbol->declaration == NULL) {
590                 symbol->declaration = declaration;
591         } else {
592                 declaration_t *iter_last = NULL;
593                 declaration_t *iter      = symbol->declaration;
594                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
595                         /* replace an entry? */
596                         if(iter->namespc == namespc) {
597                                 if(iter_last == NULL) {
598                                         symbol->declaration = declaration;
599                                 } else {
600                                         iter_last->symbol_next = declaration;
601                                 }
602                                 declaration->symbol_next = iter->symbol_next;
603                                 break;
604                         }
605                 }
606                 if(iter == NULL) {
607                         assert(iter_last->symbol_next == NULL);
608                         iter_last->symbol_next = declaration;
609                 }
610         }
611
612         return declaration;
613 }
614
615 static declaration_t *environment_push(declaration_t *declaration)
616 {
617         assert(declaration->source_position.input_name != NULL);
618         return stack_push(&environment_stack, declaration, context);
619 }
620
621 static declaration_t *label_push(declaration_t *declaration)
622 {
623         return stack_push(&label_stack, declaration, &current_function->context);
624 }
625
626 /**
627  * pops symbols from the environment stack until @p new_top is the top element
628  */
629 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
630 {
631         stack_entry_t *stack = *stack_ptr;
632         size_t         top   = ARR_LEN(stack);
633         size_t         i;
634
635         assert(new_top <= top);
636         if(new_top == top)
637                 return;
638
639         for(i = top; i > new_top; --i) {
640                 stack_entry_t *entry = & stack[i - 1];
641
642                 declaration_t *old_declaration = entry->old_declaration;
643                 symbol_t      *symbol          = entry->symbol;
644                 namespace_t    namespc         = (namespace_t)entry->namespc;
645
646                 /* replace/remove declaration */
647                 declaration_t *declaration = symbol->declaration;
648                 assert(declaration != NULL);
649                 if(declaration->namespc == namespc) {
650                         if(old_declaration == NULL) {
651                                 symbol->declaration = declaration->symbol_next;
652                         } else {
653                                 symbol->declaration = old_declaration;
654                         }
655                 } else {
656                         declaration_t *iter_last = declaration;
657                         declaration_t *iter      = declaration->symbol_next;
658                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
659                                 /* replace an entry? */
660                                 if(iter->namespc == namespc) {
661                                         assert(iter_last != NULL);
662                                         iter_last->symbol_next = old_declaration;
663                                         old_declaration->symbol_next = iter->symbol_next;
664                                         break;
665                                 }
666                         }
667                         assert(iter != NULL);
668                 }
669         }
670
671         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
672 }
673
674 static void environment_pop_to(size_t new_top)
675 {
676         stack_pop_to(&environment_stack, new_top);
677 }
678
679 static void label_pop_to(size_t new_top)
680 {
681         stack_pop_to(&label_stack, new_top);
682 }
683
684
685 static int get_rank(const type_t *type)
686 {
687         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
688          * and esp. footnote 108). However we can't fold constants (yet), so we
689          * can't decide wether unsigned int is possible, while int always works.
690          * (unsigned int would be preferable when possible... for stuff like
691          *  struct { enum { ... } bla : 4; } ) */
692         if(type->type == TYPE_ENUM)
693                 return ATOMIC_TYPE_INT;
694
695         assert(type->type == TYPE_ATOMIC);
696         const atomic_type_t *atomic_type = &type->atomic;
697         atomic_type_type_t   atype       = atomic_type->atype;
698         return atype;
699 }
700
701 static type_t *promote_integer(type_t *type)
702 {
703         if(get_rank(type) < ATOMIC_TYPE_INT)
704                 type = type_int;
705
706         return type;
707 }
708
709 static expression_t *create_cast_expression(expression_t *expression,
710                                             type_t *dest_type)
711 {
712         expression_t *cast = allocate_expression_zero(EXPR_UNARY);
713
714         cast->unary.type    = UNEXPR_CAST;
715         cast->unary.value   = expression;
716         cast->base.datatype = dest_type;
717
718         return cast;
719 }
720
721 static bool is_null_expression(const expression_t *const expression)
722 {
723         if (expression->type != EXPR_CONST)
724                 return false;
725
726         type_t *const type = skip_typeref(expression->base.datatype);
727         if (!is_type_integer(type))
728                 return false;
729
730         return expression->conste.v.int_value == 0;
731 }
732
733 static expression_t *create_implicit_cast(expression_t *expression,
734                                           type_t *dest_type)
735 {
736         type_t *source_type = expression->base.datatype;
737
738         if(source_type == NULL)
739                 return expression;
740
741         source_type = skip_typeref(source_type);
742         dest_type   = skip_typeref(dest_type);
743
744         if(source_type == dest_type)
745                 return expression;
746
747         switch (dest_type->type) {
748                 case TYPE_ENUM:
749                         /* TODO warning for implicitly converting to enum */
750                 case TYPE_ATOMIC:
751                         if (source_type->type != TYPE_ATOMIC &&
752                                         source_type->type != TYPE_ENUM) {
753                                 panic("casting of non-atomic types not implemented yet");
754                         }
755
756                         if(is_type_floating(dest_type) && !is_type_scalar(source_type)) {
757                                 type_error_incompatible("can't cast types",
758                                                 expression->base.source_position, source_type,
759                                                 dest_type);
760                                 return expression;
761                         }
762
763                         return create_cast_expression(expression, dest_type);
764
765                 case TYPE_POINTER:
766                         switch (source_type->type) {
767                                 case TYPE_ATOMIC:
768                                         if (is_null_expression(expression)) {
769                                                 return create_cast_expression(expression, dest_type);
770                                         }
771                                         break;
772
773                                 case TYPE_POINTER:
774                                         if (pointers_compatible(source_type, dest_type)) {
775                                                 return create_cast_expression(expression, dest_type);
776                                         }
777                                         break;
778
779                                 case TYPE_ARRAY: {
780                                         array_type_t   *array_type   = &source_type->array;
781                                         pointer_type_t *pointer_type = &dest_type->pointer;
782                                         if (types_compatible(array_type->element_type,
783                                                                                  pointer_type->points_to)) {
784                                                 return create_cast_expression(expression, dest_type);
785                                         }
786                                         break;
787                                 }
788
789                                 default:
790                                         panic("casting of non-atomic types not implemented yet");
791                         }
792
793                         type_error_incompatible("can't implicitly cast types",
794                                         expression->base.source_position, source_type, dest_type);
795                         return expression;
796
797                 default:
798                         panic("casting of non-atomic types not implemented yet");
799         }
800 }
801
802 /** Implements the rules from Â§ 6.5.16.1 */
803 static void semantic_assign(type_t *orig_type_left, expression_t **right,
804                             const char *context)
805 {
806         type_t *orig_type_right = (*right)->base.datatype;
807
808         if(orig_type_right == NULL)
809                 return;
810
811         type_t *const type_left  = skip_typeref(orig_type_left);
812         type_t *const type_right = skip_typeref(orig_type_right);
813
814         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
815             (is_type_pointer(type_left) && is_null_expression(*right)) ||
816             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
817                 && is_type_pointer(type_right))) {
818                 *right = create_implicit_cast(*right, type_left);
819                 return;
820         }
821
822         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
823                 pointer_type_t *pointer_type_left  = &type_left->pointer;
824                 pointer_type_t *pointer_type_right = &type_right->pointer;
825                 type_t         *points_to_left     = pointer_type_left->points_to;
826                 type_t         *points_to_right    = pointer_type_right->points_to;
827
828                 points_to_left  = skip_typeref(points_to_left);
829                 points_to_right = skip_typeref(points_to_right);
830
831                 if(!is_type_atomic(points_to_left, ATOMIC_TYPE_VOID)
832                                 && !is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)
833                                 && !types_compatible(points_to_left, points_to_right)) {
834                         goto incompatible_assign_types;
835                 }
836
837                 /* the left type has all qualifiers from the right type */
838                 unsigned missing_qualifiers
839                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
840                 if(missing_qualifiers != 0) {
841                         parser_print_error_prefix();
842                         fprintf(stderr, "destination type ");
843                         print_type_quoted(type_left);
844                         fprintf(stderr, " in %s from type ", context);
845                         print_type_quoted(type_right);
846                         fprintf(stderr, " lacks qualifiers '");
847                         print_type_qualifiers(missing_qualifiers);
848                         fprintf(stderr, "' in pointed-to type\n");
849                         return;
850                 }
851
852                 *right = create_implicit_cast(*right, type_left);
853                 return;
854         }
855
856         if (is_type_compound(type_left)
857                         && types_compatible(type_left, type_right)) {
858                 *right = create_implicit_cast(*right, type_left);
859                 return;
860         }
861
862 incompatible_assign_types:
863         /* TODO: improve error message */
864         parser_print_error_prefix();
865         fprintf(stderr, "incompatible types in %s\n", context);
866         parser_print_error_prefix();
867         print_type_quoted(type_left);
868         fputs(" <- ", stderr);
869         print_type_quoted(type_right);
870         fputs("\n", stderr);
871 }
872
873 static expression_t *parse_constant_expression(void)
874 {
875         /* start parsing at precedence 7 (conditional expression) */
876         return parse_sub_expression(7);
877 }
878
879 static expression_t *parse_assignment_expression(void)
880 {
881         /* start parsing at precedence 2 (assignment expression) */
882         return parse_sub_expression(2);
883 }
884
885 typedef struct declaration_specifiers_t  declaration_specifiers_t;
886 struct declaration_specifiers_t {
887         unsigned char storage_class;
888         bool          is_inline;
889         type_t       *type;
890 };
891
892 static void parse_compound_type_entries(void);
893 static declaration_t *parse_declarator(
894                 const declaration_specifiers_t *specifiers, type_t *type,
895                 bool may_be_abstract);
896 static declaration_t *record_declaration(declaration_t *declaration);
897
898 static const char *parse_string_literals(void)
899 {
900         assert(token.type == T_STRING_LITERAL);
901         const char *result = token.v.string;
902
903         next_token();
904
905         while(token.type == T_STRING_LITERAL) {
906                 result = concat_strings(result, token.v.string);
907                 next_token();
908         }
909
910         return result;
911 }
912
913 static void parse_attributes(void)
914 {
915         while(true) {
916                 switch(token.type) {
917                 case T___attribute__: {
918                         next_token();
919
920                         expect_void('(');
921                         int depth = 1;
922                         while(depth > 0) {
923                                 switch(token.type) {
924                                 case T_EOF:
925                                         parse_error("EOF while parsing attribute");
926                                         break;
927                                 case '(':
928                                         next_token();
929                                         depth++;
930                                         break;
931                                 case ')':
932                                         next_token();
933                                         depth--;
934                                         break;
935                                 default:
936                                         next_token();
937                                 }
938                         }
939                         break;
940                 }
941                 case T_asm:
942                         next_token();
943                         expect_void('(');
944                         if(token.type != T_STRING_LITERAL) {
945                                 parse_error_expected("while parsing assembler attribute",
946                                                      T_STRING_LITERAL);
947                                 eat_brace();
948                                 break;
949                         } else {
950                                 parse_string_literals();
951                         }
952                         expect_void(')');
953                         break;
954                 default:
955                         goto attributes_finished;
956                 }
957         }
958
959 attributes_finished:
960         ;
961 }
962
963 #if 0
964 static designator_t *parse_designation(void)
965 {
966         if(token.type != '[' && token.type != '.')
967                 return NULL;
968
969         designator_t *result = NULL;
970         designator_t *last   = NULL;
971
972         while(1) {
973                 designator_t *designator;
974                 switch(token.type) {
975                 case '[':
976                         designator = allocate_ast_zero(sizeof(designator[0]));
977                         next_token();
978                         designator->array_access = parse_constant_expression();
979                         expect(']');
980                         break;
981                 case '.':
982                         designator = allocate_ast_zero(sizeof(designator[0]));
983                         next_token();
984                         if(token.type != T_IDENTIFIER) {
985                                 parse_error_expected("while parsing designator",
986                                                      T_IDENTIFIER, 0);
987                                 return NULL;
988                         }
989                         designator->symbol = token.v.symbol;
990                         next_token();
991                         break;
992                 default:
993                         expect('=');
994                         return result;
995                 }
996
997                 assert(designator != NULL);
998                 if(last != NULL) {
999                         last->next = designator;
1000                 } else {
1001                         result = designator;
1002                 }
1003                 last = designator;
1004         }
1005 }
1006 #endif
1007
1008 static initializer_t *initializer_from_string(array_type_t *type,
1009                                               const char *string)
1010 {
1011         /* TODO: check len vs. size of array type */
1012         (void) type;
1013
1014         initializer_t *initializer = allocate_initializer(INITIALIZER_STRING);
1015         initializer->string.string = string;
1016
1017         return initializer;
1018 }
1019
1020 static initializer_t *initializer_from_expression(type_t *type,
1021                                                   expression_t *expression)
1022 {
1023         /* TODO check that expression is a constant expression */
1024
1025         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
1026         if(type->type == TYPE_ARRAY && expression->type == EXPR_STRING_LITERAL) {
1027                 array_type_t *array_type   = &type->array;
1028                 type_t       *element_type = array_type->element_type;
1029
1030                 if(element_type->type == TYPE_ATOMIC) {
1031                         atomic_type_t      *atomic_type = &element_type->atomic;
1032                         atomic_type_type_t  atype       = atomic_type->atype;
1033
1034                         /* TODO handle wide strings */
1035                         if(atype == ATOMIC_TYPE_CHAR
1036                                         || atype == ATOMIC_TYPE_SCHAR
1037                                         || atype == ATOMIC_TYPE_UCHAR) {
1038
1039                                 string_literal_expression_t *literal = &expression->string;
1040                                 return initializer_from_string(array_type, literal->value);
1041                         }
1042                 }
1043         }
1044
1045         semantic_assign(type, &expression, "initializer");
1046
1047         initializer_t *result = allocate_initializer(INITIALIZER_VALUE);
1048         result->value.value   = expression;
1049
1050         return result;
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 initializer_t *parse_sub_initializer(type_t *type,
1072                                             expression_t *expression,
1073                                             type_t *expression_type)
1074 {
1075         if(is_type_scalar(type)) {
1076                 /* there might be extra {} hierarchies */
1077                 if(token.type == '{') {
1078                         next_token();
1079                         if(!had_initializer_brace_warning) {
1080                                 parse_warning("braces around scalar initializer");
1081                                 had_initializer_brace_warning = true;
1082                         }
1083                         initializer_t *result = parse_sub_initializer(type, NULL, NULL);
1084                         if(token.type == ',') {
1085                                 next_token();
1086                                 /* TODO: warn about excessive elements */
1087                         }
1088                         expect_block('}');
1089                         return result;
1090                 }
1091
1092                 if(expression == NULL) {
1093                         expression = parse_assignment_expression();
1094                 }
1095                 return initializer_from_expression(type, expression);
1096         }
1097
1098         /* TODO: ignore qualifiers, comparing pointers is probably
1099          * not correct */
1100         if(expression != NULL && expression_type == type) {
1101                 initializer_t *result = allocate_initializer(INITIALIZER_VALUE);
1102
1103                 if(type != NULL) {
1104                         semantic_assign(type, &expression, "initializer");
1105                 }
1106                 result->value.value = expression;
1107
1108                 return result;
1109         }
1110
1111         bool read_paren = false;
1112         if(token.type == '{') {
1113                 next_token();
1114                 read_paren = true;
1115         }
1116
1117         /* descend into subtype */
1118         initializer_t  *result = NULL;
1119         initializer_t **elems;
1120         if(type->type == TYPE_ARRAY) {
1121                 array_type_t *array_type   = &type->array;
1122                 type_t       *element_type = array_type->element_type;
1123                 element_type               = skip_typeref(element_type);
1124
1125                 initializer_t *sub;
1126                 had_initializer_brace_warning = false;
1127                 if(expression == NULL) {
1128                         sub = parse_sub_initializer_elem(element_type);
1129                 } else {
1130                         sub = parse_sub_initializer(element_type, expression,
1131                                                     expression_type);
1132                 }
1133
1134                 /* didn't match the subtypes -> try the parent type */
1135                 if(sub == NULL) {
1136                         assert(!read_paren);
1137                         return NULL;
1138                 }
1139
1140                 elems = NEW_ARR_F(initializer_t*, 0);
1141                 ARR_APP1(initializer_t*, elems, sub);
1142
1143                 while(true) {
1144                         if(token.type == '}')
1145                                 break;
1146                         expect_block(',');
1147                         if(token.type == '}')
1148                                 break;
1149
1150                         sub = parse_sub_initializer(element_type, NULL, NULL);
1151                         if(sub == NULL) {
1152                                 /* TODO error, do nicer cleanup */
1153                                 parse_error("member initializer didn't match");
1154                                 DEL_ARR_F(elems);
1155                                 return NULL;
1156                         }
1157                         ARR_APP1(initializer_t*, elems, sub);
1158                 }
1159         } else {
1160                 assert(type->type == TYPE_COMPOUND_STRUCT
1161                                 || type->type == TYPE_COMPOUND_UNION);
1162                 compound_type_t *compound_type = &type->compound;
1163                 context_t       *context       = & compound_type->declaration->context;
1164
1165                 declaration_t *first = context->declarations;
1166                 if(first == NULL)
1167                         return NULL;
1168                 type_t *first_type = first->type;
1169                 first_type         = skip_typeref(first_type);
1170
1171                 initializer_t *sub;
1172                 had_initializer_brace_warning = false;
1173                 if(expression == NULL) {
1174                         sub = parse_sub_initializer_elem(first_type);
1175                 } else {
1176                         sub = parse_sub_initializer(first_type, expression,expression_type);
1177                 }
1178
1179                 /* didn't match the subtypes -> try our parent type */
1180                 if(sub == NULL) {
1181                         assert(!read_paren);
1182                         return NULL;
1183                 }
1184
1185                 elems = NEW_ARR_F(initializer_t*, 0);
1186                 ARR_APP1(initializer_t*, elems, sub);
1187
1188                 declaration_t *iter  = first->next;
1189                 for( ; iter != NULL; iter = iter->next) {
1190                         if(iter->symbol == NULL)
1191                                 continue;
1192                         if(iter->namespc != NAMESPACE_NORMAL)
1193                                 continue;
1194
1195                         if(token.type == '}')
1196                                 break;
1197                         expect_block(',');
1198                         if(token.type == '}')
1199                                 break;
1200
1201                         type_t *iter_type = iter->type;
1202                         iter_type         = skip_typeref(iter_type);
1203
1204                         sub = parse_sub_initializer(iter_type, NULL, NULL);
1205                         if(sub == NULL) {
1206                                 /* TODO error, do nicer cleanup*/
1207                                 parse_error("member initializer didn't match");
1208                                 DEL_ARR_F(elems);
1209                                 return NULL;
1210                         }
1211                         ARR_APP1(initializer_t*, elems, sub);
1212                 }
1213         }
1214
1215         int    len        = ARR_LEN(elems);
1216         size_t elems_size = sizeof(initializer_t*) * len;
1217
1218         initializer_list_t *init = allocate_ast_zero(sizeof(init[0]) + elems_size);
1219
1220         init->initializer.type = INITIALIZER_LIST;
1221         init->len              = len;
1222         memcpy(init->initializers, elems, elems_size);
1223         DEL_ARR_F(elems);
1224
1225         result = (initializer_t*) init;
1226
1227         if(read_paren) {
1228                 if(token.type == ',')
1229                         next_token();
1230                 expect('}');
1231         }
1232         return result;
1233 }
1234
1235 static initializer_t *parse_initializer(type_t *type)
1236 {
1237         initializer_t *result;
1238
1239         type = skip_typeref(type);
1240
1241         if(token.type != '{') {
1242                 expression_t *expression = parse_assignment_expression();
1243                 return initializer_from_expression(type, expression);
1244         }
1245
1246         if(is_type_scalar(type)) {
1247                 /* Â§ 6.7.8.11 */
1248                 eat('{');
1249
1250                 expression_t *expression = parse_assignment_expression();
1251                 result = initializer_from_expression(type, expression);
1252
1253                 if(token.type == ',')
1254                         next_token();
1255
1256                 expect('}');
1257                 return result;
1258         } else {
1259                 result = parse_sub_initializer(type, NULL, NULL);
1260         }
1261
1262         return result;
1263 }
1264
1265
1266
1267 static declaration_t *parse_compound_type_specifier(bool is_struct)
1268 {
1269         if(is_struct) {
1270                 eat(T_struct);
1271         } else {
1272                 eat(T_union);
1273         }
1274
1275         symbol_t      *symbol      = NULL;
1276         declaration_t *declaration = NULL;
1277
1278         if (token.type == T___attribute__) {
1279                 /* TODO */
1280                 parse_attributes();
1281         }
1282
1283         if(token.type == T_IDENTIFIER) {
1284                 symbol = token.v.symbol;
1285                 next_token();
1286
1287                 if(is_struct) {
1288                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1289                 } else {
1290                         declaration = get_declaration(symbol, NAMESPACE_UNION);
1291                 }
1292         } else if(token.type != '{') {
1293                 if(is_struct) {
1294                         parse_error_expected("while parsing struct type specifier",
1295                                              T_IDENTIFIER, '{', 0);
1296                 } else {
1297                         parse_error_expected("while parsing union type specifier",
1298                                              T_IDENTIFIER, '{', 0);
1299                 }
1300
1301                 return NULL;
1302         }
1303
1304         if(declaration == NULL) {
1305                 declaration = allocate_ast_zero(sizeof(declaration[0]));
1306
1307                 if(is_struct) {
1308                         declaration->namespc = NAMESPACE_STRUCT;
1309                 } else {
1310                         declaration->namespc = NAMESPACE_UNION;
1311                 }
1312                 declaration->source_position = token.source_position;
1313                 declaration->symbol          = symbol;
1314                 record_declaration(declaration);
1315         }
1316
1317         if(token.type == '{') {
1318                 if(declaration->init.is_defined) {
1319                         assert(symbol != NULL);
1320                         parser_print_error_prefix();
1321                         fprintf(stderr, "multiple definition of %s %s\n",
1322                                         is_struct ? "struct" : "union", symbol->string);
1323                         declaration->context.declarations = NULL;
1324                 }
1325                 declaration->init.is_defined = true;
1326
1327                 int         top          = environment_top();
1328                 context_t  *last_context = context;
1329                 set_context(& declaration->context);
1330
1331                 parse_compound_type_entries();
1332                 parse_attributes();
1333
1334                 assert(context == & declaration->context);
1335                 set_context(last_context);
1336                 environment_pop_to(top);
1337         }
1338
1339         return declaration;
1340 }
1341
1342 static void parse_enum_entries(enum_type_t *const enum_type)
1343 {
1344         eat('{');
1345
1346         if(token.type == '}') {
1347                 next_token();
1348                 parse_error("empty enum not allowed");
1349                 return;
1350         }
1351
1352         do {
1353                 declaration_t *entry = allocate_ast_zero(sizeof(entry[0]));
1354
1355                 if(token.type != T_IDENTIFIER) {
1356                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1357                         eat_block();
1358                         return;
1359                 }
1360                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
1361                 entry->type            = (type_t*) enum_type;
1362                 entry->symbol          = token.v.symbol;
1363                 entry->source_position = token.source_position;
1364                 next_token();
1365
1366                 if(token.type == '=') {
1367                         next_token();
1368                         entry->init.enum_value = parse_constant_expression();
1369
1370                         /* TODO semantic */
1371                 }
1372
1373                 record_declaration(entry);
1374
1375                 if(token.type != ',')
1376                         break;
1377                 next_token();
1378         } while(token.type != '}');
1379
1380         expect_void('}');
1381 }
1382
1383 static type_t *parse_enum_specifier(void)
1384 {
1385         eat(T_enum);
1386
1387         declaration_t *declaration;
1388         symbol_t      *symbol;
1389
1390         if(token.type == T_IDENTIFIER) {
1391                 symbol = token.v.symbol;
1392                 next_token();
1393
1394                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1395         } else if(token.type != '{') {
1396                 parse_error_expected("while parsing enum type specifier",
1397                                      T_IDENTIFIER, '{', 0);
1398                 return NULL;
1399         } else {
1400                 declaration = NULL;
1401                 symbol      = NULL;
1402         }
1403
1404         if(declaration == NULL) {
1405                 declaration = allocate_ast_zero(sizeof(declaration[0]));
1406
1407                 declaration->namespc       = NAMESPACE_ENUM;
1408                 declaration->source_position = token.source_position;
1409                 declaration->symbol          = symbol;
1410         }
1411
1412         type_t *const type      = allocate_type_zero(TYPE_ENUM);
1413         type->enumt.declaration = declaration;
1414
1415         if(token.type == '{') {
1416                 if(declaration->init.is_defined) {
1417                         parser_print_error_prefix();
1418                         fprintf(stderr, "multiple definitions of enum %s\n",
1419                                 symbol->string);
1420                 }
1421                 record_declaration(declaration);
1422                 declaration->init.is_defined = 1;
1423
1424                 parse_enum_entries(&type->enumt);
1425                 parse_attributes();
1426         }
1427
1428         return type;
1429 }
1430
1431 /**
1432  * if a symbol is a typedef to another type, return true
1433  */
1434 static bool is_typedef_symbol(symbol_t *symbol)
1435 {
1436         const declaration_t *const declaration =
1437                 get_declaration(symbol, NAMESPACE_NORMAL);
1438         return
1439                 declaration != NULL &&
1440                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1441 }
1442
1443 static type_t *parse_typeof(void)
1444 {
1445         eat(T___typeof__);
1446
1447         type_t *type;
1448
1449         expect('(');
1450
1451         expression_t *expression  = NULL;
1452
1453 restart:
1454         switch(token.type) {
1455         case T___extension__:
1456                 /* this can be a prefix to a typename or an expression */
1457                 /* we simply eat it now. */
1458                 do {
1459                         next_token();
1460                 } while(token.type == T___extension__);
1461                 goto restart;
1462
1463         case T_IDENTIFIER:
1464                 if(is_typedef_symbol(token.v.symbol)) {
1465                         type = parse_typename();
1466                 } else {
1467                         expression = parse_expression();
1468                         type       = expression->base.datatype;
1469                 }
1470                 break;
1471
1472         TYPENAME_START
1473                 type = parse_typename();
1474                 break;
1475
1476         default:
1477                 expression = parse_expression();
1478                 type       = expression->base.datatype;
1479                 break;
1480         }
1481
1482         expect(')');
1483
1484         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF);
1485         typeof_type->typeoft.expression  = expression;
1486         typeof_type->typeoft.typeof_type = type;
1487
1488         return typeof_type;
1489 }
1490
1491 typedef enum {
1492         SPECIFIER_SIGNED    = 1 << 0,
1493         SPECIFIER_UNSIGNED  = 1 << 1,
1494         SPECIFIER_LONG      = 1 << 2,
1495         SPECIFIER_INT       = 1 << 3,
1496         SPECIFIER_DOUBLE    = 1 << 4,
1497         SPECIFIER_CHAR      = 1 << 5,
1498         SPECIFIER_SHORT     = 1 << 6,
1499         SPECIFIER_LONG_LONG = 1 << 7,
1500         SPECIFIER_FLOAT     = 1 << 8,
1501         SPECIFIER_BOOL      = 1 << 9,
1502         SPECIFIER_VOID      = 1 << 10,
1503 #ifdef PROVIDE_COMPLEX
1504         SPECIFIER_COMPLEX   = 1 << 11,
1505         SPECIFIER_IMAGINARY = 1 << 12,
1506 #endif
1507 } specifiers_t;
1508
1509 static type_t *create_builtin_type(symbol_t *symbol)
1510 {
1511         type_t *type            = allocate_type_zero(TYPE_BUILTIN);
1512         type->builtin.symbol    = symbol;
1513         /* TODO... */
1514         type->builtin.real_type = type_int;
1515
1516         return type;
1517 }
1518
1519 static type_t *get_typedef_type(symbol_t *symbol)
1520 {
1521         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1522         if(declaration == NULL
1523                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1524                 return NULL;
1525
1526         type_t *type               = allocate_type_zero(TYPE_TYPEDEF);
1527         type->typedeft.declaration = declaration;
1528
1529         return type;
1530 }
1531
1532 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1533 {
1534         type_t   *type            = NULL;
1535         unsigned  type_qualifiers = 0;
1536         unsigned  type_specifiers = 0;
1537         int       newtype         = 0;
1538
1539         while(true) {
1540                 switch(token.type) {
1541
1542                 /* storage class */
1543 #define MATCH_STORAGE_CLASS(token, class)                                \
1544                 case token:                                                      \
1545                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1546                                 parse_error("multiple storage classes in declaration "   \
1547                                             "specifiers");                               \
1548                         }                                                            \
1549                         specifiers->storage_class = class;                           \
1550                         next_token();                                                \
1551                         break;
1552
1553                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1554                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1555                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1556                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1557                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1558
1559                 case T___thread:
1560                         switch (specifiers->storage_class) {
1561                                 case STORAGE_CLASS_NONE:
1562                                         specifiers->storage_class = STORAGE_CLASS_THREAD;
1563                                         break;
1564
1565                                 case STORAGE_CLASS_EXTERN:
1566                                         specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
1567                                         break;
1568
1569                                 case STORAGE_CLASS_STATIC:
1570                                         specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
1571                                         break;
1572
1573                                 default:
1574                                         parse_error("multiple storage classes in declaration specifiers");
1575                                         break;
1576                         }
1577                         next_token();
1578                         break;
1579
1580                 /* type qualifiers */
1581 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1582                 case token:                                                     \
1583                         type_qualifiers |= qualifier;                               \
1584                         next_token();                                               \
1585                         break;
1586
1587                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1588                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1589                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1590
1591                 case T___extension__:
1592                         /* TODO */
1593                         next_token();
1594                         break;
1595
1596                 /* type specifiers */
1597 #define MATCH_SPECIFIER(token, specifier, name)                         \
1598                 case token:                                                     \
1599                         next_token();                                               \
1600                         if(type_specifiers & specifier) {                           \
1601                                 parse_error("multiple " name " type specifiers given"); \
1602                         } else {                                                    \
1603                                 type_specifiers |= specifier;                           \
1604                         }                                                           \
1605                         break;
1606
1607                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1608                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1609                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1610                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1611                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1612                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1613                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1614                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1615                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1616 #ifdef PROVIDE_COMPLEX
1617                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1618                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1619 #endif
1620                 case T_inline:
1621                         next_token();
1622                         specifiers->is_inline = true;
1623                         break;
1624
1625                 case T_long:
1626                         next_token();
1627                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1628                                 parse_error("multiple type specifiers given");
1629                         } else if(type_specifiers & SPECIFIER_LONG) {
1630                                 type_specifiers |= SPECIFIER_LONG_LONG;
1631                         } else {
1632                                 type_specifiers |= SPECIFIER_LONG;
1633                         }
1634                         break;
1635
1636                 /* TODO: if type != NULL for the following rules should issue
1637                  * an error */
1638                 case T_struct: {
1639                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1640
1641                         type->compound.declaration = parse_compound_type_specifier(true);
1642                         break;
1643                 }
1644                 case T_union: {
1645                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1646
1647                         type->compound.declaration = parse_compound_type_specifier(false);
1648                         break;
1649                 }
1650                 case T_enum:
1651                         type = parse_enum_specifier();
1652                         break;
1653                 case T___typeof__:
1654                         type = parse_typeof();
1655                         break;
1656                 case T___builtin_va_list:
1657                         type = create_builtin_type(token.v.symbol);
1658                         next_token();
1659                         break;
1660
1661                 case T___attribute__:
1662                         /* TODO */
1663                         parse_attributes();
1664                         break;
1665
1666                 case T_IDENTIFIER: {
1667                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1668
1669                         if(typedef_type == NULL)
1670                                 goto finish_specifiers;
1671
1672                         next_token();
1673                         type = typedef_type;
1674                         break;
1675                 }
1676
1677                 /* function specifier */
1678                 default:
1679                         goto finish_specifiers;
1680                 }
1681         }
1682
1683 finish_specifiers:
1684
1685         if(type == NULL) {
1686                 atomic_type_type_t atomic_type;
1687
1688                 /* match valid basic types */
1689                 switch(type_specifiers) {
1690                 case SPECIFIER_VOID:
1691                         atomic_type = ATOMIC_TYPE_VOID;
1692                         break;
1693                 case SPECIFIER_CHAR:
1694                         atomic_type = ATOMIC_TYPE_CHAR;
1695                         break;
1696                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1697                         atomic_type = ATOMIC_TYPE_SCHAR;
1698                         break;
1699                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1700                         atomic_type = ATOMIC_TYPE_UCHAR;
1701                         break;
1702                 case SPECIFIER_SHORT:
1703                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1704                 case SPECIFIER_SHORT | SPECIFIER_INT:
1705                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1706                         atomic_type = ATOMIC_TYPE_SHORT;
1707                         break;
1708                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1709                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1710                         atomic_type = ATOMIC_TYPE_USHORT;
1711                         break;
1712                 case SPECIFIER_INT:
1713                 case SPECIFIER_SIGNED:
1714                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1715                         atomic_type = ATOMIC_TYPE_INT;
1716                         break;
1717                 case SPECIFIER_UNSIGNED:
1718                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1719                         atomic_type = ATOMIC_TYPE_UINT;
1720                         break;
1721                 case SPECIFIER_LONG:
1722                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1723                 case SPECIFIER_LONG | SPECIFIER_INT:
1724                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1725                         atomic_type = ATOMIC_TYPE_LONG;
1726                         break;
1727                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1728                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1729                         atomic_type = ATOMIC_TYPE_ULONG;
1730                         break;
1731                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1732                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1733                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1734                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1735                         | SPECIFIER_INT:
1736                         atomic_type = ATOMIC_TYPE_LONGLONG;
1737                         break;
1738                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1739                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1740                         | SPECIFIER_INT:
1741                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1742                         break;
1743                 case SPECIFIER_FLOAT:
1744                         atomic_type = ATOMIC_TYPE_FLOAT;
1745                         break;
1746                 case SPECIFIER_DOUBLE:
1747                         atomic_type = ATOMIC_TYPE_DOUBLE;
1748                         break;
1749                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1750                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1751                         break;
1752                 case SPECIFIER_BOOL:
1753                         atomic_type = ATOMIC_TYPE_BOOL;
1754                         break;
1755 #ifdef PROVIDE_COMPLEX
1756                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1757                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1758                         break;
1759                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1760                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1761                         break;
1762                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1763                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1764                         break;
1765                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1766                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1767                         break;
1768                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1769                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1770                         break;
1771                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1772                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1773                         break;
1774 #endif
1775                 default:
1776                         /* invalid specifier combination, give an error message */
1777                         if(type_specifiers == 0) {
1778 #ifndef STRICT_C99
1779                                 parse_warning("no type specifiers in declaration (using int)");
1780                                 atomic_type = ATOMIC_TYPE_INT;
1781                                 break;
1782 #else
1783                                 parse_error("no type specifiers given in declaration");
1784 #endif
1785                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
1786                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
1787                                 parse_error("signed and unsigned specifiers gives");
1788                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
1789                                 parse_error("only integer types can be signed or unsigned");
1790                         } else {
1791                                 parse_error("multiple datatypes in declaration");
1792                         }
1793                         atomic_type = ATOMIC_TYPE_INVALID;
1794                 }
1795
1796                 type               = allocate_type_zero(TYPE_ATOMIC);
1797                 type->atomic.atype = atomic_type;
1798                 newtype            = 1;
1799         } else {
1800                 if(type_specifiers != 0) {
1801                         parse_error("multiple datatypes in declaration");
1802                 }
1803         }
1804
1805         type->base.qualifiers = type_qualifiers;
1806
1807         type_t *result = typehash_insert(type);
1808         if(newtype && result != type) {
1809                 free_type(type);
1810         }
1811
1812         specifiers->type = result;
1813 }
1814
1815 static type_qualifiers_t parse_type_qualifiers(void)
1816 {
1817         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
1818
1819         while(true) {
1820                 switch(token.type) {
1821                 /* type qualifiers */
1822                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1823                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1824                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1825
1826                 default:
1827                         return type_qualifiers;
1828                 }
1829         }
1830 }
1831
1832 static void parse_identifier_list(void)
1833 {
1834         while(true) {
1835                 if(token.type != T_IDENTIFIER) {
1836                         parse_error_expected("while parsing parameter identifier list",
1837                                              T_IDENTIFIER, 0);
1838                         return;
1839                 }
1840                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
1841                 declaration->symbol        = token.v.symbol;
1842
1843                 next_token();
1844
1845                 if(token.type != ',')
1846                         break;
1847                 next_token();
1848         }
1849 }
1850
1851 static declaration_t *parse_parameter(void)
1852 {
1853         declaration_specifiers_t specifiers;
1854         memset(&specifiers, 0, sizeof(specifiers));
1855
1856         parse_declaration_specifiers(&specifiers);
1857
1858         declaration_t *declaration
1859                 = parse_declarator(&specifiers, specifiers.type, true);
1860
1861         /* TODO check declaration constraints for parameters */
1862         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
1863                 parse_error("typedef not allowed in parameter list");
1864         }
1865
1866         /* Array as last part of a paramter type is just syntactic sugar.  Turn it
1867          * into a pointer */
1868         if (declaration->type->type == TYPE_ARRAY) {
1869                 const array_type_t *const arr_type = &declaration->type->array;
1870                 type_t *element_type = arr_type->element_type;
1871                 declaration->type = make_pointer_type(element_type, TYPE_QUALIFIER_NONE);
1872         }
1873
1874         return declaration;
1875 }
1876
1877 static declaration_t *parse_parameters(function_type_t *type)
1878 {
1879         if(token.type == T_IDENTIFIER) {
1880                 symbol_t      *symbol = token.v.symbol;
1881                 if(!is_typedef_symbol(symbol)) {
1882                         /* TODO: K&R style C parameters */
1883                         parse_identifier_list();
1884                         return NULL;
1885                 }
1886         }
1887
1888         if(token.type == ')') {
1889                 type->unspecified_parameters = 1;
1890                 return NULL;
1891         }
1892         if(token.type == T_void && look_ahead(1)->type == ')') {
1893                 next_token();
1894                 return NULL;
1895         }
1896
1897         declaration_t        *declarations = NULL;
1898         declaration_t        *declaration;
1899         declaration_t        *last_declaration = NULL;
1900         function_parameter_t *parameter;
1901         function_parameter_t *last_parameter = NULL;
1902
1903         while(true) {
1904                 switch(token.type) {
1905                 case T_DOTDOTDOT:
1906                         next_token();
1907                         type->variadic = 1;
1908                         return declarations;
1909
1910                 case T_IDENTIFIER:
1911                 case T___extension__:
1912                 DECLARATION_START
1913                         declaration = parse_parameter();
1914
1915                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
1916                         memset(parameter, 0, sizeof(parameter[0]));
1917                         parameter->type = declaration->type;
1918
1919                         if(last_parameter != NULL) {
1920                                 last_declaration->next = declaration;
1921                                 last_parameter->next   = parameter;
1922                         } else {
1923                                 type->parameters = parameter;
1924                                 declarations     = declaration;
1925                         }
1926                         last_parameter   = parameter;
1927                         last_declaration = declaration;
1928                         break;
1929
1930                 default:
1931                         return declarations;
1932                 }
1933                 if(token.type != ',')
1934                         return declarations;
1935                 next_token();
1936         }
1937 }
1938
1939 typedef enum {
1940         CONSTRUCT_INVALID,
1941         CONSTRUCT_POINTER,
1942         CONSTRUCT_FUNCTION,
1943         CONSTRUCT_ARRAY
1944 } construct_type_type_t;
1945
1946 typedef struct construct_type_t construct_type_t;
1947 struct construct_type_t {
1948         construct_type_type_t  type;
1949         construct_type_t      *next;
1950 };
1951
1952 typedef struct parsed_pointer_t parsed_pointer_t;
1953 struct parsed_pointer_t {
1954         construct_type_t  construct_type;
1955         type_qualifiers_t type_qualifiers;
1956 };
1957
1958 typedef struct construct_function_type_t construct_function_type_t;
1959 struct construct_function_type_t {
1960         construct_type_t  construct_type;
1961         type_t           *function_type;
1962 };
1963
1964 typedef struct parsed_array_t parsed_array_t;
1965 struct parsed_array_t {
1966         construct_type_t  construct_type;
1967         type_qualifiers_t type_qualifiers;
1968         bool              is_static;
1969         bool              is_variable;
1970         expression_t     *size;
1971 };
1972
1973 typedef struct construct_base_type_t construct_base_type_t;
1974 struct construct_base_type_t {
1975         construct_type_t  construct_type;
1976         type_t           *type;
1977 };
1978
1979 static construct_type_t *parse_pointer_declarator(void)
1980 {
1981         eat('*');
1982
1983         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
1984         memset(pointer, 0, sizeof(pointer[0]));
1985         pointer->construct_type.type = CONSTRUCT_POINTER;
1986         pointer->type_qualifiers     = parse_type_qualifiers();
1987
1988         return (construct_type_t*) pointer;
1989 }
1990
1991 static construct_type_t *parse_array_declarator(void)
1992 {
1993         eat('[');
1994
1995         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
1996         memset(array, 0, sizeof(array[0]));
1997         array->construct_type.type = CONSTRUCT_ARRAY;
1998
1999         if(token.type == T_static) {
2000                 array->is_static = true;
2001                 next_token();
2002         }
2003
2004         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2005         if(type_qualifiers != 0) {
2006                 if(token.type == T_static) {
2007                         array->is_static = true;
2008                         next_token();
2009                 }
2010         }
2011         array->type_qualifiers = type_qualifiers;
2012
2013         if(token.type == '*' && look_ahead(1)->type == ']') {
2014                 array->is_variable = true;
2015                 next_token();
2016         } else if(token.type != ']') {
2017                 array->size = parse_assignment_expression();
2018         }
2019
2020         expect(']');
2021
2022         return (construct_type_t*) array;
2023 }
2024
2025 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2026 {
2027         eat('(');
2028
2029         type_t *type = allocate_type_zero(TYPE_FUNCTION);
2030
2031         declaration_t *parameters = parse_parameters(&type->function);
2032         if(declaration != NULL) {
2033                 declaration->context.declarations = parameters;
2034         }
2035
2036         construct_function_type_t *construct_function_type =
2037                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2038         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2039         construct_function_type->construct_type.type = CONSTRUCT_FUNCTION;
2040         construct_function_type->function_type       = type;
2041
2042         expect(')');
2043
2044         return (construct_type_t*) construct_function_type;
2045 }
2046
2047 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2048                 bool may_be_abstract)
2049 {
2050         /* construct a single linked list of construct_type_t's which describe
2051          * how to construct the final declarator type */
2052         construct_type_t *first = NULL;
2053         construct_type_t *last  = NULL;
2054
2055         /* pointers */
2056         while(token.type == '*') {
2057                 construct_type_t *type = parse_pointer_declarator();
2058
2059                 if(last == NULL) {
2060                         first = type;
2061                         last  = type;
2062                 } else {
2063                         last->next = type;
2064                         last       = type;
2065                 }
2066         }
2067
2068         /* TODO: find out if this is correct */
2069         parse_attributes();
2070
2071         construct_type_t *inner_types = NULL;
2072
2073         switch(token.type) {
2074         case T_IDENTIFIER:
2075                 if(declaration == NULL) {
2076                         parse_error("no identifier expected in typename");
2077                 } else {
2078                         declaration->symbol          = token.v.symbol;
2079                         declaration->source_position = token.source_position;
2080                 }
2081                 next_token();
2082                 break;
2083         case '(':
2084                 next_token();
2085                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2086                 expect(')');
2087                 break;
2088         default:
2089                 if(may_be_abstract)
2090                         break;
2091                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2092                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2093                  * eat '}' */
2094                 if(token.type == '}' && current_function == NULL) {
2095                         next_token();
2096                 } else {
2097                         eat_statement();
2098                 }
2099                 return NULL;
2100         }
2101
2102         construct_type_t *p = last;
2103
2104         while(true) {
2105                 construct_type_t *type;
2106                 switch(token.type) {
2107                 case '(':
2108                         type = parse_function_declarator(declaration);
2109                         break;
2110                 case '[':
2111                         type = parse_array_declarator();
2112                         break;
2113                 default:
2114                         goto declarator_finished;
2115                 }
2116
2117                 /* insert in the middle of the list (behind p) */
2118                 if(p != NULL) {
2119                         type->next = p->next;
2120                         p->next    = type;
2121                 } else {
2122                         type->next = first;
2123                         first      = type;
2124                 }
2125                 if(last == p) {
2126                         last = type;
2127                 }
2128         }
2129
2130 declarator_finished:
2131         parse_attributes();
2132
2133         /* append inner_types at the end of the list, we don't to set last anymore
2134          * as it's not needed anymore */
2135         if(last == NULL) {
2136                 assert(first == NULL);
2137                 first = inner_types;
2138         } else {
2139                 last->next = inner_types;
2140         }
2141
2142         return first;
2143 }
2144
2145 static type_t *construct_declarator_type(construct_type_t *construct_list,
2146                                          type_t *type)
2147 {
2148         construct_type_t *iter = construct_list;
2149         for( ; iter != NULL; iter = iter->next) {
2150                 switch(iter->type) {
2151                 case CONSTRUCT_INVALID:
2152                         panic("invalid type construction found");
2153                 case CONSTRUCT_FUNCTION: {
2154                         construct_function_type_t *construct_function_type
2155                                 = (construct_function_type_t*) iter;
2156
2157                         type_t *function_type = construct_function_type->function_type;
2158
2159                         function_type->function.result_type = type;
2160
2161                         type = function_type;
2162                         break;
2163                 }
2164
2165                 case CONSTRUCT_POINTER: {
2166                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2167                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER);
2168                         pointer_type->pointer.points_to  = type;
2169                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2170
2171                         type = pointer_type;
2172                         break;
2173                 }
2174
2175                 case CONSTRUCT_ARRAY: {
2176                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2177                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY);
2178
2179                         array_type->base.qualifiers    = parsed_array->type_qualifiers;
2180                         array_type->array.element_type = type;
2181                         array_type->array.is_static    = parsed_array->is_static;
2182                         array_type->array.is_variable  = parsed_array->is_variable;
2183                         array_type->array.size         = parsed_array->size;
2184
2185                         type = array_type;
2186                         break;
2187                 }
2188                 }
2189
2190                 type_t *hashed_type = typehash_insert(type);
2191                 if(hashed_type != type) {
2192                         /* the function type was constructed earlier freeing it here will
2193                          * destroy other types... */
2194                         if(iter->type != CONSTRUCT_FUNCTION) {
2195                                 free_type(type);
2196                         }
2197                         type = hashed_type;
2198                 }
2199         }
2200
2201         return type;
2202 }
2203
2204 static declaration_t *parse_declarator(
2205                 const declaration_specifiers_t *specifiers,
2206                 type_t *type, bool may_be_abstract)
2207 {
2208         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2209         declaration->storage_class = specifiers->storage_class;
2210         declaration->is_inline     = specifiers->is_inline;
2211
2212         construct_type_t *construct_type
2213                 = parse_inner_declarator(declaration, may_be_abstract);
2214         declaration->type = construct_declarator_type(construct_type, type);
2215
2216         if(construct_type != NULL) {
2217                 obstack_free(&temp_obst, construct_type);
2218         }
2219
2220         return declaration;
2221 }
2222
2223 static type_t *parse_abstract_declarator(type_t *base_type)
2224 {
2225         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2226
2227         type_t *result = construct_declarator_type(construct_type, base_type);
2228         if(construct_type != NULL) {
2229                 obstack_free(&temp_obst, construct_type);
2230         }
2231
2232         return result;
2233 }
2234
2235 static declaration_t *record_declaration(declaration_t *declaration)
2236 {
2237         assert(context != NULL);
2238
2239         symbol_t *symbol = declaration->symbol;
2240         if(symbol != NULL) {
2241                 declaration_t *alias = environment_push(declaration);
2242                 if(alias != declaration)
2243                         return alias;
2244         } else {
2245                 declaration->parent_context = context;
2246         }
2247
2248         if(last_declaration != NULL) {
2249                 last_declaration->next = declaration;
2250         } else {
2251                 context->declarations = declaration;
2252         }
2253         last_declaration = declaration;
2254
2255         return declaration;
2256 }
2257
2258 static void parser_error_multiple_definition(declaration_t *previous,
2259                                              declaration_t *declaration)
2260 {
2261         parser_print_error_prefix_pos(declaration->source_position);
2262         fprintf(stderr, "multiple definition of symbol '%s'\n",
2263                 declaration->symbol->string);
2264         parser_print_error_prefix_pos(previous->source_position);
2265         fprintf(stderr, "this is the location of the previous definition.\n");
2266 }
2267
2268 static void parse_init_declarators(const declaration_specifiers_t *specifiers)
2269 {
2270         while(true) {
2271                 declaration_t *ndeclaration
2272                         = parse_declarator(specifiers, specifiers->type, false);
2273
2274                 declaration_t *declaration = record_declaration(ndeclaration);
2275
2276                 type_t *orig_type = declaration->type;
2277                 type_t *type      = skip_typeref(orig_type);
2278                 if(type->type != TYPE_FUNCTION && declaration->is_inline) {
2279                         parser_print_warning_prefix_pos(declaration->source_position);
2280                         fprintf(stderr, "variable '%s' declared 'inline'\n",
2281                                 declaration->symbol->string);
2282                 }
2283
2284                 if(token.type == '=') {
2285                         next_token();
2286
2287                         /* TODO: check that this is an allowed type (no function type) */
2288
2289                         if(declaration->init.initializer != NULL) {
2290                                 parser_error_multiple_definition(declaration, ndeclaration);
2291                         }
2292
2293                         initializer_t *initializer = parse_initializer(type);
2294
2295                         if(type->type == TYPE_ARRAY && initializer != NULL) {
2296                                 array_type_t *array_type = &type->array;
2297
2298                                 if(array_type->size == NULL) {
2299                                         expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2300
2301                                         cnst->base.datatype = type_size_t;
2302
2303                                         if(initializer->type == INITIALIZER_LIST) {
2304                                                 initializer_list_t *list = &initializer->list;
2305                                                 cnst->conste.v.int_value = list->len;
2306                                         } else {
2307                                                 assert(initializer->type == INITIALIZER_STRING);
2308                                                 initializer_string_t *string = &initializer->string;
2309                                                 cnst->conste.v.int_value = strlen(string->string) + 1;
2310                                         }
2311
2312                                         array_type->size = cnst;
2313                                 }
2314                         }
2315
2316
2317                         ndeclaration->init.initializer = initializer;
2318                 } else if(token.type == '{') {
2319                         if(type->type != TYPE_FUNCTION) {
2320                                 parser_print_error_prefix();
2321                                 fprintf(stderr, "declarator '");
2322                                 print_type_ext(orig_type, declaration->symbol, NULL);
2323                                 fprintf(stderr, "' has a body but is not a function type.\n");
2324                                 eat_block();
2325                                 continue;
2326                         }
2327                         function_type_t *function_type = &type->function;
2328                         /* Â§ 6.7.5.3 (14) a function definition with () */
2329                         if(function_type->unspecified_parameters) {
2330                                 type_t *duplicate = duplicate_type(type);
2331                                 duplicate->function.unspecified_parameters = false;
2332
2333                                 type = typehash_insert(duplicate);
2334                                 if(type != duplicate) {
2335                                         obstack_free(type_obst, duplicate);
2336                                 }
2337                                 function_type = &type->function;
2338                         }
2339
2340                         if(declaration->init.statement != NULL) {
2341                                 parser_error_multiple_definition(declaration, ndeclaration);
2342                         }
2343                         if(ndeclaration != declaration) {
2344                                 memcpy(&declaration->context, &ndeclaration->context,
2345                                        sizeof(declaration->context));
2346                         }
2347
2348                         int         top          = environment_top();
2349                         context_t  *last_context = context;
2350                         set_context(&declaration->context);
2351
2352                         /* push function parameters */
2353                         declaration_t *parameter = declaration->context.declarations;
2354                         for( ; parameter != NULL; parameter = parameter->next) {
2355                                 environment_push(parameter);
2356                         }
2357
2358                         int            label_stack_top      = label_top();
2359                         declaration_t *old_current_function = current_function;
2360                         current_function                    = declaration;
2361
2362                         statement_t *statement = parse_compound_statement();
2363
2364                         assert(current_function == declaration);
2365                         current_function = old_current_function;
2366                         label_pop_to(label_stack_top);
2367
2368                         assert(context == &declaration->context);
2369                         set_context(last_context);
2370                         environment_pop_to(top);
2371
2372                         declaration->init.statement = statement;
2373                         return;
2374                 }
2375
2376                 if(token.type != ',')
2377                         break;
2378                 next_token();
2379         }
2380         expect_void(';');
2381 }
2382
2383 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2384 {
2385         while(1) {
2386                 if(token.type == ':') {
2387                         next_token();
2388                         parse_constant_expression();
2389                         /* TODO (bitfields) */
2390                 } else {
2391                         declaration_t *declaration
2392                                 = parse_declarator(specifiers, specifiers->type, true);
2393
2394                         /* TODO: check constraints for struct declarations */
2395                         /* TODO: check for doubled fields */
2396                         record_declaration(declaration);
2397
2398                         if(token.type == ':') {
2399                                 next_token();
2400                                 parse_constant_expression();
2401                                 /* TODO (bitfields) */
2402                         }
2403                 }
2404
2405                 if(token.type != ',')
2406                         break;
2407                 next_token();
2408         }
2409         expect_void(';');
2410 }
2411
2412 static void parse_compound_type_entries(void)
2413 {
2414         eat('{');
2415
2416         while(token.type != '}' && token.type != T_EOF) {
2417                 declaration_specifiers_t specifiers;
2418                 memset(&specifiers, 0, sizeof(specifiers));
2419                 parse_declaration_specifiers(&specifiers);
2420
2421                 parse_struct_declarators(&specifiers);
2422         }
2423         if(token.type == T_EOF) {
2424                 parse_error("unexpected error while parsing struct");
2425         }
2426         next_token();
2427 }
2428
2429 static void parse_declaration(void)
2430 {
2431         source_position_t source_position = token.source_position;
2432
2433         declaration_specifiers_t specifiers;
2434         memset(&specifiers, 0, sizeof(specifiers));
2435         parse_declaration_specifiers(&specifiers);
2436
2437         if(token.type == ';') {
2438                 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
2439                         parse_warning_pos(source_position,
2440                                           "useless keyword in empty declaration");
2441                 }
2442                 switch (specifiers.type->type) {
2443                         case TYPE_COMPOUND_STRUCT:
2444                         case TYPE_COMPOUND_UNION: {
2445                                 const compound_type_t *const comp_type
2446                                         = &specifiers.type->compound;
2447                                 if (comp_type->declaration->symbol == NULL) {
2448                                         parse_warning_pos(source_position,
2449                                                                                                                 "unnamed struct/union that defines no instances");
2450                                 }
2451                                 break;
2452                         }
2453
2454                         case TYPE_ENUM: break;
2455
2456                         default:
2457                                 parse_warning_pos(source_position, "empty declaration");
2458                                 break;
2459                 }
2460
2461                 next_token();
2462
2463                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2464
2465                 declaration->type            = specifiers.type;
2466                 declaration->storage_class   = specifiers.storage_class;
2467                 declaration->source_position = source_position;
2468                 record_declaration(declaration);
2469                 return;
2470         }
2471         parse_init_declarators(&specifiers);
2472 }
2473
2474 static type_t *parse_typename(void)
2475 {
2476         declaration_specifiers_t specifiers;
2477         memset(&specifiers, 0, sizeof(specifiers));
2478         parse_declaration_specifiers(&specifiers);
2479         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2480                 /* TODO: improve error message, user does probably not know what a
2481                  * storage class is...
2482                  */
2483                 parse_error("typename may not have a storage class");
2484         }
2485
2486         type_t *result = parse_abstract_declarator(specifiers.type);
2487
2488         return result;
2489 }
2490
2491
2492
2493
2494 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2495 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2496                                                           expression_t *left);
2497
2498 typedef struct expression_parser_function_t expression_parser_function_t;
2499 struct expression_parser_function_t {
2500         unsigned                         precedence;
2501         parse_expression_function        parser;
2502         unsigned                         infix_precedence;
2503         parse_expression_infix_function  infix_parser;
2504 };
2505
2506 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2507
2508 static expression_t *make_invalid_expression(void)
2509 {
2510         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2511         expression->base.source_position = token.source_position;
2512         return expression;
2513 }
2514
2515 static expression_t *expected_expression_error(void)
2516 {
2517         parser_print_error_prefix();
2518         fprintf(stderr, "expected expression, got token ");
2519         print_token(stderr, & token);
2520         fprintf(stderr, "\n");
2521
2522         next_token();
2523
2524         return make_invalid_expression();
2525 }
2526
2527 static expression_t *parse_string_const(void)
2528 {
2529         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2530         cnst->base.datatype = type_string;
2531         cnst->string.value  = parse_string_literals();
2532
2533         return cnst;
2534 }
2535
2536 static expression_t *parse_int_const(void)
2537 {
2538         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2539         cnst->base.datatype      = token.datatype;
2540         cnst->conste.v.int_value = token.v.intvalue;
2541
2542         next_token();
2543
2544         return cnst;
2545 }
2546
2547 static expression_t *parse_float_const(void)
2548 {
2549         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2550         cnst->base.datatype        = token.datatype;
2551         cnst->conste.v.float_value = token.v.floatvalue;
2552
2553         next_token();
2554
2555         return cnst;
2556 }
2557
2558 static declaration_t *create_implicit_function(symbol_t *symbol,
2559                 const source_position_t source_position)
2560 {
2561         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2562         ntype->function.result_type            = type_int;
2563         ntype->function.unspecified_parameters = true;
2564
2565         type_t *type = typehash_insert(ntype);
2566         if(type != ntype) {
2567                 free_type(ntype);
2568         }
2569
2570         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2571
2572         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2573         declaration->type            = type;
2574         declaration->symbol          = symbol;
2575         declaration->source_position = source_position;
2576
2577         /* prepend the implicit definition to the global context
2578          * this is safe since the symbol wasn't declared as anything else yet
2579          */
2580         assert(symbol->declaration == NULL);
2581
2582         context_t *last_context = context;
2583         context = global_context;
2584
2585         environment_push(declaration);
2586         declaration->next     = context->declarations;
2587         context->declarations = declaration;
2588
2589         context = last_context;
2590
2591         return declaration;
2592 }
2593
2594 static type_t *make_function_1_type(type_t *result_type, type_t *argument_type)
2595 {
2596         function_parameter_t *parameter
2597                 = obstack_alloc(type_obst, sizeof(parameter[0]));
2598         memset(parameter, 0, sizeof(parameter[0]));
2599         parameter->type = argument_type;
2600
2601         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
2602         type->function.result_type = result_type;
2603         type->function.parameters  = parameter;
2604
2605         type_t *result = typehash_insert(type);
2606         if(result != type) {
2607                 free_type(type);
2608         }
2609
2610         return result;
2611 }
2612
2613 static type_t *get_builtin_symbol_type(symbol_t *symbol)
2614 {
2615         switch(symbol->ID) {
2616         case T___builtin_alloca:
2617                 return make_function_1_type(type_void_ptr, type_size_t);
2618         default:
2619                 panic("not implemented builtin symbol found");
2620         }
2621 }
2622
2623 /**
2624  * performs automatic type cast as described in Â§ 6.3.2.1
2625  */
2626 static type_t *automatic_type_conversion(type_t *type)
2627 {
2628         if(type == NULL)
2629                 return NULL;
2630
2631         if(type->type == TYPE_ARRAY) {
2632                 array_type_t *array_type   = &type->array;
2633                 type_t       *element_type = array_type->element_type;
2634                 unsigned      qualifiers   = array_type->type.qualifiers;
2635
2636                 return make_pointer_type(element_type, qualifiers);
2637         }
2638
2639         if(type->type == TYPE_FUNCTION) {
2640                 return make_pointer_type(type, TYPE_QUALIFIER_NONE);
2641         }
2642
2643         return type;
2644 }
2645
2646 /**
2647  * reverts the automatic casts of array to pointer types and function
2648  * to function-pointer types as defined Â§ 6.3.2.1
2649  */
2650 type_t *revert_automatic_type_conversion(const expression_t *expression)
2651 {
2652         if(expression->base.datatype == NULL)
2653                 return NULL;
2654
2655         switch(expression->type) {
2656         case EXPR_REFERENCE: {
2657                 const reference_expression_t *ref = &expression->reference;
2658                 return ref->declaration->type;
2659         }
2660         case EXPR_SELECT: {
2661                 const select_expression_t *select = &expression->select;
2662                 return select->compound_entry->type;
2663         }
2664         case EXPR_UNARY: {
2665                 const unary_expression_t *unary = &expression->unary;
2666                 if(unary->type == UNEXPR_DEREFERENCE) {
2667                         expression_t   *value        = unary->value;
2668                         type_t         *type         = skip_typeref(value->base.datatype);
2669                         pointer_type_t *pointer_type = &type->pointer;
2670
2671                         return pointer_type->points_to;
2672                 }
2673                 break;
2674         }
2675         case EXPR_BUILTIN_SYMBOL: {
2676                 const builtin_symbol_expression_t *builtin
2677                         = &expression->builtin_symbol;
2678                 return get_builtin_symbol_type(builtin->symbol);
2679         }
2680         case EXPR_ARRAY_ACCESS: {
2681                 const array_access_expression_t *array_access
2682                         = &expression->array_access;
2683                 const expression_t *array_ref = array_access->array_ref;
2684                 type_t *type_left  = skip_typeref(array_ref->base.datatype);
2685                 assert(is_type_pointer(type_left));
2686                 pointer_type_t *pointer_type = &type_left->pointer;
2687                 return pointer_type->points_to;
2688         }
2689
2690         default:
2691                 break;
2692         }
2693
2694         return expression->base.datatype;
2695 }
2696
2697 static expression_t *parse_reference(void)
2698 {
2699         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
2700
2701         reference_expression_t *ref = &expression->reference;
2702         ref->symbol = token.v.symbol;
2703
2704         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
2705
2706         source_position_t source_position = token.source_position;
2707         next_token();
2708
2709         if(declaration == NULL) {
2710 #ifndef STRICT_C99
2711                 /* an implicitly defined function */
2712                 if(token.type == '(') {
2713                         parser_print_prefix_pos(token.source_position);
2714                         fprintf(stderr, "warning: implicit declaration of function '%s'\n",
2715                                 ref->symbol->string);
2716
2717                         declaration = create_implicit_function(ref->symbol,
2718                                                                source_position);
2719                 } else
2720 #endif
2721                 {
2722                         parser_print_error_prefix();
2723                         fprintf(stderr, "unknown symbol '%s' found.\n", ref->symbol->string);
2724                         return expression;
2725                 }
2726         }
2727
2728         type_t *type = declaration->type;
2729         /* we always do the auto-type conversions; the & and sizeof parser contains
2730          * code to revert this! */
2731         type = automatic_type_conversion(type);
2732
2733         ref->declaration         = declaration;
2734         ref->expression.datatype = type;
2735
2736         return expression;
2737 }
2738
2739 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
2740 {
2741         (void) expression;
2742         (void) dest_type;
2743         /* TODO check if explicit cast is allowed and issue warnings/errors */
2744 }
2745
2746 static expression_t *parse_cast(void)
2747 {
2748         expression_t *cast = allocate_expression_zero(EXPR_UNARY);
2749
2750         cast->unary.type           = UNEXPR_CAST;
2751         cast->base.source_position = token.source_position;
2752
2753         type_t *type  = parse_typename();
2754
2755         expect(')');
2756         expression_t *value = parse_sub_expression(20);
2757
2758         check_cast_allowed(value, type);
2759
2760         cast->base.datatype = type;
2761         cast->unary.value   = value;
2762
2763         return cast;
2764 }
2765
2766 static expression_t *parse_statement_expression(void)
2767 {
2768         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
2769
2770         statement_t *statement          = parse_compound_statement();
2771         expression->statement.statement = statement;
2772         if(statement == NULL) {
2773                 expect(')');
2774                 return NULL;
2775         }
2776
2777         assert(statement->type == STATEMENT_COMPOUND);
2778         compound_statement_t *compound_statement = &statement->compound;
2779
2780         /* find last statement and use it's type */
2781         const statement_t *last_statement = NULL;
2782         const statement_t *iter           = compound_statement->statements;
2783         for( ; iter != NULL; iter = iter->base.next) {
2784                 last_statement = iter;
2785         }
2786
2787         if(last_statement->type == STATEMENT_EXPRESSION) {
2788                 const expression_statement_t *expression_statement
2789                         = &last_statement->expression;
2790                 expression->base.datatype
2791                         = expression_statement->expression->base.datatype;
2792         } else {
2793                 expression->base.datatype = type_void;
2794         }
2795
2796         expect(')');
2797
2798         return expression;
2799 }
2800
2801 static expression_t *parse_brace_expression(void)
2802 {
2803         eat('(');
2804
2805         switch(token.type) {
2806         case '{':
2807                 /* gcc extension: a stement expression */
2808                 return parse_statement_expression();
2809
2810         TYPE_QUALIFIERS
2811         TYPE_SPECIFIERS
2812                 return parse_cast();
2813         case T_IDENTIFIER:
2814                 if(is_typedef_symbol(token.v.symbol)) {
2815                         return parse_cast();
2816                 }
2817         }
2818
2819         expression_t *result = parse_expression();
2820         expect(')');
2821
2822         return result;
2823 }
2824
2825 static expression_t *parse_function_keyword(void)
2826 {
2827         next_token();
2828         /* TODO */
2829
2830         if (current_function == NULL) {
2831                 parse_error("'__func__' used outside of a function");
2832         }
2833
2834         string_literal_expression_t *expression
2835                 = allocate_ast_zero(sizeof(expression[0]));
2836
2837         expression->expression.type     = EXPR_FUNCTION;
2838         expression->expression.datatype = type_string;
2839         expression->value               = "TODO: FUNCTION";
2840
2841         return (expression_t*) expression;
2842 }
2843
2844 static expression_t *parse_pretty_function_keyword(void)
2845 {
2846         eat(T___PRETTY_FUNCTION__);
2847         /* TODO */
2848
2849         string_literal_expression_t *expression
2850                 = allocate_ast_zero(sizeof(expression[0]));
2851
2852         expression->expression.type     = EXPR_PRETTY_FUNCTION;
2853         expression->expression.datatype = type_string;
2854         expression->value               = "TODO: PRETTY FUNCTION";
2855
2856         return (expression_t*) expression;
2857 }
2858
2859 static designator_t *parse_designator(void)
2860 {
2861         designator_t *result = allocate_ast_zero(sizeof(result[0]));
2862
2863         if(token.type != T_IDENTIFIER) {
2864                 parse_error_expected("while parsing member designator",
2865                                      T_IDENTIFIER, 0);
2866                 eat_brace();
2867                 return NULL;
2868         }
2869         result->symbol = token.v.symbol;
2870         next_token();
2871
2872         designator_t *last_designator = result;
2873         while(true) {
2874                 if(token.type == '.') {
2875                         next_token();
2876                         if(token.type != T_IDENTIFIER) {
2877                                 parse_error_expected("while parsing member designator",
2878                                                      T_IDENTIFIER, 0);
2879                                 eat_brace();
2880                                 return NULL;
2881                         }
2882                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2883                         designator->symbol       = token.v.symbol;
2884                         next_token();
2885
2886                         last_designator->next = designator;
2887                         last_designator       = designator;
2888                         continue;
2889                 }
2890                 if(token.type == '[') {
2891                         next_token();
2892                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2893                         designator->array_access = parse_expression();
2894                         if(designator->array_access == NULL) {
2895                                 eat_brace();
2896                                 return NULL;
2897                         }
2898                         expect(']');
2899
2900                         last_designator->next = designator;
2901                         last_designator       = designator;
2902                         continue;
2903                 }
2904                 break;
2905         }
2906
2907         return result;
2908 }
2909
2910 static expression_t *parse_offsetof(void)
2911 {
2912         eat(T___builtin_offsetof);
2913
2914         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
2915         expression->base.datatype = type_size_t;
2916
2917         expect('(');
2918         expression->offsetofe.type = parse_typename();
2919         expect(',');
2920         expression->offsetofe.designator = parse_designator();
2921         expect(')');
2922
2923         return expression;
2924 }
2925
2926 static expression_t *parse_va_arg(void)
2927 {
2928         eat(T___builtin_va_arg);
2929
2930         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
2931
2932         expect('(');
2933         expression->va_arge.arg = parse_assignment_expression();
2934         expect(',');
2935         expression->base.datatype = parse_typename();
2936         expect(')');
2937
2938         return expression;
2939 }
2940
2941 static expression_t *parse_builtin_symbol(void)
2942 {
2943         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
2944
2945         symbol_t *symbol = token.v.symbol;
2946
2947         expression->builtin_symbol.symbol = symbol;
2948         next_token();
2949
2950         type_t *type = get_builtin_symbol_type(symbol);
2951         type = automatic_type_conversion(type);
2952
2953         expression->base.datatype = type;
2954         return expression;
2955 }
2956
2957 static expression_t *parse_primary_expression(void)
2958 {
2959         switch(token.type) {
2960         case T_INTEGER:
2961                 return parse_int_const();
2962         case T_FLOATINGPOINT:
2963                 return parse_float_const();
2964         case T_STRING_LITERAL:
2965                 return parse_string_const();
2966         case T_IDENTIFIER:
2967                 return parse_reference();
2968         case T___FUNCTION__:
2969         case T___func__:
2970                 return parse_function_keyword();
2971         case T___PRETTY_FUNCTION__:
2972                 return parse_pretty_function_keyword();
2973         case T___builtin_offsetof:
2974                 return parse_offsetof();
2975         case T___builtin_va_arg:
2976                 return parse_va_arg();
2977         case T___builtin_alloca:
2978         case T___builtin_expect:
2979         case T___builtin_va_start:
2980         case T___builtin_va_end:
2981                 return parse_builtin_symbol();
2982
2983         case '(':
2984                 return parse_brace_expression();
2985         }
2986
2987         parser_print_error_prefix();
2988         fprintf(stderr, "unexpected token ");
2989         print_token(stderr, &token);
2990         fprintf(stderr, "\n");
2991         eat_statement();
2992
2993         return make_invalid_expression();
2994 }
2995
2996 static expression_t *parse_array_expression(unsigned precedence,
2997                                             expression_t *left)
2998 {
2999         (void) precedence;
3000
3001         eat('[');
3002
3003         expression_t *inside = parse_expression();
3004
3005         array_access_expression_t *array_access
3006                 = allocate_ast_zero(sizeof(array_access[0]));
3007
3008         array_access->expression.type = EXPR_ARRAY_ACCESS;
3009
3010         type_t *type_left   = left->base.datatype;
3011         type_t *type_inside = inside->base.datatype;
3012         type_t *result_type = NULL;
3013
3014         if(type_left != NULL && type_inside != NULL) {
3015                 type_left   = skip_typeref(type_left);
3016                 type_inside = skip_typeref(type_inside);
3017
3018                 if(is_type_pointer(type_left)) {
3019                         pointer_type_t *pointer = &type_left->pointer;
3020                         result_type             = pointer->points_to;
3021                         array_access->array_ref = left;
3022                         array_access->index     = inside;
3023                 } else if(is_type_pointer(type_inside)) {
3024                         pointer_type_t *pointer = &type_inside->pointer;
3025                         result_type             = pointer->points_to;
3026                         array_access->array_ref = inside;
3027                         array_access->index     = left;
3028                         array_access->flipped   = true;
3029                 } else {
3030                         parser_print_error_prefix();
3031                         fprintf(stderr, "array access on object with non-pointer types ");
3032                         print_type_quoted(type_left);
3033                         fprintf(stderr, ", ");
3034                         print_type_quoted(type_inside);
3035                         fprintf(stderr, "\n");
3036                 }
3037         } else {
3038                 array_access->array_ref = left;
3039                 array_access->index     = inside;
3040         }
3041
3042         if(token.type != ']') {
3043                 parse_error_expected("Problem while parsing array access", ']', 0);
3044                 return (expression_t*) array_access;
3045         }
3046         next_token();
3047
3048         result_type = automatic_type_conversion(result_type);
3049         array_access->expression.datatype = result_type;
3050
3051         return (expression_t*) array_access;
3052 }
3053
3054 static bool is_declaration_specifier(const token_t *token,
3055                                      bool only_type_specifiers)
3056 {
3057         switch(token->type) {
3058                 TYPE_SPECIFIERS
3059                         return 1;
3060                 case T_IDENTIFIER:
3061                         return is_typedef_symbol(token->v.symbol);
3062                 STORAGE_CLASSES
3063                 TYPE_QUALIFIERS
3064                         if(only_type_specifiers)
3065                                 return 0;
3066                         return 1;
3067
3068                 default:
3069                         return 0;
3070         }
3071 }
3072
3073 static expression_t *parse_sizeof(unsigned precedence)
3074 {
3075         eat(T_sizeof);
3076
3077         sizeof_expression_t *sizeof_expression
3078                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3079         sizeof_expression->expression.type     = EXPR_SIZEOF;
3080         sizeof_expression->expression.datatype = type_size_t;
3081
3082         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3083                 next_token();
3084                 sizeof_expression->type = parse_typename();
3085                 expect(')');
3086         } else {
3087                 expression_t *expression  = parse_sub_expression(precedence);
3088                 expression->base.datatype = revert_automatic_type_conversion(expression);
3089
3090                 sizeof_expression->type            = expression->base.datatype;
3091                 sizeof_expression->size_expression = expression;
3092         }
3093
3094         return (expression_t*) sizeof_expression;
3095 }
3096
3097 static expression_t *parse_select_expression(unsigned precedence,
3098                                              expression_t *compound)
3099 {
3100         (void) precedence;
3101         assert(token.type == '.' || token.type == T_MINUSGREATER);
3102
3103         bool is_pointer = (token.type == T_MINUSGREATER);
3104         next_token();
3105
3106         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3107         select->select.compound = compound;
3108
3109         if(token.type != T_IDENTIFIER) {
3110                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3111                 return select;
3112         }
3113         symbol_t *symbol      = token.v.symbol;
3114         select->select.symbol = symbol;
3115         next_token();
3116
3117         type_t *orig_type = compound->base.datatype;
3118         if(orig_type == NULL)
3119                 return make_invalid_expression();
3120
3121         type_t *type = skip_typeref(orig_type);
3122
3123         type_t *type_left = type;
3124         if(is_pointer) {
3125                 if(type->type != TYPE_POINTER) {
3126                         parser_print_error_prefix();
3127                         fprintf(stderr, "left hand side of '->' is not a pointer, but ");
3128                         print_type_quoted(orig_type);
3129                         fputc('\n', stderr);
3130                         return make_invalid_expression();
3131                 }
3132                 pointer_type_t *pointer_type = &type->pointer;
3133                 type_left                    = pointer_type->points_to;
3134         }
3135         type_left = skip_typeref(type_left);
3136
3137         if(type_left->type != TYPE_COMPOUND_STRUCT
3138                         && type_left->type != TYPE_COMPOUND_UNION) {
3139                 parser_print_error_prefix();
3140                 fprintf(stderr, "request for member '%s' in something not a struct or "
3141                         "union, but ", symbol->string);
3142                 print_type_quoted(type_left);
3143                 fputc('\n', stderr);
3144                 return make_invalid_expression();
3145         }
3146
3147         compound_type_t *compound_type = &type_left->compound;
3148         declaration_t   *declaration   = compound_type->declaration;
3149
3150         if(!declaration->init.is_defined) {
3151                 parser_print_error_prefix();
3152                 fprintf(stderr, "request for member '%s' of incomplete type ",
3153                         symbol->string);
3154                 print_type_quoted(type_left);
3155                 fputc('\n', stderr);
3156                 return make_invalid_expression();
3157         }
3158
3159         declaration_t *iter = declaration->context.declarations;
3160         for( ; iter != NULL; iter = iter->next) {
3161                 if(iter->symbol == symbol) {
3162                         break;
3163                 }
3164         }
3165         if(iter == NULL) {
3166                 parser_print_error_prefix();
3167                 print_type_quoted(type_left);
3168                 fprintf(stderr, " has no member named '%s'\n", symbol->string);
3169                 return make_invalid_expression();
3170         }
3171
3172         /* we always do the auto-type conversions; the & and sizeof parser contains
3173          * code to revert this! */
3174         type_t *expression_type = automatic_type_conversion(iter->type);
3175
3176         select->select.compound_entry = iter;
3177         select->base.datatype         = expression_type;
3178         return select;
3179 }
3180
3181 static expression_t *parse_call_expression(unsigned precedence,
3182                                            expression_t *expression)
3183 {
3184         (void) precedence;
3185         expression_t *result = allocate_expression_zero(EXPR_CALL);
3186
3187         call_expression_t *call  = &result->call;
3188         call->function           = expression;
3189
3190         function_type_t *function_type = NULL;
3191         type_t          *orig_type     = expression->base.datatype;
3192         if(orig_type != NULL) {
3193                 type_t *type  = skip_typeref(orig_type);
3194
3195                 if(is_type_pointer(type)) {
3196                         pointer_type_t *pointer_type = &type->pointer;
3197
3198                         type = skip_typeref(pointer_type->points_to);
3199
3200                         if (type->type == TYPE_FUNCTION) {
3201                                 function_type             = &type->function;
3202                                 call->expression.datatype = function_type->result_type;
3203                         }
3204                 }
3205                 if(function_type == NULL) {
3206                         parser_print_error_prefix();
3207                         fputs("called object '", stderr);
3208                         print_expression(expression);
3209                         fputs("' (type ", stderr);
3210                         print_type_quoted(orig_type);
3211                         fputs(") is not a pointer to a function\n", stderr);
3212
3213                         function_type             = NULL;
3214                         call->expression.datatype = NULL;
3215                 }
3216         }
3217
3218         /* parse arguments */
3219         eat('(');
3220
3221         if(token.type != ')') {
3222                 call_argument_t *last_argument = NULL;
3223
3224                 while(true) {
3225                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3226
3227                         argument->expression = parse_assignment_expression();
3228                         if(last_argument == NULL) {
3229                                 call->arguments = argument;
3230                         } else {
3231                                 last_argument->next = argument;
3232                         }
3233                         last_argument = argument;
3234
3235                         if(token.type != ',')
3236                                 break;
3237                         next_token();
3238                 }
3239         }
3240         expect(')');
3241
3242         if(function_type != NULL) {
3243                 function_parameter_t *parameter = function_type->parameters;
3244                 call_argument_t      *argument  = call->arguments;
3245                 for( ; parameter != NULL && argument != NULL;
3246                                 parameter = parameter->next, argument = argument->next) {
3247                         type_t *expected_type = parameter->type;
3248                         /* TODO report context in error messages */
3249                         argument->expression = create_implicit_cast(argument->expression,
3250                                                                     expected_type);
3251                 }
3252                 /* too few parameters */
3253                 if(parameter != NULL) {
3254                         parser_print_error_prefix();
3255                         fprintf(stderr, "too few arguments to function '");
3256                         print_expression(expression);
3257                         fprintf(stderr, "'\n");
3258                 } else if(argument != NULL) {
3259                         /* too many parameters */
3260                         if(!function_type->variadic
3261                                         && !function_type->unspecified_parameters) {
3262                                 parser_print_error_prefix();
3263                                 fprintf(stderr, "too many arguments to function '");
3264                                 print_expression(expression);
3265                                 fprintf(stderr, "'\n");
3266                         } else {
3267                                 /* do default promotion */
3268                                 for( ; argument != NULL; argument = argument->next) {
3269                                         type_t *type = argument->expression->base.datatype;
3270                                         type = skip_typeref(type);
3271
3272                                         if(type == NULL)
3273                                                 continue;
3274
3275                                         if(is_type_integer(type)) {
3276                                                 type = promote_integer(type);
3277                                         } else if(type == type_float) {
3278                                                 type = type_double;
3279                                         }
3280
3281                                         argument->expression
3282                                                 = create_implicit_cast(argument->expression, type);
3283                                 }
3284                         }
3285                 }
3286         }
3287
3288         return result;
3289 }
3290
3291 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3292
3293 static expression_t *parse_conditional_expression(unsigned precedence,
3294                                                   expression_t *expression)
3295 {
3296         eat('?');
3297
3298         conditional_expression_t *conditional
3299                 = allocate_ast_zero(sizeof(conditional[0]));
3300         conditional->expression.type = EXPR_CONDITIONAL;
3301         conditional->condition       = expression;
3302
3303         /* 6.5.15.2 */
3304         type_t *condition_type_orig = conditional->condition->base.datatype;
3305         if(condition_type_orig != NULL) {
3306                 type_t *condition_type      = skip_typeref(condition_type_orig);
3307                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3308                         type_error("expected a scalar type",
3309                                    expression->base.source_position, condition_type_orig);
3310                 }
3311         }
3312
3313         expression_t *const t_expr = parse_expression();
3314         conditional->true_expression = t_expr;
3315         expect(':');
3316         expression_t *const f_expr = parse_sub_expression(precedence);
3317         conditional->false_expression = f_expr;
3318
3319         type_t *const true_type  = t_expr->base.datatype;
3320         if(true_type == NULL)
3321                 return (expression_t*) conditional;
3322         type_t *const false_type = f_expr->base.datatype;
3323         if(false_type == NULL)
3324                 return (expression_t*) conditional;
3325
3326         type_t *const skipped_true_type  = skip_typeref(true_type);
3327         type_t *const skipped_false_type = skip_typeref(false_type);
3328
3329         /* 6.5.15.3 */
3330         if (skipped_true_type == skipped_false_type) {
3331                 conditional->expression.datatype = skipped_true_type;
3332         } else if (is_type_arithmetic(skipped_true_type) &&
3333                    is_type_arithmetic(skipped_false_type)) {
3334                 type_t *const result = semantic_arithmetic(skipped_true_type,
3335                                                            skipped_false_type);
3336                 conditional->true_expression  = create_implicit_cast(t_expr, result);
3337                 conditional->false_expression = create_implicit_cast(f_expr, result);
3338                 conditional->expression.datatype = result;
3339         } else if (skipped_true_type->type == TYPE_POINTER &&
3340                    skipped_false_type->type == TYPE_POINTER &&
3341                           true /* TODO compatible points_to types */) {
3342                 /* TODO */
3343         } else if(/* (is_null_ptr_const(skipped_true_type) &&
3344                       skipped_false_type->type == TYPE_POINTER)
3345                || (is_null_ptr_const(skipped_false_type) &&
3346                    skipped_true_type->type == TYPE_POINTER) TODO*/ false) {
3347                 /* TODO */
3348         } else if(/* 1 is pointer to object type, other is void* */ false) {
3349                 /* TODO */
3350         } else {
3351                 type_error_incompatible("while parsing conditional",
3352                                         expression->base.source_position, true_type,
3353                                         skipped_false_type);
3354         }
3355
3356         return (expression_t*) conditional;
3357 }
3358
3359 static expression_t *parse_extension(unsigned precedence)
3360 {
3361         eat(T___extension__);
3362
3363         /* TODO enable extensions */
3364
3365         return parse_sub_expression(precedence);
3366 }
3367
3368 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3369 {
3370         eat(T___builtin_classify_type);
3371
3372         classify_type_expression_t *const classify_type_expr =
3373                 allocate_ast_zero(sizeof(classify_type_expr[0]));
3374         classify_type_expr->expression.type     = EXPR_CLASSIFY_TYPE;
3375         classify_type_expr->expression.datatype = type_int;
3376
3377         expect('(');
3378         expression_t *const expression = parse_sub_expression(precedence);
3379         expect(')');
3380         classify_type_expr->type_expression = expression;
3381
3382         return (expression_t*)classify_type_expr;
3383 }
3384
3385 static void semantic_incdec(unary_expression_t *expression)
3386 {
3387         type_t *orig_type = expression->value->base.datatype;
3388         if(orig_type == NULL)
3389                 return;
3390
3391         type_t *type = skip_typeref(orig_type);
3392         if(!is_type_arithmetic(type) && type->type != TYPE_POINTER) {
3393                 /* TODO: improve error message */
3394                 parser_print_error_prefix();
3395                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
3396                 return;
3397         }
3398
3399         expression->expression.datatype = orig_type;
3400 }
3401
3402 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3403 {
3404         type_t *orig_type = expression->value->base.datatype;
3405         if(orig_type == NULL)
3406                 return;
3407
3408         type_t *type = skip_typeref(orig_type);
3409         if(!is_type_arithmetic(type)) {
3410                 /* TODO: improve error message */
3411                 parser_print_error_prefix();
3412                 fprintf(stderr, "operation needs an arithmetic type\n");
3413                 return;
3414         }
3415
3416         expression->expression.datatype = orig_type;
3417 }
3418
3419 static void semantic_unexpr_scalar(unary_expression_t *expression)
3420 {
3421         type_t *orig_type = expression->value->base.datatype;
3422         if(orig_type == NULL)
3423                 return;
3424
3425         type_t *type = skip_typeref(orig_type);
3426         if (!is_type_scalar(type)) {
3427                 parse_error("operand of ! must be of scalar type\n");
3428                 return;
3429         }
3430
3431         expression->expression.datatype = orig_type;
3432 }
3433
3434 static void semantic_unexpr_integer(unary_expression_t *expression)
3435 {
3436         type_t *orig_type = expression->value->base.datatype;
3437         if(orig_type == NULL)
3438                 return;
3439
3440         type_t *type = skip_typeref(orig_type);
3441         if (!is_type_integer(type)) {
3442                 parse_error("operand of ~ must be of integer type\n");
3443                 return;
3444         }
3445
3446         expression->expression.datatype = orig_type;
3447 }
3448
3449 static void semantic_dereference(unary_expression_t *expression)
3450 {
3451         type_t *orig_type = expression->value->base.datatype;
3452         if(orig_type == NULL)
3453                 return;
3454
3455         type_t *type = skip_typeref(orig_type);
3456         if(!is_type_pointer(type)) {
3457                 parser_print_error_prefix();
3458                 fputs("Unary '*' needs pointer or arrray type, but type ", stderr);
3459                 print_type_quoted(orig_type);
3460                 fputs(" given.\n", stderr);
3461                 return;
3462         }
3463
3464         pointer_type_t *pointer_type = &type->pointer;
3465         type_t         *result_type  = pointer_type->points_to;
3466
3467         result_type = automatic_type_conversion(result_type);
3468         expression->expression.datatype = result_type;
3469 }
3470
3471 static void semantic_take_addr(unary_expression_t *expression)
3472 {
3473         expression_t *value  = expression->value;
3474         value->base.datatype = revert_automatic_type_conversion(value);
3475
3476         type_t *orig_type = value->base.datatype;
3477         if(orig_type == NULL)
3478                 return;
3479
3480         if(value->type == EXPR_REFERENCE) {
3481                 reference_expression_t *reference   = (reference_expression_t*) value;
3482                 declaration_t          *declaration = reference->declaration;
3483                 if(declaration != NULL) {
3484                         declaration->address_taken = 1;
3485                 }
3486         }
3487
3488         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3489 }
3490
3491 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3492 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3493 {                                                                              \
3494         eat(token_type);                                                           \
3495                                                                                \
3496         unary_expression_t *unary_expression                                       \
3497                 = allocate_ast_zero(sizeof(unary_expression[0]));                      \
3498         unary_expression->expression.type     = EXPR_UNARY;                        \
3499         unary_expression->type                = unexpression_type;                 \
3500         unary_expression->value               = parse_sub_expression(precedence);  \
3501                                                                                    \
3502         sfunc(unary_expression);                                                   \
3503                                                                                \
3504         return (expression_t*) unary_expression;                                   \
3505 }
3506
3507 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE, semantic_unexpr_arithmetic)
3508 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS,   semantic_unexpr_arithmetic)
3509 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT,    semantic_unexpr_scalar)
3510 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE, semantic_dereference)
3511 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS, semantic_take_addr)
3512 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE,
3513                                semantic_unexpr_integer)
3514 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT,
3515                                semantic_incdec)
3516 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT,
3517                                semantic_incdec)
3518
3519 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
3520                                                sfunc)                         \
3521 static expression_t *parse_##unexpression_type(unsigned precedence,           \
3522                                                expression_t *left)            \
3523 {                                                                             \
3524         (void) precedence;                                                        \
3525         eat(token_type);                                                          \
3526                                                                               \
3527         unary_expression_t *unary_expression                                      \
3528                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
3529         unary_expression->expression.type     = EXPR_UNARY;                       \
3530         unary_expression->type                = unexpression_type;                \
3531         unary_expression->value               = left;                             \
3532                                                                                   \
3533         sfunc(unary_expression);                                                  \
3534                                                                               \
3535         return (expression_t*) unary_expression;                                  \
3536 }
3537
3538 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT,
3539                                        semantic_incdec)
3540 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT,
3541                                        semantic_incdec)
3542
3543 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
3544 {
3545         /* TODO: handle complex + imaginary types */
3546
3547         /* Â§ 6.3.1.8 Usual arithmetic conversions */
3548         if(type_left == type_long_double || type_right == type_long_double) {
3549                 return type_long_double;
3550         } else if(type_left == type_double || type_right == type_double) {
3551                 return type_double;
3552         } else if(type_left == type_float || type_right == type_float) {
3553                 return type_float;
3554         }
3555
3556         type_right = promote_integer(type_right);
3557         type_left  = promote_integer(type_left);
3558
3559         if(type_left == type_right)
3560                 return type_left;
3561
3562         bool signed_left  = is_type_signed(type_left);
3563         bool signed_right = is_type_signed(type_right);
3564         int  rank_left    = get_rank(type_left);
3565         int  rank_right   = get_rank(type_right);
3566         if(rank_left < rank_right) {
3567                 if(signed_left == signed_right || !signed_right) {
3568                         return type_right;
3569                 } else {
3570                         return type_left;
3571                 }
3572         } else {
3573                 if(signed_left == signed_right || !signed_left) {
3574                         return type_left;
3575                 } else {
3576                         return type_right;
3577                 }
3578         }
3579 }
3580
3581 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
3582 {
3583         expression_t *left       = expression->left;
3584         expression_t *right      = expression->right;
3585         type_t       *orig_type_left  = left->base.datatype;
3586         type_t       *orig_type_right = right->base.datatype;
3587
3588         if(orig_type_left == NULL || orig_type_right == NULL)
3589                 return;
3590
3591         type_t *type_left  = skip_typeref(orig_type_left);
3592         type_t *type_right = skip_typeref(orig_type_right);
3593
3594         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3595                 /* TODO: improve error message */
3596                 parser_print_error_prefix();
3597                 fprintf(stderr, "operation needs arithmetic types\n");
3598                 return;
3599         }
3600
3601         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3602         expression->left  = create_implicit_cast(left, arithmetic_type);
3603         expression->right = create_implicit_cast(right, arithmetic_type);
3604         expression->expression.datatype = arithmetic_type;
3605 }
3606
3607 static void semantic_shift_op(binary_expression_t *expression)
3608 {
3609         expression_t *left       = expression->left;
3610         expression_t *right      = expression->right;
3611         type_t       *orig_type_left  = left->base.datatype;
3612         type_t       *orig_type_right = right->base.datatype;
3613
3614         if(orig_type_left == NULL || orig_type_right == NULL)
3615                 return;
3616
3617         type_t *type_left  = skip_typeref(orig_type_left);
3618         type_t *type_right = skip_typeref(orig_type_right);
3619
3620         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
3621                 /* TODO: improve error message */
3622                 parser_print_error_prefix();
3623                 fprintf(stderr, "operation needs integer types\n");
3624                 return;
3625         }
3626
3627         type_left  = promote_integer(type_left);
3628         type_right = promote_integer(type_right);
3629
3630         expression->left  = create_implicit_cast(left, type_left);
3631         expression->right = create_implicit_cast(right, type_right);
3632         expression->expression.datatype = type_left;
3633 }
3634
3635 static void semantic_add(binary_expression_t *expression)
3636 {
3637         expression_t *left            = expression->left;
3638         expression_t *right           = expression->right;
3639         type_t       *orig_type_left  = left->base.datatype;
3640         type_t       *orig_type_right = right->base.datatype;
3641
3642         if(orig_type_left == NULL || orig_type_right == NULL)
3643                 return;
3644
3645         type_t *type_left  = skip_typeref(orig_type_left);
3646         type_t *type_right = skip_typeref(orig_type_right);
3647
3648         /* Â§ 5.6.5 */
3649         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3650                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3651                 expression->left  = create_implicit_cast(left, arithmetic_type);
3652                 expression->right = create_implicit_cast(right, arithmetic_type);
3653                 expression->expression.datatype = arithmetic_type;
3654                 return;
3655         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
3656                 expression->expression.datatype = type_left;
3657         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
3658                 expression->expression.datatype = type_right;
3659         } else {
3660                 parser_print_error_prefix();
3661                 fprintf(stderr, "invalid operands to binary + (");
3662                 print_type_quoted(orig_type_left);
3663                 fprintf(stderr, ", ");
3664                 print_type_quoted(orig_type_right);
3665                 fprintf(stderr, ")\n");
3666         }
3667 }
3668
3669 static void semantic_sub(binary_expression_t *expression)
3670 {
3671         expression_t *left            = expression->left;
3672         expression_t *right           = expression->right;
3673         type_t       *orig_type_left  = left->base.datatype;
3674         type_t       *orig_type_right = right->base.datatype;
3675
3676         if(orig_type_left == NULL || orig_type_right == NULL)
3677                 return;
3678
3679         type_t       *type_left       = skip_typeref(orig_type_left);
3680         type_t       *type_right      = skip_typeref(orig_type_right);
3681
3682         /* Â§ 5.6.5 */
3683         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3684                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3685                 expression->left  = create_implicit_cast(left, arithmetic_type);
3686                 expression->right = create_implicit_cast(right, arithmetic_type);
3687                 expression->expression.datatype = arithmetic_type;
3688                 return;
3689         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3690                 expression->expression.datatype = type_left;
3691         } else if(type_left->type == TYPE_POINTER &&
3692                         type_right->type == TYPE_POINTER) {
3693                 if(!pointers_compatible(type_left, type_right)) {
3694                         parser_print_error_prefix();
3695                         fprintf(stderr, "pointers to incompatible objects to binary - (");
3696                         print_type_quoted(orig_type_left);
3697                         fprintf(stderr, ", ");
3698                         print_type_quoted(orig_type_right);
3699                         fprintf(stderr, ")\n");
3700                 } else {
3701                         expression->expression.datatype = type_ptrdiff_t;
3702                 }
3703         } else {
3704                 parser_print_error_prefix();
3705                 fprintf(stderr, "invalid operands to binary - (");
3706                 print_type_quoted(orig_type_left);
3707                 fprintf(stderr, ", ");
3708                 print_type_quoted(orig_type_right);
3709                 fprintf(stderr, ")\n");
3710         }
3711 }
3712
3713 static void semantic_comparison(binary_expression_t *expression)
3714 {
3715         expression_t *left            = expression->left;
3716         expression_t *right           = expression->right;
3717         type_t       *orig_type_left  = left->base.datatype;
3718         type_t       *orig_type_right = right->base.datatype;
3719
3720         if(orig_type_left == NULL || orig_type_right == NULL)
3721                 return;
3722
3723         type_t *type_left  = skip_typeref(orig_type_left);
3724         type_t *type_right = skip_typeref(orig_type_right);
3725
3726         /* TODO non-arithmetic types */
3727         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3728                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3729                 expression->left  = create_implicit_cast(left, arithmetic_type);
3730                 expression->right = create_implicit_cast(right, arithmetic_type);
3731                 expression->expression.datatype = arithmetic_type;
3732         } else if (type_left->type  == TYPE_POINTER &&
3733                    type_right->type == TYPE_POINTER) {
3734                 /* TODO check compatibility */
3735         } else if (type_left->type == TYPE_POINTER) {
3736                 expression->right = create_implicit_cast(right, type_left);
3737         } else if (type_right->type == TYPE_POINTER) {
3738                 expression->left = create_implicit_cast(left, type_right);
3739         } else {
3740                 type_error_incompatible("invalid operands in comparison",
3741                                         token.source_position, type_left, type_right);
3742         }
3743         expression->expression.datatype = type_int;
3744 }
3745
3746 static void semantic_arithmetic_assign(binary_expression_t *expression)
3747 {
3748         expression_t *left            = expression->left;
3749         expression_t *right           = expression->right;
3750         type_t       *orig_type_left  = left->base.datatype;
3751         type_t       *orig_type_right = right->base.datatype;
3752
3753         if(orig_type_left == NULL || orig_type_right == NULL)
3754                 return;
3755
3756         type_t *type_left  = skip_typeref(orig_type_left);
3757         type_t *type_right = skip_typeref(orig_type_right);
3758
3759         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3760                 /* TODO: improve error message */
3761                 parser_print_error_prefix();
3762                 fprintf(stderr, "operation needs arithmetic types\n");
3763                 return;
3764         }
3765
3766         /* combined instructions are tricky. We can't create an implicit cast on
3767          * the left side, because we need the uncasted form for the store.
3768          * The ast2firm pass has to know that left_type must be right_type
3769          * for the arithmeitc operation and create a cast by itself */
3770         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3771         expression->right       = create_implicit_cast(right, arithmetic_type);
3772         expression->expression.datatype = type_left;
3773 }
3774
3775 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
3776 {
3777         expression_t *left            = expression->left;
3778         expression_t *right           = expression->right;
3779         type_t       *orig_type_left  = left->base.datatype;
3780         type_t       *orig_type_right = right->base.datatype;
3781
3782         if(orig_type_left == NULL || orig_type_right == NULL)
3783                 return;
3784
3785         type_t *type_left  = skip_typeref(orig_type_left);
3786         type_t *type_right = skip_typeref(orig_type_right);
3787
3788         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3789                 /* combined instructions are tricky. We can't create an implicit cast on
3790                  * the left side, because we need the uncasted form for the store.
3791                  * The ast2firm pass has to know that left_type must be right_type
3792                  * for the arithmeitc operation and create a cast by itself */
3793                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
3794                 expression->right = create_implicit_cast(right, arithmetic_type);
3795                 expression->expression.datatype = type_left;
3796         } else if (type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3797                 expression->expression.datatype = type_left;
3798         } else {
3799                 parser_print_error_prefix();
3800                 fputs("Incompatible types ", stderr);
3801                 print_type_quoted(orig_type_left);
3802                 fputs(" and ", stderr);
3803                 print_type_quoted(orig_type_right);
3804                 fputs(" in assignment\n", stderr);
3805                 return;
3806         }
3807 }
3808
3809 static void semantic_logical_op(binary_expression_t *expression)
3810 {
3811         expression_t *left            = expression->left;
3812         expression_t *right           = expression->right;
3813         type_t       *orig_type_left  = left->base.datatype;
3814         type_t       *orig_type_right = right->base.datatype;
3815
3816         if(orig_type_left == NULL || orig_type_right == NULL)
3817                 return;
3818
3819         type_t *type_left  = skip_typeref(orig_type_left);
3820         type_t *type_right = skip_typeref(orig_type_right);
3821
3822         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
3823                 /* TODO: improve error message */
3824                 parser_print_error_prefix();
3825                 fprintf(stderr, "operation needs scalar types\n");
3826                 return;
3827         }
3828
3829         expression->expression.datatype = type_int;
3830 }
3831
3832 static bool has_const_fields(type_t *type)
3833 {
3834         (void) type;
3835         /* TODO */
3836         return false;
3837 }
3838
3839 static void semantic_binexpr_assign(binary_expression_t *expression)
3840 {
3841         expression_t *left           = expression->left;
3842         type_t       *orig_type_left = left->base.datatype;
3843
3844         if(orig_type_left == NULL)
3845                 return;
3846
3847         type_t *type_left = revert_automatic_type_conversion(left);
3848         type_left = skip_typeref(orig_type_left);
3849
3850         /* must be a modifiable lvalue */
3851         if (type_left->type == TYPE_ARRAY) {
3852                 parser_print_error_prefix();
3853                 fprintf(stderr, "Cannot assign to arrays ('");
3854                 print_expression(left);
3855                 fprintf(stderr, "')\n");
3856                 return;
3857         }
3858         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
3859                 parser_print_error_prefix();
3860                 fprintf(stderr, "assignment to readonly location '");
3861                 print_expression(left);
3862                 fprintf(stderr, "' (type ");
3863                 print_type_quoted(orig_type_left);
3864                 fprintf(stderr, ")\n");
3865                 return;
3866         }
3867         if(is_type_incomplete(type_left)) {
3868                 parser_print_error_prefix();
3869                 fprintf(stderr, "left-hand side of assignment '");
3870                 print_expression(left);
3871                 fprintf(stderr, "' has incomplete type ");
3872                 print_type_quoted(orig_type_left);
3873                 fprintf(stderr, "\n");
3874                 return;
3875         }
3876         if(is_type_compound(type_left) && has_const_fields(type_left)) {
3877                 parser_print_error_prefix();
3878                 fprintf(stderr, "can't assign to '");
3879                 print_expression(left);
3880                 fprintf(stderr, "' because compound type ");
3881                 print_type_quoted(orig_type_left);
3882                 fprintf(stderr, " has readonly fields\n");
3883                 return;
3884         }
3885
3886         semantic_assign(orig_type_left, &expression->right, "assignment");
3887
3888         expression->expression.datatype = orig_type_left;
3889 }
3890
3891 static void semantic_comma(binary_expression_t *expression)
3892 {
3893         expression->expression.datatype = expression->right->base.datatype;
3894 }
3895
3896 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
3897 static expression_t *parse_##binexpression_type(unsigned precedence,     \
3898                                                 expression_t *left)      \
3899 {                                                                        \
3900         eat(token_type);                                                     \
3901                                                                          \
3902         expression_t *right = parse_sub_expression(precedence + lr);         \
3903                                                                          \
3904         binary_expression_t *binexpr                                         \
3905                 = allocate_ast_zero(sizeof(binexpr[0]));                         \
3906         binexpr->expression.type     = EXPR_BINARY;                          \
3907         binexpr->type                = binexpression_type;                   \
3908         binexpr->left                = left;                                 \
3909         binexpr->right               = right;                                \
3910         sfunc(binexpr);                                                      \
3911                                                                          \
3912         return (expression_t*) binexpr;                                      \
3913 }
3914
3915 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA,          semantic_comma, 1)
3916 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL,            semantic_binexpr_arithmetic, 1)
3917 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV,            semantic_binexpr_arithmetic, 1)
3918 CREATE_BINEXPR_PARSER('%', BINEXPR_MOD,            semantic_binexpr_arithmetic, 1)
3919 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD,            semantic_add, 1)
3920 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB,            semantic_sub, 1)
3921 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS,           semantic_comparison, 1)
3922 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER,        semantic_comparison, 1)
3923 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN,         semantic_binexpr_assign, 0)
3924 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL, semantic_comparison, 1)
3925 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL,
3926                       semantic_comparison, 1)
3927 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL, semantic_comparison, 1)
3928 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL,
3929                       semantic_comparison, 1)
3930 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND,    semantic_binexpr_arithmetic, 1)
3931 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR,     semantic_binexpr_arithmetic, 1)
3932 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR,    semantic_binexpr_arithmetic, 1)
3933 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND,  semantic_logical_op, 1)
3934 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR, semantic_logical_op, 1)
3935 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT,
3936                       semantic_shift_op, 1)
3937 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT,
3938                       semantic_shift_op, 1)
3939 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN,
3940                       semantic_arithmetic_addsubb_assign, 0)
3941 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN,
3942                       semantic_arithmetic_addsubb_assign, 0)
3943 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN,
3944                       semantic_arithmetic_assign, 0)
3945 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN,
3946                       semantic_arithmetic_assign, 0)
3947 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN,
3948                       semantic_arithmetic_assign, 0)
3949 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN,
3950                       semantic_arithmetic_assign, 0)
3951 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN,
3952                       semantic_arithmetic_assign, 0)
3953 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN,
3954                       semantic_arithmetic_assign, 0)
3955 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN,
3956                       semantic_arithmetic_assign, 0)
3957 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN,
3958                       semantic_arithmetic_assign, 0)
3959
3960 static expression_t *parse_sub_expression(unsigned precedence)
3961 {
3962         if(token.type < 0) {
3963                 return expected_expression_error();
3964         }
3965
3966         expression_parser_function_t *parser
3967                 = &expression_parsers[token.type];
3968         source_position_t             source_position = token.source_position;
3969         expression_t                 *left;
3970
3971         if(parser->parser != NULL) {
3972                 left = parser->parser(parser->precedence);
3973         } else {
3974                 left = parse_primary_expression();
3975         }
3976         assert(left != NULL);
3977         left->base.source_position = source_position;
3978
3979         while(true) {
3980                 if(token.type < 0) {
3981                         return expected_expression_error();
3982                 }
3983
3984                 parser = &expression_parsers[token.type];
3985                 if(parser->infix_parser == NULL)
3986                         break;
3987                 if(parser->infix_precedence < precedence)
3988                         break;
3989
3990                 left = parser->infix_parser(parser->infix_precedence, left);
3991
3992                 assert(left != NULL);
3993                 assert(left->type != EXPR_UNKNOWN);
3994                 left->base.source_position = source_position;
3995         }
3996
3997         return left;
3998 }
3999
4000 static expression_t *parse_expression(void)
4001 {
4002         return parse_sub_expression(1);
4003 }
4004
4005
4006
4007 static void register_expression_parser(parse_expression_function parser,
4008                                        int token_type, unsigned precedence)
4009 {
4010         expression_parser_function_t *entry = &expression_parsers[token_type];
4011
4012         if(entry->parser != NULL) {
4013                 fprintf(stderr, "for token ");
4014                 print_token_type(stderr, (token_type_t) token_type);
4015                 fprintf(stderr, "\n");
4016                 panic("trying to register multiple expression parsers for a token");
4017         }
4018         entry->parser     = parser;
4019         entry->precedence = precedence;
4020 }
4021
4022 static void register_expression_infix_parser(
4023                 parse_expression_infix_function parser, int token_type,
4024                 unsigned precedence)
4025 {
4026         expression_parser_function_t *entry = &expression_parsers[token_type];
4027
4028         if(entry->infix_parser != NULL) {
4029                 fprintf(stderr, "for token ");
4030                 print_token_type(stderr, (token_type_t) token_type);
4031                 fprintf(stderr, "\n");
4032                 panic("trying to register multiple infix expression parsers for a "
4033                       "token");
4034         }
4035         entry->infix_parser     = parser;
4036         entry->infix_precedence = precedence;
4037 }
4038
4039 static void init_expression_parsers(void)
4040 {
4041         memset(&expression_parsers, 0, sizeof(expression_parsers));
4042
4043         register_expression_infix_parser(parse_BINEXPR_MUL,         '*',        16);
4044         register_expression_infix_parser(parse_BINEXPR_DIV,         '/',        16);
4045         register_expression_infix_parser(parse_BINEXPR_MOD,         '%',        16);
4046         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,   T_LESSLESS, 16);
4047         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
4048                                                               T_GREATERGREATER, 16);
4049         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
4050         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
4051         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
4052         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
4053         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
4054         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
4055                                                                 T_GREATEREQUAL, 14);
4056         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
4057         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
4058                                                         T_EXCLAMATIONMARKEQUAL, 13);
4059         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
4060         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
4061         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
4062         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
4063         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
4064         register_expression_infix_parser(parse_conditional_expression, '?',      7);
4065         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
4066         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
4067         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
4068         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
4069                                                                 T_ASTERISKEQUAL, 2);
4070         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
4071         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
4072                                                                  T_PERCENTEQUAL, 2);
4073         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
4074                                                                 T_LESSLESSEQUAL, 2);
4075         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
4076                                                           T_GREATERGREATEREQUAL, 2);
4077         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
4078                                                                      T_ANDEQUAL, 2);
4079         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
4080                                                                     T_PIPEEQUAL, 2);
4081         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
4082                                                                    T_CARETEQUAL, 2);
4083
4084         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
4085
4086         register_expression_infix_parser(parse_array_expression,        '[',    30);
4087         register_expression_infix_parser(parse_call_expression,         '(',    30);
4088         register_expression_infix_parser(parse_select_expression,       '.',    30);
4089         register_expression_infix_parser(parse_select_expression,
4090                                                                 T_MINUSGREATER, 30);
4091         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
4092                                          T_PLUSPLUS, 30);
4093         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
4094                                          T_MINUSMINUS, 30);
4095
4096         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
4097         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
4098         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
4099         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
4100         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
4101         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
4102         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
4103         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
4104         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4105         register_expression_parser(parse_extension,            T___extension__, 25);
4106         register_expression_parser(parse_builtin_classify_type,
4107                                                      T___builtin_classify_type, 25);
4108 }
4109
4110
4111 static statement_t *parse_case_statement(void)
4112 {
4113         eat(T_case);
4114         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
4115         label->statement.type            = STATEMENT_CASE_LABEL;
4116         label->statement.source_position = token.source_position;
4117
4118         label->expression = parse_expression();
4119
4120         expect(':');
4121         label->label_statement = parse_statement();
4122
4123         return (statement_t*) label;
4124 }
4125
4126 static statement_t *parse_default_statement(void)
4127 {
4128         eat(T_default);
4129
4130         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
4131         label->statement.type            = STATEMENT_CASE_LABEL;
4132         label->statement.source_position = token.source_position;
4133
4134         expect(':');
4135         label->label_statement = parse_statement();
4136
4137         return (statement_t*) label;
4138 }
4139
4140 static declaration_t *get_label(symbol_t *symbol)
4141 {
4142         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4143         assert(current_function != NULL);
4144         /* if we found a label in the same function, then we already created the
4145          * declaration */
4146         if(candidate != NULL
4147                         && candidate->parent_context == &current_function->context) {
4148                 return candidate;
4149         }
4150
4151         /* otherwise we need to create a new one */
4152         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4153         declaration->namespc     = NAMESPACE_LABEL;
4154         declaration->symbol        = symbol;
4155
4156         label_push(declaration);
4157
4158         return declaration;
4159 }
4160
4161 static statement_t *parse_label_statement(void)
4162 {
4163         assert(token.type == T_IDENTIFIER);
4164         symbol_t *symbol = token.v.symbol;
4165         next_token();
4166
4167         declaration_t *label = get_label(symbol);
4168
4169         /* if source position is already set then the label is defined twice,
4170          * otherwise it was just mentioned in a goto so far */
4171         if(label->source_position.input_name != NULL) {
4172                 parser_print_error_prefix();
4173                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
4174                 parser_print_error_prefix_pos(label->source_position);
4175                 fprintf(stderr, "previous definition of '%s' was here\n",
4176                         symbol->string);
4177         } else {
4178                 label->source_position = token.source_position;
4179         }
4180
4181         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4182
4183         label_statement->statement.type            = STATEMENT_LABEL;
4184         label_statement->statement.source_position = token.source_position;
4185         label_statement->label                     = label;
4186
4187         expect(':');
4188
4189         if(token.type == '}') {
4190                 parse_error("label at end of compound statement");
4191                 return (statement_t*) label_statement;
4192         } else {
4193                 label_statement->label_statement = parse_statement();
4194         }
4195
4196         return (statement_t*) label_statement;
4197 }
4198
4199 static statement_t *parse_if(void)
4200 {
4201         eat(T_if);
4202
4203         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4204         statement->statement.type            = STATEMENT_IF;
4205         statement->statement.source_position = token.source_position;
4206
4207         expect('(');
4208         statement->condition = parse_expression();
4209         expect(')');
4210
4211         statement->true_statement = parse_statement();
4212         if(token.type == T_else) {
4213                 next_token();
4214                 statement->false_statement = parse_statement();
4215         }
4216
4217         return (statement_t*) statement;
4218 }
4219
4220 static statement_t *parse_switch(void)
4221 {
4222         eat(T_switch);
4223
4224         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4225         statement->statement.type            = STATEMENT_SWITCH;
4226         statement->statement.source_position = token.source_position;
4227
4228         expect('(');
4229         statement->expression = parse_expression();
4230         expect(')');
4231         statement->body = parse_statement();
4232
4233         return (statement_t*) statement;
4234 }
4235
4236 static statement_t *parse_while(void)
4237 {
4238         eat(T_while);
4239
4240         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4241         statement->statement.type            = STATEMENT_WHILE;
4242         statement->statement.source_position = token.source_position;
4243
4244         expect('(');
4245         statement->condition = parse_expression();
4246         expect(')');
4247         statement->body = parse_statement();
4248
4249         return (statement_t*) statement;
4250 }
4251
4252 static statement_t *parse_do(void)
4253 {
4254         eat(T_do);
4255
4256         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4257         statement->statement.type            = STATEMENT_DO_WHILE;
4258         statement->statement.source_position = token.source_position;
4259
4260         statement->body = parse_statement();
4261         expect(T_while);
4262         expect('(');
4263         statement->condition = parse_expression();
4264         expect(')');
4265         expect(';');
4266
4267         return (statement_t*) statement;
4268 }
4269
4270 static statement_t *parse_for(void)
4271 {
4272         eat(T_for);
4273
4274         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4275         statement->statement.type            = STATEMENT_FOR;
4276         statement->statement.source_position = token.source_position;
4277
4278         expect('(');
4279
4280         int         top          = environment_top();
4281         context_t  *last_context = context;
4282         set_context(&statement->context);
4283
4284         if(token.type != ';') {
4285                 if(is_declaration_specifier(&token, false)) {
4286                         parse_declaration();
4287                 } else {
4288                         statement->initialisation = parse_expression();
4289                         expect(';');
4290                 }
4291         } else {
4292                 expect(';');
4293         }
4294
4295         if(token.type != ';') {
4296                 statement->condition = parse_expression();
4297         }
4298         expect(';');
4299         if(token.type != ')') {
4300                 statement->step = parse_expression();
4301         }
4302         expect(')');
4303         statement->body = parse_statement();
4304
4305         assert(context == &statement->context);
4306         set_context(last_context);
4307         environment_pop_to(top);
4308
4309         return (statement_t*) statement;
4310 }
4311
4312 static statement_t *parse_goto(void)
4313 {
4314         eat(T_goto);
4315
4316         if(token.type != T_IDENTIFIER) {
4317                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4318                 eat_statement();
4319                 return NULL;
4320         }
4321         symbol_t *symbol = token.v.symbol;
4322         next_token();
4323
4324         declaration_t *label = get_label(symbol);
4325
4326         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4327
4328         statement->statement.type            = STATEMENT_GOTO;
4329         statement->statement.source_position = token.source_position;
4330
4331         statement->label = label;
4332
4333         expect(';');
4334
4335         return (statement_t*) statement;
4336 }
4337
4338 static statement_t *parse_continue(void)
4339 {
4340         eat(T_continue);
4341         expect(';');
4342
4343         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4344         statement->type                 = STATEMENT_CONTINUE;
4345         statement->base.source_position = token.source_position;
4346
4347         return statement;
4348 }
4349
4350 static statement_t *parse_break(void)
4351 {
4352         eat(T_break);
4353         expect(';');
4354
4355         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4356         statement->type                 = STATEMENT_BREAK;
4357         statement->base.source_position = token.source_position;
4358
4359         return statement;
4360 }
4361
4362 static statement_t *parse_return(void)
4363 {
4364         eat(T_return);
4365
4366         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4367
4368         statement->statement.type            = STATEMENT_RETURN;
4369         statement->statement.source_position = token.source_position;
4370
4371         assert(current_function->type->type == TYPE_FUNCTION);
4372         function_type_t *function_type = &current_function->type->function;
4373         type_t          *return_type   = function_type->result_type;
4374
4375         expression_t *return_value = NULL;
4376         if(token.type != ';') {
4377                 return_value = parse_expression();
4378         }
4379         expect(';');
4380
4381         if(return_type == NULL)
4382                 return (statement_t*) statement;
4383
4384         return_type = skip_typeref(return_type);
4385
4386         if(return_value != NULL) {
4387                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
4388
4389                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
4390                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
4391                         parse_warning("'return' with a value, in function returning void");
4392                         return_value = NULL;
4393                 } else {
4394                         if(return_type != NULL) {
4395                                 semantic_assign(return_type, &return_value, "'return'");
4396                         }
4397                 }
4398         } else {
4399                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
4400                         parse_warning("'return' without value, in function returning "
4401                                       "non-void");
4402                 }
4403         }
4404         statement->return_value = return_value;
4405
4406         return (statement_t*) statement;
4407 }
4408
4409 static statement_t *parse_declaration_statement(void)
4410 {
4411         declaration_t *before = last_declaration;
4412
4413         declaration_statement_t *statement
4414                 = allocate_ast_zero(sizeof(statement[0]));
4415         statement->statement.type            = STATEMENT_DECLARATION;
4416         statement->statement.source_position = token.source_position;
4417
4418         declaration_specifiers_t specifiers;
4419         memset(&specifiers, 0, sizeof(specifiers));
4420         parse_declaration_specifiers(&specifiers);
4421
4422         if(token.type == ';') {
4423                 eat(';');
4424         } else {
4425                 parse_init_declarators(&specifiers);
4426         }
4427
4428         if(before == NULL) {
4429                 statement->declarations_begin = context->declarations;
4430         } else {
4431                 statement->declarations_begin = before->next;
4432         }
4433         statement->declarations_end = last_declaration;
4434
4435         return (statement_t*) statement;
4436 }
4437
4438 static statement_t *parse_expression_statement(void)
4439 {
4440         expression_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4441         statement->statement.type            = STATEMENT_EXPRESSION;
4442         statement->statement.source_position = token.source_position;
4443
4444         statement->expression = parse_expression();
4445
4446         expect(';');
4447
4448         return (statement_t*) statement;
4449 }
4450
4451 static statement_t *parse_statement(void)
4452 {
4453         statement_t   *statement = NULL;
4454
4455         /* declaration or statement */
4456         switch(token.type) {
4457         case T_case:
4458                 statement = parse_case_statement();
4459                 break;
4460
4461         case T_default:
4462                 statement = parse_default_statement();
4463                 break;
4464
4465         case '{':
4466                 statement = parse_compound_statement();
4467                 break;
4468
4469         case T_if:
4470                 statement = parse_if();
4471                 break;
4472
4473         case T_switch:
4474                 statement = parse_switch();
4475                 break;
4476
4477         case T_while:
4478                 statement = parse_while();
4479                 break;
4480
4481         case T_do:
4482                 statement = parse_do();
4483                 break;
4484
4485         case T_for:
4486                 statement = parse_for();
4487                 break;
4488
4489         case T_goto:
4490                 statement = parse_goto();
4491                 break;
4492
4493         case T_continue:
4494                 statement = parse_continue();
4495                 break;
4496
4497         case T_break:
4498                 statement = parse_break();
4499                 break;
4500
4501         case T_return:
4502                 statement = parse_return();
4503                 break;
4504
4505         case ';':
4506                 next_token();
4507                 statement = NULL;
4508                 break;
4509
4510         case T_IDENTIFIER:
4511                 if(look_ahead(1)->type == ':') {
4512                         statement = parse_label_statement();
4513                         break;
4514                 }
4515
4516                 if(is_typedef_symbol(token.v.symbol)) {
4517                         statement = parse_declaration_statement();
4518                         break;
4519                 }
4520
4521                 statement = parse_expression_statement();
4522                 break;
4523
4524         case T___extension__:
4525                 /* this can be a prefix to a declaration or an expression statement */
4526                 /* we simply eat it now and parse the rest with tail recursion */
4527                 do {
4528                         next_token();
4529                 } while(token.type == T___extension__);
4530                 statement = parse_statement();
4531                 break;
4532
4533         DECLARATION_START
4534                 statement = parse_declaration_statement();
4535                 break;
4536
4537         default:
4538                 statement = parse_expression_statement();
4539                 break;
4540         }
4541
4542         assert(statement == NULL
4543                         || statement->base.source_position.input_name != NULL);
4544
4545         return statement;
4546 }
4547
4548 static statement_t *parse_compound_statement(void)
4549 {
4550         compound_statement_t *compound_statement
4551                 = allocate_ast_zero(sizeof(compound_statement[0]));
4552         compound_statement->statement.type            = STATEMENT_COMPOUND;
4553         compound_statement->statement.source_position = token.source_position;
4554
4555         eat('{');
4556
4557         int        top          = environment_top();
4558         context_t *last_context = context;
4559         set_context(&compound_statement->context);
4560
4561         statement_t *last_statement = NULL;
4562
4563         while(token.type != '}' && token.type != T_EOF) {
4564                 statement_t *statement = parse_statement();
4565                 if(statement == NULL)
4566                         continue;
4567
4568                 if(last_statement != NULL) {
4569                         last_statement->base.next = statement;
4570                 } else {
4571                         compound_statement->statements = statement;
4572                 }
4573
4574                 while(statement->base.next != NULL)
4575                         statement = statement->base.next;
4576
4577                 last_statement = statement;
4578         }
4579
4580         if(token.type != '}') {
4581                 parser_print_error_prefix_pos(
4582                                 compound_statement->statement.source_position);
4583                 fprintf(stderr, "end of file while looking for closing '}'\n");
4584         }
4585         next_token();
4586
4587         assert(context == &compound_statement->context);
4588         set_context(last_context);
4589         environment_pop_to(top);
4590
4591         return (statement_t*) compound_statement;
4592 }
4593
4594 static translation_unit_t *parse_translation_unit(void)
4595 {
4596         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
4597
4598         assert(global_context == NULL);
4599         global_context = &unit->context;
4600
4601         assert(context == NULL);
4602         set_context(&unit->context);
4603
4604         while(token.type != T_EOF) {
4605                 parse_declaration();
4606         }
4607
4608         assert(context == &unit->context);
4609         context          = NULL;
4610         last_declaration = NULL;
4611
4612         assert(global_context == &unit->context);
4613         global_context = NULL;
4614
4615         return unit;
4616 }
4617
4618 translation_unit_t *parse(void)
4619 {
4620         environment_stack = NEW_ARR_F(stack_entry_t, 0);
4621         label_stack       = NEW_ARR_F(stack_entry_t, 0);
4622         found_error       = false;
4623
4624         type_set_output(stderr);
4625         ast_set_output(stderr);
4626
4627         lookahead_bufpos = 0;
4628         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
4629                 next_token();
4630         }
4631         translation_unit_t *unit = parse_translation_unit();
4632
4633         DEL_ARR_F(environment_stack);
4634         DEL_ARR_F(label_stack);
4635
4636         if(found_error)
4637                 return NULL;
4638
4639         return unit;
4640 }
4641
4642 void init_parser(void)
4643 {
4644         init_expression_parsers();
4645         obstack_init(&temp_obst);
4646
4647         type_int         = make_atomic_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
4648         type_long_double = make_atomic_type(ATOMIC_TYPE_LONG_DOUBLE, TYPE_QUALIFIER_NONE);
4649         type_double      = make_atomic_type(ATOMIC_TYPE_DOUBLE, TYPE_QUALIFIER_NONE);
4650         type_float       = make_atomic_type(ATOMIC_TYPE_FLOAT, TYPE_QUALIFIER_NONE);
4651         type_size_t      = make_atomic_type(ATOMIC_TYPE_ULONG, TYPE_QUALIFIER_NONE);
4652         type_ptrdiff_t   = make_atomic_type(ATOMIC_TYPE_LONG, TYPE_QUALIFIER_NONE);
4653         type_char        = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_NONE);
4654         type_void        = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
4655         type_void_ptr    = make_pointer_type(type_void, TYPE_QUALIFIER_NONE);
4656         type_string      = make_pointer_type(type_char, TYPE_QUALIFIER_NONE);
4657 }
4658
4659 void exit_parser(void)
4660 {
4661         obstack_free(&temp_obst, NULL);
4662 }