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