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