17a6fdff5c8a15a9a9595db1558399eed0934264
[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                 /* type qualifiers */
1560 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1561                 case token:                                                     \
1562                         type_qualifiers |= qualifier;                               \
1563                         next_token();                                               \
1564                         break;
1565
1566                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1567                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1568                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1569
1570                 case T___extension__:
1571                         /* TODO */
1572                         next_token();
1573                         break;
1574
1575                 /* type specifiers */
1576 #define MATCH_SPECIFIER(token, specifier, name)                         \
1577                 case token:                                                     \
1578                         next_token();                                               \
1579                         if(type_specifiers & specifier) {                           \
1580                                 parse_error("multiple " name " type specifiers given"); \
1581                         } else {                                                    \
1582                                 type_specifiers |= specifier;                           \
1583                         }                                                           \
1584                         break;
1585
1586                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1587                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1588                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1589                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1590                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1591                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1592                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1593                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1594                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1595 #ifdef PROVIDE_COMPLEX
1596                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1597                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1598 #endif
1599                 case T_inline:
1600                         next_token();
1601                         specifiers->is_inline = true;
1602                         break;
1603
1604                 case T_long:
1605                         next_token();
1606                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1607                                 parse_error("multiple type specifiers given");
1608                         } else if(type_specifiers & SPECIFIER_LONG) {
1609                                 type_specifiers |= SPECIFIER_LONG_LONG;
1610                         } else {
1611                                 type_specifiers |= SPECIFIER_LONG;
1612                         }
1613                         break;
1614
1615                 /* TODO: if type != NULL for the following rules should issue
1616                  * an error */
1617                 case T_struct: {
1618                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1619
1620                         type->compound.declaration = parse_compound_type_specifier(true);
1621                         break;
1622                 }
1623                 case T_union: {
1624                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1625
1626                         type->compound.declaration = parse_compound_type_specifier(false);
1627                         break;
1628                 }
1629                 case T_enum:
1630                         type = parse_enum_specifier();
1631                         break;
1632                 case T___typeof__:
1633                         type = parse_typeof();
1634                         break;
1635                 case T___builtin_va_list:
1636                         type = create_builtin_type(token.v.symbol);
1637                         next_token();
1638                         break;
1639
1640                 case T___attribute__:
1641                         /* TODO */
1642                         parse_attributes();
1643                         break;
1644
1645                 case T_IDENTIFIER: {
1646                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1647
1648                         if(typedef_type == NULL)
1649                                 goto finish_specifiers;
1650
1651                         next_token();
1652                         type = typedef_type;
1653                         break;
1654                 }
1655
1656                 /* function specifier */
1657                 default:
1658                         goto finish_specifiers;
1659                 }
1660         }
1661
1662 finish_specifiers:
1663
1664         if(type == NULL) {
1665                 atomic_type_type_t atomic_type;
1666
1667                 /* match valid basic types */
1668                 switch(type_specifiers) {
1669                 case SPECIFIER_VOID:
1670                         atomic_type = ATOMIC_TYPE_VOID;
1671                         break;
1672                 case SPECIFIER_CHAR:
1673                         atomic_type = ATOMIC_TYPE_CHAR;
1674                         break;
1675                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1676                         atomic_type = ATOMIC_TYPE_SCHAR;
1677                         break;
1678                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1679                         atomic_type = ATOMIC_TYPE_UCHAR;
1680                         break;
1681                 case SPECIFIER_SHORT:
1682                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1683                 case SPECIFIER_SHORT | SPECIFIER_INT:
1684                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1685                         atomic_type = ATOMIC_TYPE_SHORT;
1686                         break;
1687                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1688                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1689                         atomic_type = ATOMIC_TYPE_USHORT;
1690                         break;
1691                 case SPECIFIER_INT:
1692                 case SPECIFIER_SIGNED:
1693                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1694                         atomic_type = ATOMIC_TYPE_INT;
1695                         break;
1696                 case SPECIFIER_UNSIGNED:
1697                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1698                         atomic_type = ATOMIC_TYPE_UINT;
1699                         break;
1700                 case SPECIFIER_LONG:
1701                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1702                 case SPECIFIER_LONG | SPECIFIER_INT:
1703                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1704                         atomic_type = ATOMIC_TYPE_LONG;
1705                         break;
1706                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1707                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1708                         atomic_type = ATOMIC_TYPE_ULONG;
1709                         break;
1710                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1711                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1712                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1713                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1714                         | SPECIFIER_INT:
1715                         atomic_type = ATOMIC_TYPE_LONGLONG;
1716                         break;
1717                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1718                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1719                         | SPECIFIER_INT:
1720                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1721                         break;
1722                 case SPECIFIER_FLOAT:
1723                         atomic_type = ATOMIC_TYPE_FLOAT;
1724                         break;
1725                 case SPECIFIER_DOUBLE:
1726                         atomic_type = ATOMIC_TYPE_DOUBLE;
1727                         break;
1728                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1729                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1730                         break;
1731                 case SPECIFIER_BOOL:
1732                         atomic_type = ATOMIC_TYPE_BOOL;
1733                         break;
1734 #ifdef PROVIDE_COMPLEX
1735                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1736                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1737                         break;
1738                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1739                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1740                         break;
1741                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1742                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1743                         break;
1744                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1745                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1746                         break;
1747                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1748                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1749                         break;
1750                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1751                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1752                         break;
1753 #endif
1754                 default:
1755                         /* invalid specifier combination, give an error message */
1756                         if(type_specifiers == 0) {
1757 #ifndef STRICT_C99
1758                                 parse_warning("no type specifiers in declaration (using int)");
1759                                 atomic_type = ATOMIC_TYPE_INT;
1760                                 break;
1761 #else
1762                                 parse_error("no type specifiers given in declaration");
1763 #endif
1764                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
1765                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
1766                                 parse_error("signed and unsigned specifiers gives");
1767                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
1768                                 parse_error("only integer types can be signed or unsigned");
1769                         } else {
1770                                 parse_error("multiple datatypes in declaration");
1771                         }
1772                         atomic_type = ATOMIC_TYPE_INVALID;
1773                 }
1774
1775                 type               = allocate_type_zero(TYPE_ATOMIC);
1776                 type->atomic.atype = atomic_type;
1777                 newtype            = 1;
1778         } else {
1779                 if(type_specifiers != 0) {
1780                         parse_error("multiple datatypes in declaration");
1781                 }
1782         }
1783
1784         type->base.qualifiers = type_qualifiers;
1785
1786         type_t *result = typehash_insert(type);
1787         if(newtype && result != type) {
1788                 free_type(type);
1789         }
1790
1791         specifiers->type = result;
1792 }
1793
1794 static type_qualifiers_t parse_type_qualifiers(void)
1795 {
1796         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
1797
1798         while(true) {
1799                 switch(token.type) {
1800                 /* type qualifiers */
1801                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1802                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1803                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1804
1805                 default:
1806                         return type_qualifiers;
1807                 }
1808         }
1809 }
1810
1811 static void parse_identifier_list(void)
1812 {
1813         while(true) {
1814                 if(token.type != T_IDENTIFIER) {
1815                         parse_error_expected("while parsing parameter identifier list",
1816                                              T_IDENTIFIER, 0);
1817                         return;
1818                 }
1819                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
1820                 declaration->symbol        = token.v.symbol;
1821
1822                 next_token();
1823
1824                 if(token.type != ',')
1825                         break;
1826                 next_token();
1827         }
1828 }
1829
1830 static declaration_t *parse_parameter(void)
1831 {
1832         declaration_specifiers_t specifiers;
1833         memset(&specifiers, 0, sizeof(specifiers));
1834
1835         parse_declaration_specifiers(&specifiers);
1836
1837         declaration_t *declaration
1838                 = parse_declarator(&specifiers, specifiers.type, true);
1839
1840         /* TODO check declaration constraints for parameters */
1841         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
1842                 parse_error("typedef not allowed in parameter list");
1843         }
1844
1845         /* Array as last part of a paramter type is just syntactic sugar.  Turn it
1846          * into a pointer */
1847         if (declaration->type->type == TYPE_ARRAY) {
1848                 const array_type_t *const arr_type = &declaration->type->array;
1849                 type_t *element_type = arr_type->element_type;
1850                 declaration->type = make_pointer_type(element_type, TYPE_QUALIFIER_NONE);
1851         }
1852
1853         return declaration;
1854 }
1855
1856 static declaration_t *parse_parameters(function_type_t *type)
1857 {
1858         if(token.type == T_IDENTIFIER) {
1859                 symbol_t      *symbol = token.v.symbol;
1860                 if(!is_typedef_symbol(symbol)) {
1861                         /* TODO: K&R style C parameters */
1862                         parse_identifier_list();
1863                         return NULL;
1864                 }
1865         }
1866
1867         if(token.type == ')') {
1868                 type->unspecified_parameters = 1;
1869                 return NULL;
1870         }
1871         if(token.type == T_void && look_ahead(1)->type == ')') {
1872                 next_token();
1873                 return NULL;
1874         }
1875
1876         declaration_t        *declarations = NULL;
1877         declaration_t        *declaration;
1878         declaration_t        *last_declaration = NULL;
1879         function_parameter_t *parameter;
1880         function_parameter_t *last_parameter = NULL;
1881
1882         while(true) {
1883                 switch(token.type) {
1884                 case T_DOTDOTDOT:
1885                         next_token();
1886                         type->variadic = 1;
1887                         return declarations;
1888
1889                 case T_IDENTIFIER:
1890                 case T___extension__:
1891                 DECLARATION_START
1892                         declaration = parse_parameter();
1893
1894                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
1895                         memset(parameter, 0, sizeof(parameter[0]));
1896                         parameter->type = declaration->type;
1897
1898                         if(last_parameter != NULL) {
1899                                 last_declaration->next = declaration;
1900                                 last_parameter->next   = parameter;
1901                         } else {
1902                                 type->parameters = parameter;
1903                                 declarations     = declaration;
1904                         }
1905                         last_parameter   = parameter;
1906                         last_declaration = declaration;
1907                         break;
1908
1909                 default:
1910                         return declarations;
1911                 }
1912                 if(token.type != ',')
1913                         return declarations;
1914                 next_token();
1915         }
1916 }
1917
1918 typedef enum {
1919         CONSTRUCT_INVALID,
1920         CONSTRUCT_POINTER,
1921         CONSTRUCT_FUNCTION,
1922         CONSTRUCT_ARRAY
1923 } construct_type_type_t;
1924
1925 typedef struct construct_type_t construct_type_t;
1926 struct construct_type_t {
1927         construct_type_type_t  type;
1928         construct_type_t      *next;
1929 };
1930
1931 typedef struct parsed_pointer_t parsed_pointer_t;
1932 struct parsed_pointer_t {
1933         construct_type_t  construct_type;
1934         type_qualifiers_t type_qualifiers;
1935 };
1936
1937 typedef struct construct_function_type_t construct_function_type_t;
1938 struct construct_function_type_t {
1939         construct_type_t  construct_type;
1940         type_t           *function_type;
1941 };
1942
1943 typedef struct parsed_array_t parsed_array_t;
1944 struct parsed_array_t {
1945         construct_type_t  construct_type;
1946         type_qualifiers_t type_qualifiers;
1947         bool              is_static;
1948         bool              is_variable;
1949         expression_t     *size;
1950 };
1951
1952 typedef struct construct_base_type_t construct_base_type_t;
1953 struct construct_base_type_t {
1954         construct_type_t  construct_type;
1955         type_t           *type;
1956 };
1957
1958 static construct_type_t *parse_pointer_declarator(void)
1959 {
1960         eat('*');
1961
1962         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
1963         memset(pointer, 0, sizeof(pointer[0]));
1964         pointer->construct_type.type = CONSTRUCT_POINTER;
1965         pointer->type_qualifiers     = parse_type_qualifiers();
1966
1967         return (construct_type_t*) pointer;
1968 }
1969
1970 static construct_type_t *parse_array_declarator(void)
1971 {
1972         eat('[');
1973
1974         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
1975         memset(array, 0, sizeof(array[0]));
1976         array->construct_type.type = CONSTRUCT_ARRAY;
1977
1978         if(token.type == T_static) {
1979                 array->is_static = true;
1980                 next_token();
1981         }
1982
1983         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
1984         if(type_qualifiers != 0) {
1985                 if(token.type == T_static) {
1986                         array->is_static = true;
1987                         next_token();
1988                 }
1989         }
1990         array->type_qualifiers = type_qualifiers;
1991
1992         if(token.type == '*' && look_ahead(1)->type == ']') {
1993                 array->is_variable = true;
1994                 next_token();
1995         } else if(token.type != ']') {
1996                 array->size = parse_assignment_expression();
1997         }
1998
1999         expect(']');
2000
2001         return (construct_type_t*) array;
2002 }
2003
2004 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2005 {
2006         eat('(');
2007
2008         type_t *type = allocate_type_zero(TYPE_FUNCTION);
2009
2010         declaration_t *parameters = parse_parameters(&type->function);
2011         if(declaration != NULL) {
2012                 declaration->context.declarations = parameters;
2013         }
2014
2015         construct_function_type_t *construct_function_type =
2016                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2017         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2018         construct_function_type->construct_type.type = CONSTRUCT_FUNCTION;
2019         construct_function_type->function_type       = type;
2020
2021         expect(')');
2022
2023         return (construct_type_t*) construct_function_type;
2024 }
2025
2026 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2027                 bool may_be_abstract)
2028 {
2029         /* construct a single linked list of construct_type_t's which describe
2030          * how to construct the final declarator type */
2031         construct_type_t *first = NULL;
2032         construct_type_t *last  = NULL;
2033
2034         /* pointers */
2035         while(token.type == '*') {
2036                 construct_type_t *type = parse_pointer_declarator();
2037
2038                 if(last == NULL) {
2039                         first = type;
2040                         last  = type;
2041                 } else {
2042                         last->next = type;
2043                         last       = type;
2044                 }
2045         }
2046
2047         /* TODO: find out if this is correct */
2048         parse_attributes();
2049
2050         construct_type_t *inner_types = NULL;
2051
2052         switch(token.type) {
2053         case T_IDENTIFIER:
2054                 if(declaration == NULL) {
2055                         parse_error("no identifier expected in typename");
2056                 } else {
2057                         declaration->symbol          = token.v.symbol;
2058                         declaration->source_position = token.source_position;
2059                 }
2060                 next_token();
2061                 break;
2062         case '(':
2063                 next_token();
2064                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2065                 expect(')');
2066                 break;
2067         default:
2068                 if(may_be_abstract)
2069                         break;
2070                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2071                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2072                  * eat '}' */
2073                 if(token.type == '}' && current_function == NULL) {
2074                         next_token();
2075                 } else {
2076                         eat_statement();
2077                 }
2078                 return NULL;
2079         }
2080
2081         construct_type_t *p = last;
2082
2083         while(true) {
2084                 construct_type_t *type;
2085                 switch(token.type) {
2086                 case '(':
2087                         type = parse_function_declarator(declaration);
2088                         break;
2089                 case '[':
2090                         type = parse_array_declarator();
2091                         break;
2092                 default:
2093                         goto declarator_finished;
2094                 }
2095
2096                 /* insert in the middle of the list (behind p) */
2097                 if(p != NULL) {
2098                         type->next = p->next;
2099                         p->next    = type;
2100                 } else {
2101                         type->next = first;
2102                         first      = type;
2103                 }
2104                 if(last == p) {
2105                         last = type;
2106                 }
2107         }
2108
2109 declarator_finished:
2110         parse_attributes();
2111
2112         /* append inner_types at the end of the list, we don't to set last anymore
2113          * as it's not needed anymore */
2114         if(last == NULL) {
2115                 assert(first == NULL);
2116                 first = inner_types;
2117         } else {
2118                 last->next = inner_types;
2119         }
2120
2121         return first;
2122 }
2123
2124 static type_t *construct_declarator_type(construct_type_t *construct_list,
2125                                          type_t *type)
2126 {
2127         construct_type_t *iter = construct_list;
2128         for( ; iter != NULL; iter = iter->next) {
2129                 switch(iter->type) {
2130                 case CONSTRUCT_INVALID:
2131                         panic("invalid type construction found");
2132                 case CONSTRUCT_FUNCTION: {
2133                         construct_function_type_t *construct_function_type
2134                                 = (construct_function_type_t*) iter;
2135
2136                         type_t *function_type = construct_function_type->function_type;
2137
2138                         function_type->function.result_type = type;
2139
2140                         type = function_type;
2141                         break;
2142                 }
2143
2144                 case CONSTRUCT_POINTER: {
2145                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2146                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER);
2147                         pointer_type->pointer.points_to  = type;
2148                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2149
2150                         type = pointer_type;
2151                         break;
2152                 }
2153
2154                 case CONSTRUCT_ARRAY: {
2155                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2156                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY);
2157
2158                         array_type->base.qualifiers    = parsed_array->type_qualifiers;
2159                         array_type->array.element_type = type;
2160                         array_type->array.is_static    = parsed_array->is_static;
2161                         array_type->array.is_variable  = parsed_array->is_variable;
2162                         array_type->array.size         = parsed_array->size;
2163
2164                         type = array_type;
2165                         break;
2166                 }
2167                 }
2168
2169                 type_t *hashed_type = typehash_insert(type);
2170                 if(hashed_type != type) {
2171                         /* the function type was constructed earlier freeing it here will
2172                          * destroy other types... */
2173                         if(iter->type != CONSTRUCT_FUNCTION) {
2174                                 free_type(type);
2175                         }
2176                         type = hashed_type;
2177                 }
2178         }
2179
2180         return type;
2181 }
2182
2183 static declaration_t *parse_declarator(
2184                 const declaration_specifiers_t *specifiers,
2185                 type_t *type, bool may_be_abstract)
2186 {
2187         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2188         declaration->storage_class = specifiers->storage_class;
2189         declaration->is_inline     = specifiers->is_inline;
2190
2191         construct_type_t *construct_type
2192                 = parse_inner_declarator(declaration, may_be_abstract);
2193         declaration->type = construct_declarator_type(construct_type, type);
2194
2195         if(construct_type != NULL) {
2196                 obstack_free(&temp_obst, construct_type);
2197         }
2198
2199         return declaration;
2200 }
2201
2202 static type_t *parse_abstract_declarator(type_t *base_type)
2203 {
2204         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2205
2206         type_t *result = construct_declarator_type(construct_type, base_type);
2207         if(construct_type != NULL) {
2208                 obstack_free(&temp_obst, construct_type);
2209         }
2210
2211         return result;
2212 }
2213
2214 static declaration_t *record_declaration(declaration_t *declaration)
2215 {
2216         assert(context != NULL);
2217
2218         symbol_t *symbol = declaration->symbol;
2219         if(symbol != NULL) {
2220                 declaration_t *alias = environment_push(declaration);
2221                 if(alias != declaration)
2222                         return alias;
2223         } else {
2224                 declaration->parent_context = context;
2225         }
2226
2227         if(last_declaration != NULL) {
2228                 last_declaration->next = declaration;
2229         } else {
2230                 context->declarations = declaration;
2231         }
2232         last_declaration = declaration;
2233
2234         return declaration;
2235 }
2236
2237 static void parser_error_multiple_definition(declaration_t *previous,
2238                                              declaration_t *declaration)
2239 {
2240         parser_print_error_prefix_pos(declaration->source_position);
2241         fprintf(stderr, "multiple definition of symbol '%s'\n",
2242                 declaration->symbol->string);
2243         parser_print_error_prefix_pos(previous->source_position);
2244         fprintf(stderr, "this is the location of the previous definition.\n");
2245 }
2246
2247 static void parse_init_declarators(const declaration_specifiers_t *specifiers)
2248 {
2249         while(true) {
2250                 declaration_t *ndeclaration
2251                         = parse_declarator(specifiers, specifiers->type, false);
2252
2253                 declaration_t *declaration = record_declaration(ndeclaration);
2254
2255                 type_t *orig_type = declaration->type;
2256                 type_t *type      = skip_typeref(orig_type);
2257                 if(type->type != TYPE_FUNCTION && declaration->is_inline) {
2258                         parser_print_warning_prefix_pos(declaration->source_position);
2259                         fprintf(stderr, "variable '%s' declared 'inline'\n",
2260                                 declaration->symbol->string);
2261                 }
2262
2263                 if(token.type == '=') {
2264                         next_token();
2265
2266                         /* TODO: check that this is an allowed type (no function type) */
2267
2268                         if(declaration->init.initializer != NULL) {
2269                                 parser_error_multiple_definition(declaration, ndeclaration);
2270                         }
2271
2272                         initializer_t *initializer = parse_initializer(type);
2273
2274                         if(type->type == TYPE_ARRAY && initializer != NULL) {
2275                                 array_type_t *array_type = &type->array;
2276
2277                                 if(array_type->size == NULL) {
2278                                         expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2279
2280                                         cnst->base.datatype = type_size_t;
2281
2282                                         if(initializer->type == INITIALIZER_LIST) {
2283                                                 initializer_list_t *list = &initializer->list;
2284                                                 cnst->conste.v.int_value = list->len;
2285                                         } else {
2286                                                 assert(initializer->type == INITIALIZER_STRING);
2287                                                 initializer_string_t *string = &initializer->string;
2288                                                 cnst->conste.v.int_value = strlen(string->string) + 1;
2289                                         }
2290
2291                                         array_type->size = cnst;
2292                                 }
2293                         }
2294
2295
2296                         ndeclaration->init.initializer = initializer;
2297                 } else if(token.type == '{') {
2298                         if(type->type != TYPE_FUNCTION) {
2299                                 parser_print_error_prefix();
2300                                 fprintf(stderr, "declarator '");
2301                                 print_type_ext(orig_type, declaration->symbol, NULL);
2302                                 fprintf(stderr, "' has a body but is not a function type.\n");
2303                                 eat_block();
2304                                 continue;
2305                         }
2306                         function_type_t *function_type = &type->function;
2307                         /* Â§ 6.7.5.3 (14) a function definition with () */
2308                         if(function_type->unspecified_parameters) {
2309                                 type_t *duplicate = duplicate_type(type);
2310                                 duplicate->function.unspecified_parameters = true;
2311
2312                                 type = typehash_insert(duplicate);
2313                                 if(type != duplicate) {
2314                                         obstack_free(type_obst, duplicate);
2315                                 }
2316                                 function_type = &type->function;
2317                         }
2318
2319                         if(declaration->init.statement != NULL) {
2320                                 parser_error_multiple_definition(declaration, ndeclaration);
2321                         }
2322                         if(ndeclaration != declaration) {
2323                                 memcpy(&declaration->context, &ndeclaration->context,
2324                                        sizeof(declaration->context));
2325                         }
2326
2327                         int         top          = environment_top();
2328                         context_t  *last_context = context;
2329                         set_context(&declaration->context);
2330
2331                         /* push function parameters */
2332                         declaration_t *parameter = declaration->context.declarations;
2333                         for( ; parameter != NULL; parameter = parameter->next) {
2334                                 environment_push(parameter);
2335                         }
2336
2337                         int            label_stack_top      = label_top();
2338                         declaration_t *old_current_function = current_function;
2339                         current_function                    = declaration;
2340
2341                         statement_t *statement = parse_compound_statement();
2342
2343                         assert(current_function == declaration);
2344                         current_function = old_current_function;
2345                         label_pop_to(label_stack_top);
2346
2347                         assert(context == &declaration->context);
2348                         set_context(last_context);
2349                         environment_pop_to(top);
2350
2351                         declaration->init.statement = statement;
2352                         return;
2353                 }
2354
2355                 if(token.type != ',')
2356                         break;
2357                 next_token();
2358         }
2359         expect_void(';');
2360 }
2361
2362 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2363 {
2364         while(1) {
2365                 if(token.type == ':') {
2366                         next_token();
2367                         parse_constant_expression();
2368                         /* TODO (bitfields) */
2369                 } else {
2370                         declaration_t *declaration
2371                                 = parse_declarator(specifiers, specifiers->type, true);
2372
2373                         /* TODO: check constraints for struct declarations */
2374                         /* TODO: check for doubled fields */
2375                         record_declaration(declaration);
2376
2377                         if(token.type == ':') {
2378                                 next_token();
2379                                 parse_constant_expression();
2380                                 /* TODO (bitfields) */
2381                         }
2382                 }
2383
2384                 if(token.type != ',')
2385                         break;
2386                 next_token();
2387         }
2388         expect_void(';');
2389 }
2390
2391 static void parse_compound_type_entries(void)
2392 {
2393         eat('{');
2394
2395         while(token.type != '}' && token.type != T_EOF) {
2396                 declaration_specifiers_t specifiers;
2397                 memset(&specifiers, 0, sizeof(specifiers));
2398                 parse_declaration_specifiers(&specifiers);
2399
2400                 parse_struct_declarators(&specifiers);
2401         }
2402         if(token.type == T_EOF) {
2403                 parse_error("unexpected error while parsing struct");
2404         }
2405         next_token();
2406 }
2407
2408 static void parse_declaration(void)
2409 {
2410         source_position_t source_position = token.source_position;
2411
2412         declaration_specifiers_t specifiers;
2413         memset(&specifiers, 0, sizeof(specifiers));
2414         parse_declaration_specifiers(&specifiers);
2415
2416         if(token.type == ';') {
2417                 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
2418                         parse_warning_pos(source_position,
2419                                           "useless keyword in empty declaration");
2420                 }
2421                 switch (specifiers.type->type) {
2422                         case TYPE_COMPOUND_STRUCT:
2423                         case TYPE_COMPOUND_UNION: {
2424                                 const compound_type_t *const comp_type
2425                                         = &specifiers.type->compound;
2426                                 if (comp_type->declaration->symbol == NULL) {
2427                                         parse_warning_pos(source_position,
2428                                                                                                                 "unnamed struct/union that defines no instances");
2429                                 }
2430                                 break;
2431                         }
2432
2433                         case TYPE_ENUM: break;
2434
2435                         default:
2436                                 parse_warning_pos(source_position, "empty declaration");
2437                                 break;
2438                 }
2439
2440                 next_token();
2441
2442                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2443
2444                 declaration->type            = specifiers.type;
2445                 declaration->storage_class   = specifiers.storage_class;
2446                 declaration->source_position = source_position;
2447                 record_declaration(declaration);
2448                 return;
2449         }
2450         parse_init_declarators(&specifiers);
2451 }
2452
2453 static type_t *parse_typename(void)
2454 {
2455         declaration_specifiers_t specifiers;
2456         memset(&specifiers, 0, sizeof(specifiers));
2457         parse_declaration_specifiers(&specifiers);
2458         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2459                 /* TODO: improve error message, user does probably not know what a
2460                  * storage class is...
2461                  */
2462                 parse_error("typename may not have a storage class");
2463         }
2464
2465         type_t *result = parse_abstract_declarator(specifiers.type);
2466
2467         return result;
2468 }
2469
2470
2471
2472
2473 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2474 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2475                                                           expression_t *left);
2476
2477 typedef struct expression_parser_function_t expression_parser_function_t;
2478 struct expression_parser_function_t {
2479         unsigned                         precedence;
2480         parse_expression_function        parser;
2481         unsigned                         infix_precedence;
2482         parse_expression_infix_function  infix_parser;
2483 };
2484
2485 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2486
2487 static expression_t *make_invalid_expression(void)
2488 {
2489         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2490         expression->base.source_position = token.source_position;
2491         return expression;
2492 }
2493
2494 static expression_t *expected_expression_error(void)
2495 {
2496         parser_print_error_prefix();
2497         fprintf(stderr, "expected expression, got token ");
2498         print_token(stderr, & token);
2499         fprintf(stderr, "\n");
2500
2501         next_token();
2502
2503         return make_invalid_expression();
2504 }
2505
2506 static expression_t *parse_string_const(void)
2507 {
2508         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2509         cnst->base.datatype = type_string;
2510         cnst->string.value  = parse_string_literals();
2511
2512         return cnst;
2513 }
2514
2515 static expression_t *parse_int_const(void)
2516 {
2517         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2518         cnst->base.datatype      = token.datatype;
2519         cnst->conste.v.int_value = token.v.intvalue;
2520
2521         next_token();
2522
2523         return cnst;
2524 }
2525
2526 static expression_t *parse_float_const(void)
2527 {
2528         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2529         cnst->base.datatype        = token.datatype;
2530         cnst->conste.v.float_value = token.v.floatvalue;
2531
2532         next_token();
2533
2534         return cnst;
2535 }
2536
2537 static declaration_t *create_implicit_function(symbol_t *symbol,
2538                 const source_position_t source_position)
2539 {
2540         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2541         ntype->function.result_type            = type_int;
2542         ntype->function.unspecified_parameters = true;
2543
2544         type_t *type = typehash_insert(ntype);
2545         if(type != ntype) {
2546                 free_type(ntype);
2547         }
2548
2549         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2550
2551         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2552         declaration->type            = type;
2553         declaration->symbol          = symbol;
2554         declaration->source_position = source_position;
2555
2556         /* prepend the implicit definition to the global context
2557          * this is safe since the symbol wasn't declared as anything else yet
2558          */
2559         assert(symbol->declaration == NULL);
2560
2561         context_t *last_context = context;
2562         context = global_context;
2563
2564         environment_push(declaration);
2565         declaration->next     = context->declarations;
2566         context->declarations = declaration;
2567
2568         context = last_context;
2569
2570         return declaration;
2571 }
2572
2573 static type_t *make_function_1_type(type_t *result_type, type_t *argument_type)
2574 {
2575         function_parameter_t *parameter
2576                 = obstack_alloc(type_obst, sizeof(parameter[0]));
2577         memset(parameter, 0, sizeof(parameter[0]));
2578         parameter->type = argument_type;
2579
2580         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
2581         type->function.result_type = result_type;
2582         type->function.parameters  = parameter;
2583
2584         type_t *result = typehash_insert(type);
2585         if(result != type) {
2586                 free_type(type);
2587         }
2588
2589         return result;
2590 }
2591
2592 static type_t *get_builtin_symbol_type(symbol_t *symbol)
2593 {
2594         switch(symbol->ID) {
2595         case T___builtin_alloca:
2596                 return make_function_1_type(type_void_ptr, type_size_t);
2597         default:
2598                 panic("not implemented builtin symbol found");
2599         }
2600 }
2601
2602 /**
2603  * performs automatic type cast as described in Â§ 6.3.2.1
2604  */
2605 static type_t *automatic_type_conversion(type_t *type)
2606 {
2607         if(type == NULL)
2608                 return NULL;
2609
2610         if(type->type == TYPE_ARRAY) {
2611                 array_type_t *array_type   = &type->array;
2612                 type_t       *element_type = array_type->element_type;
2613                 unsigned      qualifiers   = array_type->type.qualifiers;
2614
2615                 return make_pointer_type(element_type, qualifiers);
2616         }
2617
2618         if(type->type == TYPE_FUNCTION) {
2619                 return make_pointer_type(type, TYPE_QUALIFIER_NONE);
2620         }
2621
2622         return type;
2623 }
2624
2625 /**
2626  * reverts the automatic casts of array to pointer types and function
2627  * to function-pointer types as defined Â§ 6.3.2.1
2628  */
2629 type_t *revert_automatic_type_conversion(const expression_t *expression)
2630 {
2631         if(expression->base.datatype == NULL)
2632                 return NULL;
2633
2634         switch(expression->type) {
2635         case EXPR_REFERENCE: {
2636                 const reference_expression_t *ref = &expression->reference;
2637                 return ref->declaration->type;
2638         }
2639         case EXPR_SELECT: {
2640                 const select_expression_t *select = &expression->select;
2641                 return select->compound_entry->type;
2642         }
2643         case EXPR_UNARY: {
2644                 const unary_expression_t *unary = &expression->unary;
2645                 if(unary->type == UNEXPR_DEREFERENCE) {
2646                         expression_t   *value        = unary->value;
2647                         type_t         *type         = skip_typeref(value->base.datatype);
2648                         pointer_type_t *pointer_type = &type->pointer;
2649
2650                         return pointer_type->points_to;
2651                 }
2652                 break;
2653         }
2654         case EXPR_BUILTIN_SYMBOL: {
2655                 const builtin_symbol_expression_t *builtin
2656                         = &expression->builtin_symbol;
2657                 return get_builtin_symbol_type(builtin->symbol);
2658         }
2659         case EXPR_ARRAY_ACCESS: {
2660                 const array_access_expression_t *array_access
2661                         = &expression->array_access;
2662                 const expression_t *array_ref = array_access->array_ref;
2663                 type_t *type_left  = skip_typeref(array_ref->base.datatype);
2664                 assert(is_type_pointer(type_left));
2665                 pointer_type_t *pointer_type = &type_left->pointer;
2666                 return pointer_type->points_to;
2667         }
2668
2669         default:
2670                 break;
2671         }
2672
2673         return expression->base.datatype;
2674 }
2675
2676 static expression_t *parse_reference(void)
2677 {
2678         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
2679
2680         reference_expression_t *ref = &expression->reference;
2681         ref->symbol = token.v.symbol;
2682
2683         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
2684
2685         source_position_t source_position = token.source_position;
2686         next_token();
2687
2688         if(declaration == NULL) {
2689 #ifndef STRICT_C99
2690                 /* an implicitly defined function */
2691                 if(token.type == '(') {
2692                         parser_print_prefix_pos(token.source_position);
2693                         fprintf(stderr, "warning: implicit declaration of function '%s'\n",
2694                                 ref->symbol->string);
2695
2696                         declaration = create_implicit_function(ref->symbol,
2697                                                                source_position);
2698                 } else
2699 #endif
2700                 {
2701                         parser_print_error_prefix();
2702                         fprintf(stderr, "unknown symbol '%s' found.\n", ref->symbol->string);
2703                         return expression;
2704                 }
2705         }
2706
2707         type_t *type = declaration->type;
2708         /* we always do the auto-type conversions; the & and sizeof parser contains
2709          * code to revert this! */
2710         type = automatic_type_conversion(type);
2711
2712         ref->declaration         = declaration;
2713         ref->expression.datatype = type;
2714
2715         return expression;
2716 }
2717
2718 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
2719 {
2720         (void) expression;
2721         (void) dest_type;
2722         /* TODO check if explicit cast is allowed and issue warnings/errors */
2723 }
2724
2725 static expression_t *parse_cast(void)
2726 {
2727         expression_t *cast = allocate_expression_zero(EXPR_UNARY);
2728
2729         cast->unary.type           = UNEXPR_CAST;
2730         cast->base.source_position = token.source_position;
2731
2732         type_t *type  = parse_typename();
2733
2734         expect(')');
2735         expression_t *value = parse_sub_expression(20);
2736
2737         check_cast_allowed(value, type);
2738
2739         cast->base.datatype = type;
2740         cast->unary.value   = value;
2741
2742         return cast;
2743 }
2744
2745 static expression_t *parse_statement_expression(void)
2746 {
2747         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
2748
2749         statement_t *statement          = parse_compound_statement();
2750         expression->statement.statement = statement;
2751         if(statement == NULL) {
2752                 expect(')');
2753                 return NULL;
2754         }
2755
2756         assert(statement->type == STATEMENT_COMPOUND);
2757         compound_statement_t *compound_statement = &statement->compound;
2758
2759         /* find last statement and use it's type */
2760         const statement_t *last_statement = NULL;
2761         const statement_t *iter           = compound_statement->statements;
2762         for( ; iter != NULL; iter = iter->base.next) {
2763                 last_statement = iter;
2764         }
2765
2766         if(last_statement->type == STATEMENT_EXPRESSION) {
2767                 const expression_statement_t *expression_statement
2768                         = &last_statement->expression;
2769                 expression->base.datatype
2770                         = expression_statement->expression->base.datatype;
2771         } else {
2772                 expression->base.datatype = type_void;
2773         }
2774
2775         expect(')');
2776
2777         return expression;
2778 }
2779
2780 static expression_t *parse_brace_expression(void)
2781 {
2782         eat('(');
2783
2784         switch(token.type) {
2785         case '{':
2786                 /* gcc extension: a stement expression */
2787                 return parse_statement_expression();
2788
2789         TYPE_QUALIFIERS
2790         TYPE_SPECIFIERS
2791                 return parse_cast();
2792         case T_IDENTIFIER:
2793                 if(is_typedef_symbol(token.v.symbol)) {
2794                         return parse_cast();
2795                 }
2796         }
2797
2798         expression_t *result = parse_expression();
2799         expect(')');
2800
2801         return result;
2802 }
2803
2804 static expression_t *parse_function_keyword(void)
2805 {
2806         next_token();
2807         /* TODO */
2808
2809         if (current_function == NULL) {
2810                 parse_error("'__func__' used outside of a function");
2811         }
2812
2813         string_literal_expression_t *expression
2814                 = allocate_ast_zero(sizeof(expression[0]));
2815
2816         expression->expression.type     = EXPR_FUNCTION;
2817         expression->expression.datatype = type_string;
2818         expression->value               = "TODO: FUNCTION";
2819
2820         return (expression_t*) expression;
2821 }
2822
2823 static expression_t *parse_pretty_function_keyword(void)
2824 {
2825         eat(T___PRETTY_FUNCTION__);
2826         /* TODO */
2827
2828         string_literal_expression_t *expression
2829                 = allocate_ast_zero(sizeof(expression[0]));
2830
2831         expression->expression.type     = EXPR_PRETTY_FUNCTION;
2832         expression->expression.datatype = type_string;
2833         expression->value               = "TODO: PRETTY FUNCTION";
2834
2835         return (expression_t*) expression;
2836 }
2837
2838 static designator_t *parse_designator(void)
2839 {
2840         designator_t *result = allocate_ast_zero(sizeof(result[0]));
2841
2842         if(token.type != T_IDENTIFIER) {
2843                 parse_error_expected("while parsing member designator",
2844                                      T_IDENTIFIER, 0);
2845                 eat_brace();
2846                 return NULL;
2847         }
2848         result->symbol = token.v.symbol;
2849         next_token();
2850
2851         designator_t *last_designator = result;
2852         while(true) {
2853                 if(token.type == '.') {
2854                         next_token();
2855                         if(token.type != T_IDENTIFIER) {
2856                                 parse_error_expected("while parsing member designator",
2857                                                      T_IDENTIFIER, 0);
2858                                 eat_brace();
2859                                 return NULL;
2860                         }
2861                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2862                         designator->symbol       = token.v.symbol;
2863                         next_token();
2864
2865                         last_designator->next = designator;
2866                         last_designator       = designator;
2867                         continue;
2868                 }
2869                 if(token.type == '[') {
2870                         next_token();
2871                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2872                         designator->array_access = parse_expression();
2873                         if(designator->array_access == NULL) {
2874                                 eat_brace();
2875                                 return NULL;
2876                         }
2877                         expect(']');
2878
2879                         last_designator->next = designator;
2880                         last_designator       = designator;
2881                         continue;
2882                 }
2883                 break;
2884         }
2885
2886         return result;
2887 }
2888
2889 static expression_t *parse_offsetof(void)
2890 {
2891         eat(T___builtin_offsetof);
2892
2893         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
2894         expression->base.datatype = type_size_t;
2895
2896         expect('(');
2897         expression->offsetofe.type = parse_typename();
2898         expect(',');
2899         expression->offsetofe.designator = parse_designator();
2900         expect(')');
2901
2902         return expression;
2903 }
2904
2905 static expression_t *parse_va_arg(void)
2906 {
2907         eat(T___builtin_va_arg);
2908
2909         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
2910
2911         expect('(');
2912         expression->va_arge.arg = parse_assignment_expression();
2913         expect(',');
2914         expression->base.datatype = parse_typename();
2915         expect(')');
2916
2917         return expression;
2918 }
2919
2920 static expression_t *parse_builtin_symbol(void)
2921 {
2922         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
2923
2924         symbol_t *symbol = token.v.symbol;
2925
2926         expression->builtin_symbol.symbol = symbol;
2927         next_token();
2928
2929         type_t *type = get_builtin_symbol_type(symbol);
2930         type = automatic_type_conversion(type);
2931
2932         expression->base.datatype = type;
2933         return expression;
2934 }
2935
2936 static expression_t *parse_primary_expression(void)
2937 {
2938         switch(token.type) {
2939         case T_INTEGER:
2940                 return parse_int_const();
2941         case T_FLOATINGPOINT:
2942                 return parse_float_const();
2943         case T_STRING_LITERAL:
2944                 return parse_string_const();
2945         case T_IDENTIFIER:
2946                 return parse_reference();
2947         case T___FUNCTION__:
2948         case T___func__:
2949                 return parse_function_keyword();
2950         case T___PRETTY_FUNCTION__:
2951                 return parse_pretty_function_keyword();
2952         case T___builtin_offsetof:
2953                 return parse_offsetof();
2954         case T___builtin_va_arg:
2955                 return parse_va_arg();
2956         case T___builtin_alloca:
2957         case T___builtin_expect:
2958         case T___builtin_va_start:
2959         case T___builtin_va_end:
2960                 return parse_builtin_symbol();
2961
2962         case '(':
2963                 return parse_brace_expression();
2964         }
2965
2966         parser_print_error_prefix();
2967         fprintf(stderr, "unexpected token ");
2968         print_token(stderr, &token);
2969         fprintf(stderr, "\n");
2970         eat_statement();
2971
2972         return make_invalid_expression();
2973 }
2974
2975 static expression_t *parse_array_expression(unsigned precedence,
2976                                             expression_t *left)
2977 {
2978         (void) precedence;
2979
2980         eat('[');
2981
2982         expression_t *inside = parse_expression();
2983
2984         array_access_expression_t *array_access
2985                 = allocate_ast_zero(sizeof(array_access[0]));
2986
2987         array_access->expression.type = EXPR_ARRAY_ACCESS;
2988
2989         type_t *type_left   = left->base.datatype;
2990         type_t *type_inside = inside->base.datatype;
2991         type_t *result_type = NULL;
2992
2993         if(type_left != NULL && type_inside != NULL) {
2994                 type_left   = skip_typeref(type_left);
2995                 type_inside = skip_typeref(type_inside);
2996
2997                 if(is_type_pointer(type_left)) {
2998                         pointer_type_t *pointer = &type_left->pointer;
2999                         result_type             = pointer->points_to;
3000                         array_access->array_ref = left;
3001                         array_access->index     = inside;
3002                 } else if(is_type_pointer(type_inside)) {
3003                         pointer_type_t *pointer = &type_inside->pointer;
3004                         result_type             = pointer->points_to;
3005                         array_access->array_ref = inside;
3006                         array_access->index     = left;
3007                         array_access->flipped   = true;
3008                 } else {
3009                         parser_print_error_prefix();
3010                         fprintf(stderr, "array access on object with non-pointer types ");
3011                         print_type_quoted(type_left);
3012                         fprintf(stderr, ", ");
3013                         print_type_quoted(type_inside);
3014                         fprintf(stderr, "\n");
3015                 }
3016         } else {
3017                 array_access->array_ref = left;
3018                 array_access->index     = inside;
3019         }
3020
3021         if(token.type != ']') {
3022                 parse_error_expected("Problem while parsing array access", ']', 0);
3023                 return (expression_t*) array_access;
3024         }
3025         next_token();
3026
3027         result_type = automatic_type_conversion(result_type);
3028         array_access->expression.datatype = result_type;
3029
3030         return (expression_t*) array_access;
3031 }
3032
3033 static bool is_declaration_specifier(const token_t *token,
3034                                      bool only_type_specifiers)
3035 {
3036         switch(token->type) {
3037                 TYPE_SPECIFIERS
3038                         return 1;
3039                 case T_IDENTIFIER:
3040                         return is_typedef_symbol(token->v.symbol);
3041                 STORAGE_CLASSES
3042                 TYPE_QUALIFIERS
3043                         if(only_type_specifiers)
3044                                 return 0;
3045                         return 1;
3046
3047                 default:
3048                         return 0;
3049         }
3050 }
3051
3052 static expression_t *parse_sizeof(unsigned precedence)
3053 {
3054         eat(T_sizeof);
3055
3056         sizeof_expression_t *sizeof_expression
3057                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3058         sizeof_expression->expression.type     = EXPR_SIZEOF;
3059         sizeof_expression->expression.datatype = type_size_t;
3060
3061         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3062                 next_token();
3063                 sizeof_expression->type = parse_typename();
3064                 expect(')');
3065         } else {
3066                 expression_t *expression  = parse_sub_expression(precedence);
3067                 expression->base.datatype = revert_automatic_type_conversion(expression);
3068
3069                 sizeof_expression->type            = expression->base.datatype;
3070                 sizeof_expression->size_expression = expression;
3071         }
3072
3073         return (expression_t*) sizeof_expression;
3074 }
3075
3076 static expression_t *parse_select_expression(unsigned precedence,
3077                                              expression_t *compound)
3078 {
3079         (void) precedence;
3080         assert(token.type == '.' || token.type == T_MINUSGREATER);
3081
3082         bool is_pointer = (token.type == T_MINUSGREATER);
3083         next_token();
3084
3085         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3086         select->select.compound = compound;
3087
3088         if(token.type != T_IDENTIFIER) {
3089                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3090                 return select;
3091         }
3092         symbol_t *symbol      = token.v.symbol;
3093         select->select.symbol = symbol;
3094         next_token();
3095
3096         type_t *orig_type = compound->base.datatype;
3097         if(orig_type == NULL)
3098                 return make_invalid_expression();
3099
3100         type_t *type = skip_typeref(orig_type);
3101
3102         type_t *type_left = type;
3103         if(is_pointer) {
3104                 if(type->type != TYPE_POINTER) {
3105                         parser_print_error_prefix();
3106                         fprintf(stderr, "left hand side of '->' is not a pointer, but ");
3107                         print_type_quoted(orig_type);
3108                         fputc('\n', stderr);
3109                         return make_invalid_expression();
3110                 }
3111                 pointer_type_t *pointer_type = &type->pointer;
3112                 type_left                    = pointer_type->points_to;
3113         }
3114         type_left = skip_typeref(type_left);
3115
3116         if(type_left->type != TYPE_COMPOUND_STRUCT
3117                         && type_left->type != TYPE_COMPOUND_UNION) {
3118                 parser_print_error_prefix();
3119                 fprintf(stderr, "request for member '%s' in something not a struct or "
3120                         "union, but ", symbol->string);
3121                 print_type_quoted(type_left);
3122                 fputc('\n', stderr);
3123                 return make_invalid_expression();
3124         }
3125
3126         compound_type_t *compound_type = &type_left->compound;
3127         declaration_t   *declaration   = compound_type->declaration;
3128
3129         if(!declaration->init.is_defined) {
3130                 parser_print_error_prefix();
3131                 fprintf(stderr, "request for member '%s' of incomplete type ",
3132                         symbol->string);
3133                 print_type_quoted(type_left);
3134                 fputc('\n', stderr);
3135                 return make_invalid_expression();
3136         }
3137
3138         declaration_t *iter = declaration->context.declarations;
3139         for( ; iter != NULL; iter = iter->next) {
3140                 if(iter->symbol == symbol) {
3141                         break;
3142                 }
3143         }
3144         if(iter == NULL) {
3145                 parser_print_error_prefix();
3146                 print_type_quoted(type_left);
3147                 fprintf(stderr, " has no member named '%s'\n", symbol->string);
3148                 return make_invalid_expression();
3149         }
3150
3151         /* we always do the auto-type conversions; the & and sizeof parser contains
3152          * code to revert this! */
3153         type_t *expression_type = automatic_type_conversion(iter->type);
3154
3155         select->select.compound_entry = iter;
3156         select->base.datatype         = expression_type;
3157         return select;
3158 }
3159
3160 static expression_t *parse_call_expression(unsigned precedence,
3161                                            expression_t *expression)
3162 {
3163         (void) precedence;
3164         expression_t *result = allocate_expression_zero(EXPR_CALL);
3165
3166         call_expression_t *call  = &result->call;
3167         call->function           = expression;
3168
3169         function_type_t *function_type = NULL;
3170         type_t          *orig_type     = expression->base.datatype;
3171         if(orig_type != NULL) {
3172                 type_t *type  = skip_typeref(orig_type);
3173
3174                 if(is_type_pointer(type)) {
3175                         pointer_type_t *pointer_type = &type->pointer;
3176
3177                         type = skip_typeref(pointer_type->points_to);
3178
3179                         if (type->type == TYPE_FUNCTION) {
3180                                 function_type             = &type->function;
3181                                 call->expression.datatype = function_type->result_type;
3182                         }
3183                 }
3184                 if(function_type == NULL) {
3185                         parser_print_error_prefix();
3186                         fputs("called object '", stderr);
3187                         print_expression(expression);
3188                         fputs("' (type ", stderr);
3189                         print_type_quoted(orig_type);
3190                         fputs(") is not a pointer to a function\n", stderr);
3191
3192                         function_type             = NULL;
3193                         call->expression.datatype = NULL;
3194                 }
3195         }
3196
3197         /* parse arguments */
3198         eat('(');
3199
3200         if(token.type != ')') {
3201                 call_argument_t *last_argument = NULL;
3202
3203                 while(true) {
3204                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3205
3206                         argument->expression = parse_assignment_expression();
3207                         if(last_argument == NULL) {
3208                                 call->arguments = argument;
3209                         } else {
3210                                 last_argument->next = argument;
3211                         }
3212                         last_argument = argument;
3213
3214                         if(token.type != ',')
3215                                 break;
3216                         next_token();
3217                 }
3218         }
3219         expect(')');
3220
3221         if(function_type != NULL) {
3222                 function_parameter_t *parameter = function_type->parameters;
3223                 call_argument_t      *argument  = call->arguments;
3224                 for( ; parameter != NULL && argument != NULL;
3225                                 parameter = parameter->next, argument = argument->next) {
3226                         type_t *expected_type = parameter->type;
3227                         /* TODO report context in error messages */
3228                         argument->expression = create_implicit_cast(argument->expression,
3229                                                                     expected_type);
3230                 }
3231                 /* too few parameters */
3232                 if(parameter != NULL) {
3233                         parser_print_error_prefix();
3234                         fprintf(stderr, "too few arguments to function '");
3235                         print_expression(expression);
3236                         fprintf(stderr, "'\n");
3237                 } else if(argument != NULL) {
3238                         /* too many parameters */
3239                         if(!function_type->variadic
3240                                         && !function_type->unspecified_parameters) {
3241                                 parser_print_error_prefix();
3242                                 fprintf(stderr, "too many arguments to function '");
3243                                 print_expression(expression);
3244                                 fprintf(stderr, "'\n");
3245                         } else {
3246                                 /* do default promotion */
3247                                 for( ; argument != NULL; argument = argument->next) {
3248                                         type_t *type = argument->expression->base.datatype;
3249                                         type = skip_typeref(type);
3250
3251                                         if(type == NULL)
3252                                                 continue;
3253
3254                                         if(is_type_integer(type)) {
3255                                                 type = promote_integer(type);
3256                                         } else if(type == type_float) {
3257                                                 type = type_double;
3258                                         }
3259
3260                                         argument->expression
3261                                                 = create_implicit_cast(argument->expression, type);
3262                                 }
3263                         }
3264                 }
3265         }
3266
3267         return result;
3268 }
3269
3270 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3271
3272 static expression_t *parse_conditional_expression(unsigned precedence,
3273                                                   expression_t *expression)
3274 {
3275         eat('?');
3276
3277         conditional_expression_t *conditional
3278                 = allocate_ast_zero(sizeof(conditional[0]));
3279         conditional->expression.type = EXPR_CONDITIONAL;
3280         conditional->condition       = expression;
3281
3282         /* 6.5.15.2 */
3283         type_t *condition_type_orig = conditional->condition->base.datatype;
3284         if(condition_type_orig != NULL) {
3285                 type_t *condition_type      = skip_typeref(condition_type_orig);
3286                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3287                         type_error("expected a scalar type",
3288                                    expression->base.source_position, condition_type_orig);
3289                 }
3290         }
3291
3292         expression_t *const t_expr = parse_expression();
3293         conditional->true_expression = t_expr;
3294         expect(':');
3295         expression_t *const f_expr = parse_sub_expression(precedence);
3296         conditional->false_expression = f_expr;
3297
3298         type_t *const true_type  = t_expr->base.datatype;
3299         if(true_type == NULL)
3300                 return (expression_t*) conditional;
3301         type_t *const false_type = f_expr->base.datatype;
3302         if(false_type == NULL)
3303                 return (expression_t*) conditional;
3304
3305         type_t *const skipped_true_type  = skip_typeref(true_type);
3306         type_t *const skipped_false_type = skip_typeref(false_type);
3307
3308         /* 6.5.15.3 */
3309         if (skipped_true_type == skipped_false_type) {
3310                 conditional->expression.datatype = skipped_true_type;
3311         } else if (is_type_arithmetic(skipped_true_type) &&
3312                    is_type_arithmetic(skipped_false_type)) {
3313                 type_t *const result = semantic_arithmetic(skipped_true_type,
3314                                                            skipped_false_type);
3315                 conditional->true_expression  = create_implicit_cast(t_expr, result);
3316                 conditional->false_expression = create_implicit_cast(f_expr, result);
3317                 conditional->expression.datatype = result;
3318         } else if (skipped_true_type->type == TYPE_POINTER &&
3319                    skipped_false_type->type == TYPE_POINTER &&
3320                           true /* TODO compatible points_to types */) {
3321                 /* TODO */
3322         } else if(/* (is_null_ptr_const(skipped_true_type) &&
3323                       skipped_false_type->type == TYPE_POINTER)
3324                || (is_null_ptr_const(skipped_false_type) &&
3325                    skipped_true_type->type == TYPE_POINTER) TODO*/ false) {
3326                 /* TODO */
3327         } else if(/* 1 is pointer to object type, other is void* */ false) {
3328                 /* TODO */
3329         } else {
3330                 type_error_incompatible("while parsing conditional",
3331                                         expression->base.source_position, true_type,
3332                                         skipped_false_type);
3333         }
3334
3335         return (expression_t*) conditional;
3336 }
3337
3338 static expression_t *parse_extension(unsigned precedence)
3339 {
3340         eat(T___extension__);
3341
3342         /* TODO enable extensions */
3343
3344         return parse_sub_expression(precedence);
3345 }
3346
3347 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3348 {
3349         eat(T___builtin_classify_type);
3350
3351         classify_type_expression_t *const classify_type_expr =
3352                 allocate_ast_zero(sizeof(classify_type_expr[0]));
3353         classify_type_expr->expression.type     = EXPR_CLASSIFY_TYPE;
3354         classify_type_expr->expression.datatype = type_int;
3355
3356         expect('(');
3357         expression_t *const expression = parse_sub_expression(precedence);
3358         expect(')');
3359         classify_type_expr->type_expression = expression;
3360
3361         return (expression_t*)classify_type_expr;
3362 }
3363
3364 static void semantic_incdec(unary_expression_t *expression)
3365 {
3366         type_t *orig_type = expression->value->base.datatype;
3367         if(orig_type == NULL)
3368                 return;
3369
3370         type_t *type = skip_typeref(orig_type);
3371         if(!is_type_arithmetic(type) && type->type != TYPE_POINTER) {
3372                 /* TODO: improve error message */
3373                 parser_print_error_prefix();
3374                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
3375                 return;
3376         }
3377
3378         expression->expression.datatype = orig_type;
3379 }
3380
3381 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3382 {
3383         type_t *orig_type = expression->value->base.datatype;
3384         if(orig_type == NULL)
3385                 return;
3386
3387         type_t *type = skip_typeref(orig_type);
3388         if(!is_type_arithmetic(type)) {
3389                 /* TODO: improve error message */
3390                 parser_print_error_prefix();
3391                 fprintf(stderr, "operation needs an arithmetic type\n");
3392                 return;
3393         }
3394
3395         expression->expression.datatype = orig_type;
3396 }
3397
3398 static void semantic_unexpr_scalar(unary_expression_t *expression)
3399 {
3400         type_t *orig_type = expression->value->base.datatype;
3401         if(orig_type == NULL)
3402                 return;
3403
3404         type_t *type = skip_typeref(orig_type);
3405         if (!is_type_scalar(type)) {
3406                 parse_error("operand of ! must be of scalar type\n");
3407                 return;
3408         }
3409
3410         expression->expression.datatype = orig_type;
3411 }
3412
3413 static void semantic_unexpr_integer(unary_expression_t *expression)
3414 {
3415         type_t *orig_type = expression->value->base.datatype;
3416         if(orig_type == NULL)
3417                 return;
3418
3419         type_t *type = skip_typeref(orig_type);
3420         if (!is_type_integer(type)) {
3421                 parse_error("operand of ~ must be of integer type\n");
3422                 return;
3423         }
3424
3425         expression->expression.datatype = orig_type;
3426 }
3427
3428 static void semantic_dereference(unary_expression_t *expression)
3429 {
3430         type_t *orig_type = expression->value->base.datatype;
3431         if(orig_type == NULL)
3432                 return;
3433
3434         type_t *type = skip_typeref(orig_type);
3435         if(!is_type_pointer(type)) {
3436                 parser_print_error_prefix();
3437                 fputs("Unary '*' needs pointer or arrray type, but type ", stderr);
3438                 print_type_quoted(orig_type);
3439                 fputs(" given.\n", stderr);
3440                 return;
3441         }
3442
3443         pointer_type_t *pointer_type = &type->pointer;
3444         type_t         *result_type  = pointer_type->points_to;
3445
3446         result_type = automatic_type_conversion(result_type);
3447         expression->expression.datatype = result_type;
3448 }
3449
3450 static void semantic_take_addr(unary_expression_t *expression)
3451 {
3452         expression_t *value  = expression->value;
3453         value->base.datatype = revert_automatic_type_conversion(value);
3454
3455         type_t *orig_type = value->base.datatype;
3456         if(orig_type == NULL)
3457                 return;
3458
3459         if(value->type == EXPR_REFERENCE) {
3460                 reference_expression_t *reference   = (reference_expression_t*) value;
3461                 declaration_t          *declaration = reference->declaration;
3462                 if(declaration != NULL) {
3463                         declaration->address_taken = 1;
3464                 }
3465         }
3466
3467         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3468 }
3469
3470 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3471 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3472 {                                                                              \
3473         eat(token_type);                                                           \
3474                                                                                \
3475         unary_expression_t *unary_expression                                       \
3476                 = allocate_ast_zero(sizeof(unary_expression[0]));                      \
3477         unary_expression->expression.type     = EXPR_UNARY;                        \
3478         unary_expression->type                = unexpression_type;                 \
3479         unary_expression->value               = parse_sub_expression(precedence);  \
3480                                                                                    \
3481         sfunc(unary_expression);                                                   \
3482                                                                                \
3483         return (expression_t*) unary_expression;                                   \
3484 }
3485
3486 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE, semantic_unexpr_arithmetic)
3487 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS,   semantic_unexpr_arithmetic)
3488 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT,    semantic_unexpr_scalar)
3489 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE, semantic_dereference)
3490 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS, semantic_take_addr)
3491 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE,
3492                                semantic_unexpr_integer)
3493 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT,
3494                                semantic_incdec)
3495 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT,
3496                                semantic_incdec)
3497
3498 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
3499                                                sfunc)                         \
3500 static expression_t *parse_##unexpression_type(unsigned precedence,           \
3501                                                expression_t *left)            \
3502 {                                                                             \
3503         (void) precedence;                                                        \
3504         eat(token_type);                                                          \
3505                                                                               \
3506         unary_expression_t *unary_expression                                      \
3507                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
3508         unary_expression->expression.type     = EXPR_UNARY;                       \
3509         unary_expression->type                = unexpression_type;                \
3510         unary_expression->value               = left;                             \
3511                                                                                   \
3512         sfunc(unary_expression);                                                  \
3513                                                                               \
3514         return (expression_t*) unary_expression;                                  \
3515 }
3516
3517 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT,
3518                                        semantic_incdec)
3519 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT,
3520                                        semantic_incdec)
3521
3522 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
3523 {
3524         /* TODO: handle complex + imaginary types */
3525
3526         /* Â§ 6.3.1.8 Usual arithmetic conversions */
3527         if(type_left == type_long_double || type_right == type_long_double) {
3528                 return type_long_double;
3529         } else if(type_left == type_double || type_right == type_double) {
3530                 return type_double;
3531         } else if(type_left == type_float || type_right == type_float) {
3532                 return type_float;
3533         }
3534
3535         type_right = promote_integer(type_right);
3536         type_left  = promote_integer(type_left);
3537
3538         if(type_left == type_right)
3539                 return type_left;
3540
3541         bool signed_left  = is_type_signed(type_left);
3542         bool signed_right = is_type_signed(type_right);
3543         int  rank_left    = get_rank(type_left);
3544         int  rank_right   = get_rank(type_right);
3545         if(rank_left < rank_right) {
3546                 if(signed_left == signed_right || !signed_right) {
3547                         return type_right;
3548                 } else {
3549                         return type_left;
3550                 }
3551         } else {
3552                 if(signed_left == signed_right || !signed_left) {
3553                         return type_left;
3554                 } else {
3555                         return type_right;
3556                 }
3557         }
3558 }
3559
3560 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
3561 {
3562         expression_t *left       = expression->left;
3563         expression_t *right      = expression->right;
3564         type_t       *orig_type_left  = left->base.datatype;
3565         type_t       *orig_type_right = right->base.datatype;
3566
3567         if(orig_type_left == NULL || orig_type_right == NULL)
3568                 return;
3569
3570         type_t *type_left  = skip_typeref(orig_type_left);
3571         type_t *type_right = skip_typeref(orig_type_right);
3572
3573         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3574                 /* TODO: improve error message */
3575                 parser_print_error_prefix();
3576                 fprintf(stderr, "operation needs arithmetic types\n");
3577                 return;
3578         }
3579
3580         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3581         expression->left  = create_implicit_cast(left, arithmetic_type);
3582         expression->right = create_implicit_cast(right, arithmetic_type);
3583         expression->expression.datatype = arithmetic_type;
3584 }
3585
3586 static void semantic_shift_op(binary_expression_t *expression)
3587 {
3588         expression_t *left       = expression->left;
3589         expression_t *right      = expression->right;
3590         type_t       *orig_type_left  = left->base.datatype;
3591         type_t       *orig_type_right = right->base.datatype;
3592
3593         if(orig_type_left == NULL || orig_type_right == NULL)
3594                 return;
3595
3596         type_t *type_left  = skip_typeref(orig_type_left);
3597         type_t *type_right = skip_typeref(orig_type_right);
3598
3599         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
3600                 /* TODO: improve error message */
3601                 parser_print_error_prefix();
3602                 fprintf(stderr, "operation needs integer types\n");
3603                 return;
3604         }
3605
3606         type_left  = promote_integer(type_left);
3607         type_right = promote_integer(type_right);
3608
3609         expression->left  = create_implicit_cast(left, type_left);
3610         expression->right = create_implicit_cast(right, type_right);
3611         expression->expression.datatype = type_left;
3612 }
3613
3614 static void semantic_add(binary_expression_t *expression)
3615 {
3616         expression_t *left            = expression->left;
3617         expression_t *right           = expression->right;
3618         type_t       *orig_type_left  = left->base.datatype;
3619         type_t       *orig_type_right = right->base.datatype;
3620
3621         if(orig_type_left == NULL || orig_type_right == NULL)
3622                 return;
3623
3624         type_t *type_left  = skip_typeref(orig_type_left);
3625         type_t *type_right = skip_typeref(orig_type_right);
3626
3627         /* Â§ 5.6.5 */
3628         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3629                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3630                 expression->left  = create_implicit_cast(left, arithmetic_type);
3631                 expression->right = create_implicit_cast(right, arithmetic_type);
3632                 expression->expression.datatype = arithmetic_type;
3633                 return;
3634         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
3635                 expression->expression.datatype = type_left;
3636         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
3637                 expression->expression.datatype = type_right;
3638         } else {
3639                 parser_print_error_prefix();
3640                 fprintf(stderr, "invalid operands to binary + (");
3641                 print_type_quoted(orig_type_left);
3642                 fprintf(stderr, ", ");
3643                 print_type_quoted(orig_type_right);
3644                 fprintf(stderr, ")\n");
3645         }
3646 }
3647
3648 static void semantic_sub(binary_expression_t *expression)
3649 {
3650         expression_t *left            = expression->left;
3651         expression_t *right           = expression->right;
3652         type_t       *orig_type_left  = left->base.datatype;
3653         type_t       *orig_type_right = right->base.datatype;
3654
3655         if(orig_type_left == NULL || orig_type_right == NULL)
3656                 return;
3657
3658         type_t       *type_left       = skip_typeref(orig_type_left);
3659         type_t       *type_right      = skip_typeref(orig_type_right);
3660
3661         /* Â§ 5.6.5 */
3662         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3663                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3664                 expression->left  = create_implicit_cast(left, arithmetic_type);
3665                 expression->right = create_implicit_cast(right, arithmetic_type);
3666                 expression->expression.datatype = arithmetic_type;
3667                 return;
3668         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3669                 expression->expression.datatype = type_left;
3670         } else if(type_left->type == TYPE_POINTER &&
3671                         type_right->type == TYPE_POINTER) {
3672                 if(!pointers_compatible(type_left, type_right)) {
3673                         parser_print_error_prefix();
3674                         fprintf(stderr, "pointers to incompatible objects to binary - (");
3675                         print_type_quoted(orig_type_left);
3676                         fprintf(stderr, ", ");
3677                         print_type_quoted(orig_type_right);
3678                         fprintf(stderr, ")\n");
3679                 } else {
3680                         expression->expression.datatype = type_ptrdiff_t;
3681                 }
3682         } else {
3683                 parser_print_error_prefix();
3684                 fprintf(stderr, "invalid operands to binary - (");
3685                 print_type_quoted(orig_type_left);
3686                 fprintf(stderr, ", ");
3687                 print_type_quoted(orig_type_right);
3688                 fprintf(stderr, ")\n");
3689         }
3690 }
3691
3692 static void semantic_comparison(binary_expression_t *expression)
3693 {
3694         expression_t *left            = expression->left;
3695         expression_t *right           = expression->right;
3696         type_t       *orig_type_left  = left->base.datatype;
3697         type_t       *orig_type_right = right->base.datatype;
3698
3699         if(orig_type_left == NULL || orig_type_right == NULL)
3700                 return;
3701
3702         type_t *type_left  = skip_typeref(orig_type_left);
3703         type_t *type_right = skip_typeref(orig_type_right);
3704
3705         /* TODO non-arithmetic types */
3706         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3707                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3708                 expression->left  = create_implicit_cast(left, arithmetic_type);
3709                 expression->right = create_implicit_cast(right, arithmetic_type);
3710                 expression->expression.datatype = arithmetic_type;
3711         } else if (type_left->type  == TYPE_POINTER &&
3712                    type_right->type == TYPE_POINTER) {
3713                 /* TODO check compatibility */
3714         } else if (type_left->type == TYPE_POINTER) {
3715                 expression->right = create_implicit_cast(right, type_left);
3716         } else if (type_right->type == TYPE_POINTER) {
3717                 expression->left = create_implicit_cast(left, type_right);
3718         } else {
3719                 type_error_incompatible("invalid operands in comparison",
3720                                         token.source_position, type_left, type_right);
3721         }
3722         expression->expression.datatype = type_int;
3723 }
3724
3725 static void semantic_arithmetic_assign(binary_expression_t *expression)
3726 {
3727         expression_t *left            = expression->left;
3728         expression_t *right           = expression->right;
3729         type_t       *orig_type_left  = left->base.datatype;
3730         type_t       *orig_type_right = right->base.datatype;
3731
3732         if(orig_type_left == NULL || orig_type_right == NULL)
3733                 return;
3734
3735         type_t *type_left  = skip_typeref(orig_type_left);
3736         type_t *type_right = skip_typeref(orig_type_right);
3737
3738         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3739                 /* TODO: improve error message */
3740                 parser_print_error_prefix();
3741                 fprintf(stderr, "operation needs arithmetic types\n");
3742                 return;
3743         }
3744
3745         /* combined instructions are tricky. We can't create an implicit cast on
3746          * the left side, because we need the uncasted form for the store.
3747          * The ast2firm pass has to know that left_type must be right_type
3748          * for the arithmeitc operation and create a cast by itself */
3749         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3750         expression->right       = create_implicit_cast(right, arithmetic_type);
3751         expression->expression.datatype = type_left;
3752 }
3753
3754 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
3755 {
3756         expression_t *left            = expression->left;
3757         expression_t *right           = expression->right;
3758         type_t       *orig_type_left  = left->base.datatype;
3759         type_t       *orig_type_right = right->base.datatype;
3760
3761         if(orig_type_left == NULL || orig_type_right == NULL)
3762                 return;
3763
3764         type_t *type_left  = skip_typeref(orig_type_left);
3765         type_t *type_right = skip_typeref(orig_type_right);
3766
3767         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3768                 /* combined instructions are tricky. We can't create an implicit cast on
3769                  * the left side, because we need the uncasted form for the store.
3770                  * The ast2firm pass has to know that left_type must be right_type
3771                  * for the arithmeitc operation and create a cast by itself */
3772                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
3773                 expression->right = create_implicit_cast(right, arithmetic_type);
3774                 expression->expression.datatype = type_left;
3775         } else if (type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3776                 expression->expression.datatype = type_left;
3777         } else {
3778                 parser_print_error_prefix();
3779                 fputs("Incompatible types ", stderr);
3780                 print_type_quoted(orig_type_left);
3781                 fputs(" and ", stderr);
3782                 print_type_quoted(orig_type_right);
3783                 fputs(" in assignment\n", stderr);
3784                 return;
3785         }
3786 }
3787
3788 static void semantic_logical_op(binary_expression_t *expression)
3789 {
3790         expression_t *left            = expression->left;
3791         expression_t *right           = expression->right;
3792         type_t       *orig_type_left  = left->base.datatype;
3793         type_t       *orig_type_right = right->base.datatype;
3794
3795         if(orig_type_left == NULL || orig_type_right == NULL)
3796                 return;
3797
3798         type_t *type_left  = skip_typeref(orig_type_left);
3799         type_t *type_right = skip_typeref(orig_type_right);
3800
3801         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
3802                 /* TODO: improve error message */
3803                 parser_print_error_prefix();
3804                 fprintf(stderr, "operation needs scalar types\n");
3805                 return;
3806         }
3807
3808         expression->expression.datatype = type_int;
3809 }
3810
3811 static bool has_const_fields(type_t *type)
3812 {
3813         (void) type;
3814         /* TODO */
3815         return false;
3816 }
3817
3818 static void semantic_binexpr_assign(binary_expression_t *expression)
3819 {
3820         expression_t *left           = expression->left;
3821         type_t       *orig_type_left = left->base.datatype;
3822
3823         if(orig_type_left == NULL)
3824                 return;
3825
3826         type_t *type_left = revert_automatic_type_conversion(left);
3827         type_left = skip_typeref(orig_type_left);
3828
3829         /* must be a modifiable lvalue */
3830         if (type_left->type == TYPE_ARRAY) {
3831                 parser_print_error_prefix();
3832                 fprintf(stderr, "Cannot assign to arrays ('");
3833                 print_expression(left);
3834                 fprintf(stderr, "')\n");
3835                 return;
3836         }
3837         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
3838                 parser_print_error_prefix();
3839                 fprintf(stderr, "assignment to readonly location '");
3840                 print_expression(left);
3841                 fprintf(stderr, "' (type ");
3842                 print_type_quoted(orig_type_left);
3843                 fprintf(stderr, ")\n");
3844                 return;
3845         }
3846         if(is_type_incomplete(type_left)) {
3847                 parser_print_error_prefix();
3848                 fprintf(stderr, "left-hand side of assignment '");
3849                 print_expression(left);
3850                 fprintf(stderr, "' has incomplete type ");
3851                 print_type_quoted(orig_type_left);
3852                 fprintf(stderr, "\n");
3853                 return;
3854         }
3855         if(is_type_compound(type_left) && has_const_fields(type_left)) {
3856                 parser_print_error_prefix();
3857                 fprintf(stderr, "can't assign to '");
3858                 print_expression(left);
3859                 fprintf(stderr, "' because compound type ");
3860                 print_type_quoted(orig_type_left);
3861                 fprintf(stderr, " has readonly fields\n");
3862                 return;
3863         }
3864
3865         semantic_assign(orig_type_left, &expression->right, "assignment");
3866
3867         expression->expression.datatype = orig_type_left;
3868 }
3869
3870 static void semantic_comma(binary_expression_t *expression)
3871 {
3872         expression->expression.datatype = expression->right->base.datatype;
3873 }
3874
3875 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
3876 static expression_t *parse_##binexpression_type(unsigned precedence,     \
3877                                                 expression_t *left)      \
3878 {                                                                        \
3879         eat(token_type);                                                     \
3880                                                                          \
3881         expression_t *right = parse_sub_expression(precedence + lr);         \
3882                                                                          \
3883         binary_expression_t *binexpr                                         \
3884                 = allocate_ast_zero(sizeof(binexpr[0]));                         \
3885         binexpr->expression.type     = EXPR_BINARY;                          \
3886         binexpr->type                = binexpression_type;                   \
3887         binexpr->left                = left;                                 \
3888         binexpr->right               = right;                                \
3889         sfunc(binexpr);                                                      \
3890                                                                          \
3891         return (expression_t*) binexpr;                                      \
3892 }
3893
3894 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA,          semantic_comma, 1)
3895 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL,            semantic_binexpr_arithmetic, 1)
3896 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV,            semantic_binexpr_arithmetic, 1)
3897 CREATE_BINEXPR_PARSER('%', BINEXPR_MOD,            semantic_binexpr_arithmetic, 1)
3898 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD,            semantic_add, 1)
3899 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB,            semantic_sub, 1)
3900 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS,           semantic_comparison, 1)
3901 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER,        semantic_comparison, 1)
3902 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN,         semantic_binexpr_assign, 0)
3903 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL, semantic_comparison, 1)
3904 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL,
3905                       semantic_comparison, 1)
3906 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL, semantic_comparison, 1)
3907 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL,
3908                       semantic_comparison, 1)
3909 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND,    semantic_binexpr_arithmetic, 1)
3910 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR,     semantic_binexpr_arithmetic, 1)
3911 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR,    semantic_binexpr_arithmetic, 1)
3912 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND,  semantic_logical_op, 1)
3913 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR, semantic_logical_op, 1)
3914 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT,
3915                       semantic_shift_op, 1)
3916 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT,
3917                       semantic_shift_op, 1)
3918 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN,
3919                       semantic_arithmetic_addsubb_assign, 0)
3920 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN,
3921                       semantic_arithmetic_addsubb_assign, 0)
3922 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN,
3923                       semantic_arithmetic_assign, 0)
3924 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN,
3925                       semantic_arithmetic_assign, 0)
3926 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN,
3927                       semantic_arithmetic_assign, 0)
3928 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN,
3929                       semantic_arithmetic_assign, 0)
3930 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN,
3931                       semantic_arithmetic_assign, 0)
3932 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN,
3933                       semantic_arithmetic_assign, 0)
3934 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN,
3935                       semantic_arithmetic_assign, 0)
3936 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN,
3937                       semantic_arithmetic_assign, 0)
3938
3939 static expression_t *parse_sub_expression(unsigned precedence)
3940 {
3941         if(token.type < 0) {
3942                 return expected_expression_error();
3943         }
3944
3945         expression_parser_function_t *parser
3946                 = &expression_parsers[token.type];
3947         source_position_t             source_position = token.source_position;
3948         expression_t                 *left;
3949
3950         if(parser->parser != NULL) {
3951                 left = parser->parser(parser->precedence);
3952         } else {
3953                 left = parse_primary_expression();
3954         }
3955         assert(left != NULL);
3956         left->base.source_position = source_position;
3957
3958         while(true) {
3959                 if(token.type < 0) {
3960                         return expected_expression_error();
3961                 }
3962
3963                 parser = &expression_parsers[token.type];
3964                 if(parser->infix_parser == NULL)
3965                         break;
3966                 if(parser->infix_precedence < precedence)
3967                         break;
3968
3969                 left = parser->infix_parser(parser->infix_precedence, left);
3970
3971                 assert(left != NULL);
3972                 assert(left->type != EXPR_UNKNOWN);
3973                 left->base.source_position = source_position;
3974         }
3975
3976         return left;
3977 }
3978
3979 static expression_t *parse_expression(void)
3980 {
3981         return parse_sub_expression(1);
3982 }
3983
3984
3985
3986 static void register_expression_parser(parse_expression_function parser,
3987                                        int token_type, unsigned precedence)
3988 {
3989         expression_parser_function_t *entry = &expression_parsers[token_type];
3990
3991         if(entry->parser != NULL) {
3992                 fprintf(stderr, "for token ");
3993                 print_token_type(stderr, (token_type_t) token_type);
3994                 fprintf(stderr, "\n");
3995                 panic("trying to register multiple expression parsers for a token");
3996         }
3997         entry->parser     = parser;
3998         entry->precedence = precedence;
3999 }
4000
4001 static void register_expression_infix_parser(
4002                 parse_expression_infix_function parser, int token_type,
4003                 unsigned precedence)
4004 {
4005         expression_parser_function_t *entry = &expression_parsers[token_type];
4006
4007         if(entry->infix_parser != NULL) {
4008                 fprintf(stderr, "for token ");
4009                 print_token_type(stderr, (token_type_t) token_type);
4010                 fprintf(stderr, "\n");
4011                 panic("trying to register multiple infix expression parsers for a "
4012                       "token");
4013         }
4014         entry->infix_parser     = parser;
4015         entry->infix_precedence = precedence;
4016 }
4017
4018 static void init_expression_parsers(void)
4019 {
4020         memset(&expression_parsers, 0, sizeof(expression_parsers));
4021
4022         register_expression_infix_parser(parse_BINEXPR_MUL,         '*',        16);
4023         register_expression_infix_parser(parse_BINEXPR_DIV,         '/',        16);
4024         register_expression_infix_parser(parse_BINEXPR_MOD,         '%',        16);
4025         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,   T_LESSLESS, 16);
4026         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
4027                                                               T_GREATERGREATER, 16);
4028         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
4029         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
4030         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
4031         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
4032         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
4033         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
4034                                                                 T_GREATEREQUAL, 14);
4035         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
4036         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
4037                                                         T_EXCLAMATIONMARKEQUAL, 13);
4038         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
4039         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
4040         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
4041         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
4042         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
4043         register_expression_infix_parser(parse_conditional_expression, '?',      7);
4044         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
4045         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
4046         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
4047         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
4048                                                                 T_ASTERISKEQUAL, 2);
4049         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
4050         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
4051                                                                  T_PERCENTEQUAL, 2);
4052         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
4053                                                                 T_LESSLESSEQUAL, 2);
4054         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
4055                                                           T_GREATERGREATEREQUAL, 2);
4056         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
4057                                                                      T_ANDEQUAL, 2);
4058         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
4059                                                                     T_PIPEEQUAL, 2);
4060         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
4061                                                                    T_CARETEQUAL, 2);
4062
4063         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
4064
4065         register_expression_infix_parser(parse_array_expression,        '[',    30);
4066         register_expression_infix_parser(parse_call_expression,         '(',    30);
4067         register_expression_infix_parser(parse_select_expression,       '.',    30);
4068         register_expression_infix_parser(parse_select_expression,
4069                                                                 T_MINUSGREATER, 30);
4070         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
4071                                          T_PLUSPLUS, 30);
4072         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
4073                                          T_MINUSMINUS, 30);
4074
4075         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
4076         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
4077         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
4078         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
4079         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
4080         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
4081         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
4082         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
4083         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4084         register_expression_parser(parse_extension,            T___extension__, 25);
4085         register_expression_parser(parse_builtin_classify_type,
4086                                                      T___builtin_classify_type, 25);
4087 }
4088
4089
4090 static statement_t *parse_case_statement(void)
4091 {
4092         eat(T_case);
4093         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
4094         label->statement.type            = STATEMENT_CASE_LABEL;
4095         label->statement.source_position = token.source_position;
4096
4097         label->expression = parse_expression();
4098
4099         expect(':');
4100         label->label_statement = parse_statement();
4101
4102         return (statement_t*) label;
4103 }
4104
4105 static statement_t *parse_default_statement(void)
4106 {
4107         eat(T_default);
4108
4109         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
4110         label->statement.type            = STATEMENT_CASE_LABEL;
4111         label->statement.source_position = token.source_position;
4112
4113         expect(':');
4114         label->label_statement = parse_statement();
4115
4116         return (statement_t*) label;
4117 }
4118
4119 static declaration_t *get_label(symbol_t *symbol)
4120 {
4121         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4122         assert(current_function != NULL);
4123         /* if we found a label in the same function, then we already created the
4124          * declaration */
4125         if(candidate != NULL
4126                         && candidate->parent_context == &current_function->context) {
4127                 return candidate;
4128         }
4129
4130         /* otherwise we need to create a new one */
4131         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4132         declaration->namespc     = NAMESPACE_LABEL;
4133         declaration->symbol        = symbol;
4134
4135         label_push(declaration);
4136
4137         return declaration;
4138 }
4139
4140 static statement_t *parse_label_statement(void)
4141 {
4142         assert(token.type == T_IDENTIFIER);
4143         symbol_t *symbol = token.v.symbol;
4144         next_token();
4145
4146         declaration_t *label = get_label(symbol);
4147
4148         /* if source position is already set then the label is defined twice,
4149          * otherwise it was just mentioned in a goto so far */
4150         if(label->source_position.input_name != NULL) {
4151                 parser_print_error_prefix();
4152                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
4153                 parser_print_error_prefix_pos(label->source_position);
4154                 fprintf(stderr, "previous definition of '%s' was here\n",
4155                         symbol->string);
4156         } else {
4157                 label->source_position = token.source_position;
4158         }
4159
4160         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4161
4162         label_statement->statement.type            = STATEMENT_LABEL;
4163         label_statement->statement.source_position = token.source_position;
4164         label_statement->label                     = label;
4165
4166         expect(':');
4167
4168         if(token.type == '}') {
4169                 parse_error("label at end of compound statement");
4170                 return (statement_t*) label_statement;
4171         } else {
4172                 label_statement->label_statement = parse_statement();
4173         }
4174
4175         return (statement_t*) label_statement;
4176 }
4177
4178 static statement_t *parse_if(void)
4179 {
4180         eat(T_if);
4181
4182         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4183         statement->statement.type            = STATEMENT_IF;
4184         statement->statement.source_position = token.source_position;
4185
4186         expect('(');
4187         statement->condition = parse_expression();
4188         expect(')');
4189
4190         statement->true_statement = parse_statement();
4191         if(token.type == T_else) {
4192                 next_token();
4193                 statement->false_statement = parse_statement();
4194         }
4195
4196         return (statement_t*) statement;
4197 }
4198
4199 static statement_t *parse_switch(void)
4200 {
4201         eat(T_switch);
4202
4203         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4204         statement->statement.type            = STATEMENT_SWITCH;
4205         statement->statement.source_position = token.source_position;
4206
4207         expect('(');
4208         statement->expression = parse_expression();
4209         expect(')');
4210         statement->body = parse_statement();
4211
4212         return (statement_t*) statement;
4213 }
4214
4215 static statement_t *parse_while(void)
4216 {
4217         eat(T_while);
4218
4219         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4220         statement->statement.type            = STATEMENT_WHILE;
4221         statement->statement.source_position = token.source_position;
4222
4223         expect('(');
4224         statement->condition = parse_expression();
4225         expect(')');
4226         statement->body = parse_statement();
4227
4228         return (statement_t*) statement;
4229 }
4230
4231 static statement_t *parse_do(void)
4232 {
4233         eat(T_do);
4234
4235         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4236         statement->statement.type            = STATEMENT_DO_WHILE;
4237         statement->statement.source_position = token.source_position;
4238
4239         statement->body = parse_statement();
4240         expect(T_while);
4241         expect('(');
4242         statement->condition = parse_expression();
4243         expect(')');
4244         expect(';');
4245
4246         return (statement_t*) statement;
4247 }
4248
4249 static statement_t *parse_for(void)
4250 {
4251         eat(T_for);
4252
4253         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4254         statement->statement.type            = STATEMENT_FOR;
4255         statement->statement.source_position = token.source_position;
4256
4257         expect('(');
4258
4259         int         top          = environment_top();
4260         context_t  *last_context = context;
4261         set_context(&statement->context);
4262
4263         if(token.type != ';') {
4264                 if(is_declaration_specifier(&token, false)) {
4265                         parse_declaration();
4266                 } else {
4267                         statement->initialisation = parse_expression();
4268                         expect(';');
4269                 }
4270         } else {
4271                 expect(';');
4272         }
4273
4274         if(token.type != ';') {
4275                 statement->condition = parse_expression();
4276         }
4277         expect(';');
4278         if(token.type != ')') {
4279                 statement->step = parse_expression();
4280         }
4281         expect(')');
4282         statement->body = parse_statement();
4283
4284         assert(context == &statement->context);
4285         set_context(last_context);
4286         environment_pop_to(top);
4287
4288         return (statement_t*) statement;
4289 }
4290
4291 static statement_t *parse_goto(void)
4292 {
4293         eat(T_goto);
4294
4295         if(token.type != T_IDENTIFIER) {
4296                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4297                 eat_statement();
4298                 return NULL;
4299         }
4300         symbol_t *symbol = token.v.symbol;
4301         next_token();
4302
4303         declaration_t *label = get_label(symbol);
4304
4305         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4306
4307         statement->statement.type            = STATEMENT_GOTO;
4308         statement->statement.source_position = token.source_position;
4309
4310         statement->label = label;
4311
4312         expect(';');
4313
4314         return (statement_t*) statement;
4315 }
4316
4317 static statement_t *parse_continue(void)
4318 {
4319         eat(T_continue);
4320         expect(';');
4321
4322         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4323         statement->type                 = STATEMENT_CONTINUE;
4324         statement->base.source_position = token.source_position;
4325
4326         return statement;
4327 }
4328
4329 static statement_t *parse_break(void)
4330 {
4331         eat(T_break);
4332         expect(';');
4333
4334         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4335         statement->type                 = STATEMENT_BREAK;
4336         statement->base.source_position = token.source_position;
4337
4338         return statement;
4339 }
4340
4341 static statement_t *parse_return(void)
4342 {
4343         eat(T_return);
4344
4345         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4346
4347         statement->statement.type            = STATEMENT_RETURN;
4348         statement->statement.source_position = token.source_position;
4349
4350         assert(current_function->type->type == TYPE_FUNCTION);
4351         function_type_t *function_type = &current_function->type->function;
4352         type_t          *return_type   = function_type->result_type;
4353
4354         expression_t *return_value = NULL;
4355         if(token.type != ';') {
4356                 return_value = parse_expression();
4357         }
4358         expect(';');
4359
4360         if(return_type == NULL)
4361                 return (statement_t*) statement;
4362
4363         return_type = skip_typeref(return_type);
4364
4365         if(return_value != NULL) {
4366                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
4367
4368                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
4369                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
4370                         parse_warning("'return' with a value, in function returning void");
4371                         return_value = NULL;
4372                 } else {
4373                         if(return_type != NULL) {
4374                                 semantic_assign(return_type, &return_value, "'return'");
4375                         }
4376                 }
4377         } else {
4378                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
4379                         parse_warning("'return' without value, in function returning "
4380                                       "non-void");
4381                 }
4382         }
4383         statement->return_value = return_value;
4384
4385         return (statement_t*) statement;
4386 }
4387
4388 static statement_t *parse_declaration_statement(void)
4389 {
4390         declaration_t *before = last_declaration;
4391
4392         declaration_statement_t *statement
4393                 = allocate_ast_zero(sizeof(statement[0]));
4394         statement->statement.type            = STATEMENT_DECLARATION;
4395         statement->statement.source_position = token.source_position;
4396
4397         declaration_specifiers_t specifiers;
4398         memset(&specifiers, 0, sizeof(specifiers));
4399         parse_declaration_specifiers(&specifiers);
4400
4401         if(token.type == ';') {
4402                 eat(';');
4403         } else {
4404                 parse_init_declarators(&specifiers);
4405         }
4406
4407         if(before == NULL) {
4408                 statement->declarations_begin = context->declarations;
4409         } else {
4410                 statement->declarations_begin = before->next;
4411         }
4412         statement->declarations_end = last_declaration;
4413
4414         return (statement_t*) statement;
4415 }
4416
4417 static statement_t *parse_expression_statement(void)
4418 {
4419         expression_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4420         statement->statement.type            = STATEMENT_EXPRESSION;
4421         statement->statement.source_position = token.source_position;
4422
4423         statement->expression = parse_expression();
4424
4425         expect(';');
4426
4427         return (statement_t*) statement;
4428 }
4429
4430 static statement_t *parse_statement(void)
4431 {
4432         statement_t   *statement = NULL;
4433
4434         /* declaration or statement */
4435         switch(token.type) {
4436         case T_case:
4437                 statement = parse_case_statement();
4438                 break;
4439
4440         case T_default:
4441                 statement = parse_default_statement();
4442                 break;
4443
4444         case '{':
4445                 statement = parse_compound_statement();
4446                 break;
4447
4448         case T_if:
4449                 statement = parse_if();
4450                 break;
4451
4452         case T_switch:
4453                 statement = parse_switch();
4454                 break;
4455
4456         case T_while:
4457                 statement = parse_while();
4458                 break;
4459
4460         case T_do:
4461                 statement = parse_do();
4462                 break;
4463
4464         case T_for:
4465                 statement = parse_for();
4466                 break;
4467
4468         case T_goto:
4469                 statement = parse_goto();
4470                 break;
4471
4472         case T_continue:
4473                 statement = parse_continue();
4474                 break;
4475
4476         case T_break:
4477                 statement = parse_break();
4478                 break;
4479
4480         case T_return:
4481                 statement = parse_return();
4482                 break;
4483
4484         case ';':
4485                 next_token();
4486                 statement = NULL;
4487                 break;
4488
4489         case T_IDENTIFIER:
4490                 if(look_ahead(1)->type == ':') {
4491                         statement = parse_label_statement();
4492                         break;
4493                 }
4494
4495                 if(is_typedef_symbol(token.v.symbol)) {
4496                         statement = parse_declaration_statement();
4497                         break;
4498                 }
4499
4500                 statement = parse_expression_statement();
4501                 break;
4502
4503         case T___extension__:
4504                 /* this can be a prefix to a declaration or an expression statement */
4505                 /* we simply eat it now and parse the rest with tail recursion */
4506                 do {
4507                         next_token();
4508                 } while(token.type == T___extension__);
4509                 statement = parse_statement();
4510                 break;
4511
4512         DECLARATION_START
4513                 statement = parse_declaration_statement();
4514                 break;
4515
4516         default:
4517                 statement = parse_expression_statement();
4518                 break;
4519         }
4520
4521         assert(statement == NULL
4522                         || statement->base.source_position.input_name != NULL);
4523
4524         return statement;
4525 }
4526
4527 static statement_t *parse_compound_statement(void)
4528 {
4529         compound_statement_t *compound_statement
4530                 = allocate_ast_zero(sizeof(compound_statement[0]));
4531         compound_statement->statement.type            = STATEMENT_COMPOUND;
4532         compound_statement->statement.source_position = token.source_position;
4533
4534         eat('{');
4535
4536         int        top          = environment_top();
4537         context_t *last_context = context;
4538         set_context(&compound_statement->context);
4539
4540         statement_t *last_statement = NULL;
4541
4542         while(token.type != '}' && token.type != T_EOF) {
4543                 statement_t *statement = parse_statement();
4544                 if(statement == NULL)
4545                         continue;
4546
4547                 if(last_statement != NULL) {
4548                         last_statement->base.next = statement;
4549                 } else {
4550                         compound_statement->statements = statement;
4551                 }
4552
4553                 while(statement->base.next != NULL)
4554                         statement = statement->base.next;
4555
4556                 last_statement = statement;
4557         }
4558
4559         if(token.type != '}') {
4560                 parser_print_error_prefix_pos(
4561                                 compound_statement->statement.source_position);
4562                 fprintf(stderr, "end of file while looking for closing '}'\n");
4563         }
4564         next_token();
4565
4566         assert(context == &compound_statement->context);
4567         set_context(last_context);
4568         environment_pop_to(top);
4569
4570         return (statement_t*) compound_statement;
4571 }
4572
4573 static translation_unit_t *parse_translation_unit(void)
4574 {
4575         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
4576
4577         assert(global_context == NULL);
4578         global_context = &unit->context;
4579
4580         assert(context == NULL);
4581         set_context(&unit->context);
4582
4583         while(token.type != T_EOF) {
4584                 parse_declaration();
4585         }
4586
4587         assert(context == &unit->context);
4588         context          = NULL;
4589         last_declaration = NULL;
4590
4591         assert(global_context == &unit->context);
4592         global_context = NULL;
4593
4594         return unit;
4595 }
4596
4597 translation_unit_t *parse(void)
4598 {
4599         environment_stack = NEW_ARR_F(stack_entry_t, 0);
4600         label_stack       = NEW_ARR_F(stack_entry_t, 0);
4601         found_error       = false;
4602
4603         type_set_output(stderr);
4604         ast_set_output(stderr);
4605
4606         lookahead_bufpos = 0;
4607         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
4608                 next_token();
4609         }
4610         translation_unit_t *unit = parse_translation_unit();
4611
4612         DEL_ARR_F(environment_stack);
4613         DEL_ARR_F(label_stack);
4614
4615         if(found_error)
4616                 return NULL;
4617
4618         return unit;
4619 }
4620
4621 void init_parser(void)
4622 {
4623         init_expression_parsers();
4624         obstack_init(&temp_obst);
4625
4626         type_int         = make_atomic_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
4627         type_long_double = make_atomic_type(ATOMIC_TYPE_LONG_DOUBLE, TYPE_QUALIFIER_NONE);
4628         type_double      = make_atomic_type(ATOMIC_TYPE_DOUBLE, TYPE_QUALIFIER_NONE);
4629         type_float       = make_atomic_type(ATOMIC_TYPE_FLOAT, TYPE_QUALIFIER_NONE);
4630         type_size_t      = make_atomic_type(ATOMIC_TYPE_ULONG, TYPE_QUALIFIER_NONE);
4631         type_ptrdiff_t   = make_atomic_type(ATOMIC_TYPE_LONG, TYPE_QUALIFIER_NONE);
4632         type_char        = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_NONE);
4633         type_void        = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
4634         type_void_ptr    = make_pointer_type(type_void, TYPE_QUALIFIER_NONE);
4635         type_string      = make_pointer_type(type_char, TYPE_QUALIFIER_NONE);
4636 }
4637
4638 void exit_parser(void)
4639 {
4640         obstack_free(&temp_obst, NULL);
4641 }