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