Array as last part of a paramter type is just syntactic sugar. Turn it into a pointer.
[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         const declaration_t *const declaration =
1111                 get_declaration(symbol, NAMESPACE_NORMAL);
1112         return
1113                 declaration != NULL &&
1114                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1115 }
1116
1117 static type_t *parse_typeof(void)
1118 {
1119         eat(T___typeof__);
1120
1121         type_t *type;
1122
1123         expect('(');
1124
1125         expression_t *expression  = NULL;
1126
1127 restart:
1128         switch(token.type) {
1129         case T___extension__:
1130                 /* this can be a prefix to a typename or an expression */
1131                 /* we simply eat it now. */
1132                 do {
1133                         next_token();
1134                 } while(token.type == T___extension__);
1135                 goto restart;
1136
1137         case T_IDENTIFIER:
1138                 if(is_typedef_symbol(token.v.symbol)) {
1139                         type = parse_typename();
1140                 } else {
1141                         expression = parse_expression();
1142                         type       = expression->datatype;
1143                 }
1144                 break;
1145
1146         TYPENAME_START
1147                 type = parse_typename();
1148                 break;
1149
1150         default:
1151                 expression = parse_expression();
1152                 type       = expression->datatype;
1153                 break;
1154         }
1155
1156         expect(')');
1157
1158         typeof_type_t *typeof = allocate_type_zero(sizeof(typeof[0]));
1159         typeof->type.type     = TYPE_TYPEOF;
1160         typeof->expression    = expression;
1161         typeof->typeof_type   = type;
1162
1163         return (type_t*) typeof;
1164 }
1165
1166 typedef enum {
1167         SPECIFIER_SIGNED    = 1 << 0,
1168         SPECIFIER_UNSIGNED  = 1 << 1,
1169         SPECIFIER_LONG      = 1 << 2,
1170         SPECIFIER_INT       = 1 << 3,
1171         SPECIFIER_DOUBLE    = 1 << 4,
1172         SPECIFIER_CHAR      = 1 << 5,
1173         SPECIFIER_SHORT     = 1 << 6,
1174         SPECIFIER_LONG_LONG = 1 << 7,
1175         SPECIFIER_FLOAT     = 1 << 8,
1176         SPECIFIER_BOOL      = 1 << 9,
1177         SPECIFIER_VOID      = 1 << 10,
1178 #ifdef PROVIDE_COMPLEX
1179         SPECIFIER_COMPLEX   = 1 << 11,
1180 #endif
1181 #ifdef PROVIDE_IMAGINARY
1182         SPECIFIER_IMAGINARY = 1 << 12,
1183 #endif
1184 } specifiers_t;
1185
1186 static type_t *create_builtin_type(symbol_t *symbol)
1187 {
1188         builtin_type_t *type = allocate_type_zero(sizeof(type[0]));
1189         type->type.type      = TYPE_BUILTIN;
1190         type->symbol         = symbol;
1191         /* TODO... */
1192         type->real_type      = type_int;
1193
1194         return (type_t*) type;
1195 }
1196
1197 static type_t *get_typedef_type(symbol_t *symbol)
1198 {
1199         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1200         if(declaration == NULL
1201                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1202                 return NULL;
1203
1204         typedef_type_t *typedef_type = allocate_type_zero(sizeof(typedef_type[0]));
1205         typedef_type->type.type    = TYPE_TYPEDEF;
1206         typedef_type->declaration  = declaration;
1207
1208         return (type_t*) typedef_type;
1209 }
1210
1211 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1212 {
1213         type_t        *type            = NULL;
1214         unsigned       type_qualifiers = 0;
1215         unsigned       type_specifiers = 0;
1216         int            newtype         = 0;
1217
1218         while(true) {
1219                 switch(token.type) {
1220
1221                 /* storage class */
1222 #define MATCH_STORAGE_CLASS(token, class)                                \
1223                 case token:                                                      \
1224                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1225                                 parse_error("multiple storage classes in declaration "   \
1226                                             "specifiers");                               \
1227                         }                                                            \
1228                         specifiers->storage_class = class;                           \
1229                         next_token();                                                \
1230                         break;
1231
1232                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1233                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1234                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1235                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1236                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1237
1238                 /* type qualifiers */
1239 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1240                 case token:                                                     \
1241                         type_qualifiers |= qualifier;                               \
1242                         next_token();                                               \
1243                         break;
1244
1245                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1246                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1247                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1248
1249                 case T___extension__:
1250                         /* TODO */
1251                         next_token();
1252                         break;
1253
1254                 /* type specifiers */
1255 #define MATCH_SPECIFIER(token, specifier, name)                         \
1256                 case token:                                                     \
1257                         next_token();                                               \
1258                         if(type_specifiers & specifier) {                           \
1259                                 parse_error("multiple " name " type specifiers given"); \
1260                         } else {                                                    \
1261                                 type_specifiers |= specifier;                           \
1262                         }                                                           \
1263                         break;
1264
1265                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1266                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1267                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1268                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1269                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1270                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1271                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1272                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1273                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1274 #ifdef PROVIDE_COMPLEX
1275                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1276 #endif
1277 #ifdef PROVIDE_IMAGINARY
1278                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1279 #endif
1280                 case T_inline:
1281                         next_token();
1282                         specifiers->is_inline = true;
1283                         break;
1284
1285                 case T_long:
1286                         next_token();
1287                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1288                                 parse_error("multiple type specifiers given");
1289                         } else if(type_specifiers & SPECIFIER_LONG) {
1290                                 type_specifiers |= SPECIFIER_LONG_LONG;
1291                         } else {
1292                                 type_specifiers |= SPECIFIER_LONG;
1293                         }
1294                         break;
1295
1296                 /* TODO: if type != NULL for the following rules should issue
1297                  * an error */
1298                 case T_struct: {
1299                         compound_type_t *compound_type
1300                                 = allocate_type_zero(sizeof(compound_type[0]));
1301                         compound_type->type.type = TYPE_COMPOUND_STRUCT;
1302                         compound_type->declaration = parse_compound_type_specifier(true);
1303
1304                         type = (type_t*) compound_type;
1305                         break;
1306                 }
1307                 case T_union: {
1308                         compound_type_t *compound_type
1309                                 = allocate_type_zero(sizeof(compound_type[0]));
1310                         compound_type->type.type = TYPE_COMPOUND_UNION;
1311                         compound_type->declaration = parse_compound_type_specifier(false);
1312
1313                         type = (type_t*) compound_type;
1314                         break;
1315                 }
1316                 case T_enum: {
1317                         enum_type_t *enum_type = allocate_type_zero(sizeof(enum_type[0]));
1318                         enum_type->type.type   = TYPE_ENUM;
1319                         enum_type->declaration = parse_enum_specifier();
1320
1321                         type = (type_t*) enum_type;
1322                         break;
1323                 }
1324                 case T___typeof__:
1325                         type = parse_typeof();
1326                         break;
1327                 case T___builtin_va_list:
1328                         type = create_builtin_type(token.v.symbol);
1329                         next_token();
1330                         break;
1331
1332                 case T___attribute__:
1333                         /* TODO */
1334                         parse_attributes();
1335                         break;
1336
1337                 case T_IDENTIFIER: {
1338                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1339
1340                         if(typedef_type == NULL)
1341                                 goto finish_specifiers;
1342
1343                         next_token();
1344                         type = typedef_type;
1345                         break;
1346                 }
1347
1348                 /* function specifier */
1349                 default:
1350                         goto finish_specifiers;
1351                 }
1352         }
1353
1354 finish_specifiers:
1355
1356         if(type == NULL) {
1357                 atomic_type_type_t atomic_type;
1358
1359                 /* match valid basic types */
1360                 switch(type_specifiers) {
1361                 case SPECIFIER_VOID:
1362                         atomic_type = ATOMIC_TYPE_VOID;
1363                         break;
1364                 case SPECIFIER_CHAR:
1365                         atomic_type = ATOMIC_TYPE_CHAR;
1366                         break;
1367                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1368                         atomic_type = ATOMIC_TYPE_SCHAR;
1369                         break;
1370                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1371                         atomic_type = ATOMIC_TYPE_UCHAR;
1372                         break;
1373                 case SPECIFIER_SHORT:
1374                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1375                 case SPECIFIER_SHORT | SPECIFIER_INT:
1376                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1377                         atomic_type = ATOMIC_TYPE_SHORT;
1378                         break;
1379                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1380                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1381                         atomic_type = ATOMIC_TYPE_USHORT;
1382                         break;
1383                 case SPECIFIER_INT:
1384                 case SPECIFIER_SIGNED:
1385                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1386                         atomic_type = ATOMIC_TYPE_INT;
1387                         break;
1388                 case SPECIFIER_UNSIGNED:
1389                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1390                         atomic_type = ATOMIC_TYPE_UINT;
1391                         break;
1392                 case SPECIFIER_LONG:
1393                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1394                 case SPECIFIER_LONG | SPECIFIER_INT:
1395                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1396                         atomic_type = ATOMIC_TYPE_LONG;
1397                         break;
1398                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1399                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1400                         atomic_type = ATOMIC_TYPE_ULONG;
1401                         break;
1402                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1403                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1404                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1405                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1406                         | SPECIFIER_INT:
1407                         atomic_type = ATOMIC_TYPE_LONGLONG;
1408                         break;
1409                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1410                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1411                         | SPECIFIER_INT:
1412                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1413                         break;
1414                 case SPECIFIER_FLOAT:
1415                         atomic_type = ATOMIC_TYPE_FLOAT;
1416                         break;
1417                 case SPECIFIER_DOUBLE:
1418                         atomic_type = ATOMIC_TYPE_DOUBLE;
1419                         break;
1420                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1421                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1422                         break;
1423                 case SPECIFIER_BOOL:
1424                         atomic_type = ATOMIC_TYPE_BOOL;
1425                         break;
1426 #ifdef PROVIDE_COMPLEX
1427                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1428                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1429                         break;
1430                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1431                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1432                         break;
1433                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1434                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1435                         break;
1436 #endif
1437 #ifdef PROVIDE_IMAGINARY
1438                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1439                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1440                         break;
1441                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1442                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1443                         break;
1444                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1445                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1446                         break;
1447 #endif
1448                 default:
1449                         /* invalid specifier combination, give an error message */
1450                         if(type_specifiers == 0) {
1451 #ifndef STRICT_C99
1452                                 parse_warning("no type specifiers in declaration (using int)");
1453                                 atomic_type = ATOMIC_TYPE_INT;
1454                                 break;
1455 #else
1456                                 parse_error("no type specifiers given in declaration");
1457 #endif
1458                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
1459                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
1460                                 parse_error("signed and unsigned specifiers gives");
1461                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
1462                                 parse_error("only integer types can be signed or unsigned");
1463                         } else {
1464                                 parse_error("multiple datatypes in declaration");
1465                         }
1466                         atomic_type = ATOMIC_TYPE_INVALID;
1467                 }
1468
1469                 atomic_type_t *atype = allocate_type_zero(sizeof(atype[0]));
1470                 atype->type.type     = TYPE_ATOMIC;
1471                 atype->atype         = atomic_type;
1472                 newtype              = 1;
1473
1474                 type = (type_t*) atype;
1475         } else {
1476                 if(type_specifiers != 0) {
1477                         parse_error("multiple datatypes in declaration");
1478                 }
1479         }
1480
1481         type->qualifiers = (type_qualifier_t)type_qualifiers;
1482
1483         type_t *result = typehash_insert(type);
1484         if(newtype && result != (type_t*) type) {
1485                 free_type(type);
1486         }
1487
1488         specifiers->type = result;
1489 }
1490
1491 static unsigned parse_type_qualifiers(void)
1492 {
1493         unsigned type_qualifiers = TYPE_QUALIFIER_NONE;
1494
1495         while(true) {
1496                 switch(token.type) {
1497                 /* type qualifiers */
1498                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1499                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1500                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1501
1502                 default:
1503                         return type_qualifiers;
1504                 }
1505         }
1506 }
1507
1508 static void parse_identifier_list(void)
1509 {
1510         while(true) {
1511                 if(token.type != T_IDENTIFIER) {
1512                         parse_error_expected("while parsing parameter identifier list",
1513                                              T_IDENTIFIER, 0);
1514                         return;
1515                 }
1516                 next_token();
1517                 if(token.type != ',')
1518                         break;
1519                 next_token();
1520         }
1521 }
1522
1523 static declaration_t *parse_parameter(void)
1524 {
1525         declaration_specifiers_t specifiers;
1526         memset(&specifiers, 0, sizeof(specifiers));
1527
1528         parse_declaration_specifiers(&specifiers);
1529
1530         declaration_t *declaration
1531                 = parse_declarator(&specifiers, specifiers.type, true);
1532
1533         /* TODO check declaration constraints for parameters */
1534         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
1535                 parse_error("typedef not allowed in parameter list");
1536         }
1537
1538         /* Array as last part of a paramter type is just syntactic sugar.  Turn it
1539          * into a pointer */
1540         if (declaration->type->type == TYPE_ARRAY) {
1541                 const array_type_t *const arr_type =
1542                         (const array_type_t*)declaration->type;
1543                 declaration->type =
1544                         make_pointer_type(arr_type->element_type, TYPE_QUALIFIER_NONE);
1545         }
1546
1547         return declaration;
1548 }
1549
1550 static declaration_t *parse_parameters(function_type_t *type)
1551 {
1552         if(token.type == T_IDENTIFIER) {
1553                 symbol_t      *symbol = token.v.symbol;
1554                 if(!is_typedef_symbol(symbol)) {
1555                         /* TODO */
1556                         parse_identifier_list();
1557                         return NULL;
1558                 }
1559         }
1560
1561         if(token.type == ')') {
1562                 type->unspecified_parameters = 1;
1563                 return NULL;
1564         }
1565         if(token.type == T_void && look_ahead(1)->type == ')') {
1566                 next_token();
1567                 return NULL;
1568         }
1569
1570         declaration_t        *declarations = NULL;
1571         declaration_t        *declaration;
1572         declaration_t        *last_declaration = NULL;
1573         function_parameter_t *parameter;
1574         function_parameter_t *last_parameter = NULL;
1575
1576         while(true) {
1577                 switch(token.type) {
1578                 case T_DOTDOTDOT:
1579                         next_token();
1580                         type->variadic = 1;
1581                         return declarations;
1582
1583                 case T_IDENTIFIER:
1584                 case T___extension__:
1585                 DECLARATION_START
1586                         declaration = parse_parameter();
1587
1588                         parameter       = allocate_type_zero(sizeof(parameter[0]));
1589                         parameter->type = declaration->type;
1590
1591                         if(last_parameter != NULL) {
1592                                 last_declaration->next = declaration;
1593                                 last_parameter->next   = parameter;
1594                         } else {
1595                                 type->parameters = parameter;
1596                                 declarations     = declaration;
1597                         }
1598                         last_parameter   = parameter;
1599                         last_declaration = declaration;
1600                         break;
1601
1602                 default:
1603                         return declarations;
1604                 }
1605                 if(token.type != ',')
1606                         return declarations;
1607                 next_token();
1608         }
1609 }
1610
1611 typedef enum {
1612         CONSTRUCT_INVALID,
1613         CONSTRUCT_POINTER,
1614         CONSTRUCT_FUNCTION,
1615         CONSTRUCT_ARRAY
1616 } construct_type_type_t;
1617
1618 typedef struct construct_type_t construct_type_t;
1619 struct construct_type_t {
1620         construct_type_type_t  type;
1621         construct_type_t      *next;
1622 };
1623
1624 typedef struct parsed_pointer_t parsed_pointer_t;
1625 struct parsed_pointer_t {
1626         construct_type_t  construct_type;
1627         type_qualifier_t  type_qualifiers;
1628 };
1629
1630 typedef struct construct_function_type_t construct_function_type_t;
1631 struct construct_function_type_t {
1632         construct_type_t    construct_type;
1633         function_type_t    *function_type;
1634 };
1635
1636 typedef struct parsed_array_t parsed_array_t;
1637 struct parsed_array_t {
1638         construct_type_t  construct_type;
1639         type_qualifier_t  type_qualifiers;
1640         bool              is_static;
1641         bool              is_variable;
1642         expression_t     *size;
1643 };
1644
1645 typedef struct construct_base_type_t construct_base_type_t;
1646 struct construct_base_type_t {
1647         construct_type_t  construct_type;
1648         type_t           *type;
1649 };
1650
1651 static construct_type_t *parse_pointer_declarator(void)
1652 {
1653         eat('*');
1654
1655         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
1656         memset(pointer, 0, sizeof(pointer[0]));
1657         pointer->construct_type.type = CONSTRUCT_POINTER;
1658         pointer->type_qualifiers     = parse_type_qualifiers();
1659
1660         return (construct_type_t*) pointer;
1661 }
1662
1663 static construct_type_t *parse_array_declarator(void)
1664 {
1665         eat('[');
1666
1667         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
1668         memset(array, 0, sizeof(array[0]));
1669         array->construct_type.type = CONSTRUCT_ARRAY;
1670
1671         if(token.type == T_static) {
1672                 array->is_static = true;
1673                 next_token();
1674         }
1675
1676         type_qualifier_t type_qualifiers = parse_type_qualifiers();
1677         if(type_qualifiers != 0) {
1678                 if(token.type == T_static) {
1679                         array->is_static = true;
1680                         next_token();
1681                 }
1682         }
1683         array->type_qualifiers = type_qualifiers;
1684
1685         if(token.type == '*' && look_ahead(1)->type == ']') {
1686                 array->is_variable = true;
1687                 next_token();
1688         } else if(token.type != ']') {
1689                 array->size = parse_assignment_expression();
1690         }
1691
1692         expect(']');
1693
1694         return (construct_type_t*) array;
1695 }
1696
1697 static construct_type_t *parse_function_declarator(declaration_t *declaration)
1698 {
1699         eat('(');
1700
1701         function_type_t *type = allocate_type_zero(sizeof(type[0]));
1702         type->type.type       = TYPE_FUNCTION;
1703
1704         declaration_t *parameters = parse_parameters(type);
1705         if(declaration != NULL) {
1706                 declaration->context.declarations = parameters;
1707         }
1708
1709         construct_function_type_t *construct_function_type =
1710                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
1711         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
1712         construct_function_type->construct_type.type = CONSTRUCT_FUNCTION;
1713         construct_function_type->function_type       = type;
1714
1715         expect(')');
1716
1717         return (construct_type_t*) construct_function_type;
1718 }
1719
1720 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
1721                 int may_be_abstract)
1722 {
1723         construct_type_t *result = NULL;
1724         construct_type_t *last   = NULL;
1725
1726         while(token.type == '*') {
1727                 construct_type_t *type = parse_pointer_declarator();
1728                 if(last != NULL) {
1729                         last->next = type;
1730                 } else {
1731                         result = type;
1732                 }
1733                 last = type;
1734         }
1735
1736         /* TODO: find out if this is correct */
1737         parse_attributes();
1738
1739         construct_type_t *inner_types = NULL;
1740
1741         switch(token.type) {
1742         case T_IDENTIFIER:
1743                 if(declaration == NULL) {
1744                         parse_error("no identifier expected in typename");
1745                 } else {
1746                         declaration->symbol          = token.v.symbol;
1747                         declaration->source_position = token.source_position;
1748                 }
1749                 next_token();
1750                 break;
1751         case '(':
1752                 next_token();
1753                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
1754                 expect(')');
1755                 break;
1756         default:
1757                 if(may_be_abstract)
1758                         break;
1759                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
1760         }
1761
1762         while(true) {
1763                 construct_type_t *type;
1764                 switch(token.type) {
1765                 case '(':
1766                         type = parse_function_declarator(declaration);
1767                         break;
1768                 case '[':
1769                         type = parse_array_declarator();
1770                         break;
1771                 default:
1772                         goto declarator_finished;
1773                 }
1774
1775                 if(last != NULL) {
1776                         last->next = type;
1777                 } else {
1778                         result = type;
1779                 }
1780                 last = type;
1781         }
1782
1783 declarator_finished:
1784         parse_attributes();
1785
1786         if(inner_types != NULL) {
1787                 if(last != NULL) {
1788                         last->next = inner_types;
1789                 } else {
1790                         result = inner_types;
1791                 }
1792                 last = inner_types;
1793         }
1794
1795         return result;
1796 }
1797
1798 static type_t *construct_declarator_type(construct_type_t *construct_list,
1799                                          type_t *type)
1800 {
1801         construct_type_t *iter = construct_list;
1802         for( ; iter != NULL; iter = iter->next) {
1803                 parsed_pointer_t          *parsed_pointer;
1804                 parsed_array_t            *parsed_array;
1805                 construct_function_type_t *construct_function_type;
1806                 function_type_t           *function_type;
1807                 pointer_type_t            *pointer_type;
1808                 array_type_t              *array_type;
1809
1810                 switch(iter->type) {
1811                 case CONSTRUCT_INVALID:
1812                         panic("invalid type construction found");
1813                 case CONSTRUCT_FUNCTION:
1814                         construct_function_type = (construct_function_type_t*) iter;
1815                         function_type           = construct_function_type->function_type;
1816
1817                         function_type->result_type = type;
1818                         type                       = (type_t*) function_type;
1819                         break;
1820
1821                 case CONSTRUCT_POINTER:
1822                         parsed_pointer = (parsed_pointer_t*) iter;
1823                         pointer_type   = allocate_type_zero(sizeof(pointer_type[0]));
1824
1825                         pointer_type->type.type       = TYPE_POINTER;
1826                         pointer_type->points_to       = type;
1827                         pointer_type->type.qualifiers = parsed_pointer->type_qualifiers;
1828                         type                          = (type_t*) pointer_type;
1829                         break;
1830
1831                 case CONSTRUCT_ARRAY:
1832                         parsed_array  = (parsed_array_t*) iter;
1833                         array_type    = allocate_type_zero(sizeof(array_type[0]));
1834
1835                         array_type->type.type       = TYPE_ARRAY;
1836                         array_type->element_type    = type;
1837                         array_type->type.qualifiers = parsed_array->type_qualifiers;
1838                         array_type->is_static       = parsed_array->is_static;
1839                         array_type->is_variable     = parsed_array->is_variable;
1840                         array_type->size            = parsed_array->size;
1841                         type                        = (type_t*) array_type;
1842                         break;
1843                 }
1844
1845                 type_t *hashed_type = typehash_insert((type_t*) type);
1846                 if(hashed_type != type) {
1847                         free_type(type);
1848                         type = hashed_type;
1849                 }
1850         }
1851
1852         return type;
1853 }
1854
1855 static declaration_t *parse_declarator(
1856                 const declaration_specifiers_t *specifiers,
1857                 type_t *type, bool may_be_abstract)
1858 {
1859         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
1860         declaration->storage_class = specifiers->storage_class;
1861         declaration->is_inline     = specifiers->is_inline;
1862
1863         construct_type_t *construct_type
1864                 = parse_inner_declarator(declaration, may_be_abstract);
1865         declaration->type = construct_declarator_type(construct_type, type);
1866
1867         if(construct_type != NULL) {
1868                 obstack_free(&temp_obst, construct_type);
1869         }
1870
1871         return declaration;
1872 }
1873
1874 static type_t *parse_abstract_declarator(type_t *base_type)
1875 {
1876         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
1877
1878         type_t *result = construct_declarator_type(construct_type, base_type);
1879         if(construct_type != NULL) {
1880                 obstack_free(&temp_obst, construct_type);
1881         }
1882
1883         return result;
1884 }
1885
1886 static declaration_t *record_declaration(declaration_t *declaration)
1887 {
1888         assert(context != NULL);
1889
1890         symbol_t *symbol = declaration->symbol;
1891         if(symbol != NULL) {
1892                 declaration_t *alias = environment_push(declaration);
1893                 if(alias != declaration)
1894                         return alias;
1895         } else {
1896                 declaration->parent_context = context;
1897         }
1898
1899         if(last_declaration != NULL) {
1900                 last_declaration->next = declaration;
1901         } else {
1902                 context->declarations = declaration;
1903         }
1904         last_declaration = declaration;
1905
1906         return declaration;
1907 }
1908
1909 static void parser_error_multiple_definition(declaration_t *previous,
1910                                              declaration_t *declaration)
1911 {
1912         parser_print_error_prefix_pos(declaration->source_position);
1913         fprintf(stderr, "multiple definition of symbol '%s'\n",
1914                 declaration->symbol->string);
1915         parser_print_error_prefix_pos(previous->source_position);
1916         fprintf(stderr, "this is the location of the previous "
1917                 "definition.\n");
1918 }
1919
1920 static void parse_init_declarators(const declaration_specifiers_t *specifiers)
1921 {
1922         while(true) {
1923                 declaration_t *ndeclaration
1924                         = parse_declarator(specifiers, specifiers->type, false);
1925
1926                 declaration_t *declaration = record_declaration(ndeclaration);
1927
1928                 type_t *type = declaration->type;
1929                 if(type->type != TYPE_FUNCTION && declaration->is_inline) {
1930                         parser_print_warning_prefix_pos(declaration->source_position);
1931                         fprintf(stderr, "variable â€˜%s’ declared â€˜inline’\n",
1932                                 declaration->symbol->string);
1933                 }
1934
1935                 if(token.type == '=') {
1936                         next_token();
1937
1938                         /* TODO: check that this is an allowed type (no function type) */
1939
1940                         if(declaration->init.initializer != NULL) {
1941                                 parser_error_multiple_definition(declaration, ndeclaration);
1942                         }
1943
1944                         ndeclaration->init.initializer = parse_initializer(declaration->type);
1945                 } else if(token.type == '{') {
1946                         if(declaration->type->type != TYPE_FUNCTION) {
1947                                 parser_print_error_prefix();
1948                                 fprintf(stderr, "Declarator ");
1949                                 print_type_ext(declaration->type, declaration->symbol, NULL);
1950                                 fprintf(stderr, " has a body but is not a function type.\n");
1951                                 eat_block();
1952                                 continue;
1953                         }
1954
1955                         if(declaration->init.statement != NULL) {
1956                                 parser_error_multiple_definition(declaration, ndeclaration);
1957                         }
1958                         if(ndeclaration != declaration) {
1959                                 memcpy(&declaration->context, &ndeclaration->context,
1960                                        sizeof(declaration->context));
1961                         }
1962
1963                         int         top          = environment_top();
1964                         context_t  *last_context = context;
1965                         set_context(&declaration->context);
1966
1967                         /* push function parameters */
1968                         declaration_t *parameter = declaration->context.declarations;
1969                         for( ; parameter != NULL; parameter = parameter->next) {
1970                                 environment_push(parameter);
1971                         }
1972
1973                         int            label_stack_top      = label_top();
1974                         declaration_t *old_current_function = current_function;
1975                         current_function                    = declaration;
1976
1977                         statement_t *statement = parse_compound_statement();
1978
1979                         assert(current_function == declaration);
1980                         current_function = old_current_function;
1981                         label_pop_to(label_stack_top);
1982
1983                         assert(context == &declaration->context);
1984                         set_context(last_context);
1985                         environment_pop_to(top);
1986
1987                         declaration->init.statement = statement;
1988                         return;
1989                 }
1990
1991                 if(token.type != ',')
1992                         break;
1993                 next_token();
1994         }
1995         expect_void(';');
1996 }
1997
1998 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
1999 {
2000         while(1) {
2001                 if(token.type == ':') {
2002                         next_token();
2003                         parse_constant_expression();
2004                         /* TODO (bitfields) */
2005                 } else {
2006                         declaration_t *declaration
2007                                 = parse_declarator(specifiers, specifiers->type, true);
2008
2009                         /* TODO: check constraints for struct declarations */
2010                         /* TODO: check for doubled fields */
2011                         record_declaration(declaration);
2012
2013                         if(token.type == ':') {
2014                                 next_token();
2015                                 parse_constant_expression();
2016                                 /* TODO (bitfields) */
2017                         }
2018                 }
2019
2020                 if(token.type != ',')
2021                         break;
2022                 next_token();
2023         }
2024         expect_void(';');
2025 }
2026
2027 static void parse_compound_type_entries(void)
2028 {
2029         eat('{');
2030
2031         while(token.type != '}' && token.type != T_EOF) {
2032                 declaration_specifiers_t specifiers;
2033                 memset(&specifiers, 0, sizeof(specifiers));
2034                 parse_declaration_specifiers(&specifiers);
2035
2036                 parse_struct_declarators(&specifiers);
2037         }
2038         if(token.type == T_EOF) {
2039                 parse_error("unexpected error while parsing struct");
2040         }
2041         next_token();
2042 }
2043
2044 static void parse_declaration(void)
2045 {
2046         source_position_t source_position = token.source_position;
2047
2048         declaration_specifiers_t specifiers;
2049         memset(&specifiers, 0, sizeof(specifiers));
2050         parse_declaration_specifiers(&specifiers);
2051
2052         if(token.type == ';') {
2053                 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
2054                         parse_warning_pos(source_position,
2055                                           "useless keyword in empty declaration");
2056                 }
2057                 switch (specifiers.type->type) {
2058                         case TYPE_COMPOUND_STRUCT:
2059                         case TYPE_COMPOUND_UNION: {
2060                                 const compound_type_t *const comp_type =
2061                                         (const compound_type_t*)specifiers.type;
2062                                 if (comp_type->declaration->symbol == NULL) {
2063                                         parse_warning_pos(source_position,
2064                                                                                                                 "unnamed struct/union that defines no instances");
2065                                 }
2066                                 break;
2067                         }
2068
2069                         case TYPE_ENUM: break;
2070
2071                         default:
2072                                 parse_warning_pos(source_position, "empty declaration");
2073                                 break;
2074                 }
2075
2076                 next_token();
2077
2078                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2079
2080                 declaration->type            = specifiers.type;
2081                 declaration->storage_class   = specifiers.storage_class;
2082                 declaration->source_position = source_position;
2083                 record_declaration(declaration);
2084                 return;
2085         }
2086         parse_init_declarators(&specifiers);
2087 }
2088
2089 static type_t *parse_typename(void)
2090 {
2091         declaration_specifiers_t specifiers;
2092         memset(&specifiers, 0, sizeof(specifiers));
2093         parse_declaration_specifiers(&specifiers);
2094         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2095                 /* TODO: improve error message, user does probably not know what a
2096                  * storage class is...
2097                  */
2098                 parse_error("typename may not have a storage class");
2099         }
2100
2101         type_t *result = parse_abstract_declarator(specifiers.type);
2102
2103         return result;
2104 }
2105
2106
2107
2108
2109 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2110 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2111                                                           expression_t *left);
2112
2113 typedef struct expression_parser_function_t expression_parser_function_t;
2114 struct expression_parser_function_t {
2115         unsigned                         precedence;
2116         parse_expression_function        parser;
2117         unsigned                         infix_precedence;
2118         parse_expression_infix_function  infix_parser;
2119 };
2120
2121 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2122
2123 static expression_t *make_invalid_expression(void)
2124 {
2125         expression_t *expression    = allocate_ast_zero(sizeof(expression[0]));
2126         expression->type            = EXPR_INVALID;
2127         expression->source_position = token.source_position;
2128         return expression;
2129 }
2130
2131 static expression_t *expected_expression_error(void)
2132 {
2133         parser_print_error_prefix();
2134         fprintf(stderr, "expected expression, got token ");
2135         print_token(stderr, & token);
2136         fprintf(stderr, "\n");
2137
2138         next_token();
2139
2140         return make_invalid_expression();
2141 }
2142
2143 static expression_t *parse_string_const(void)
2144 {
2145         string_literal_t *cnst = allocate_ast_zero(sizeof(cnst[0]));
2146
2147         cnst->expression.type     = EXPR_STRING_LITERAL;
2148         cnst->expression.datatype = type_string;
2149         cnst->value               = parse_string_literals();
2150
2151         return (expression_t*) cnst;
2152 }
2153
2154 static expression_t *parse_int_const(void)
2155 {
2156         const_t *cnst = allocate_ast_zero(sizeof(cnst[0]));
2157
2158         cnst->expression.type     = EXPR_CONST;
2159         cnst->expression.datatype = type_int;
2160         cnst->v.int_value         = token.v.intvalue;
2161
2162         next_token();
2163
2164         return (expression_t*) cnst;
2165 }
2166
2167 static expression_t *parse_float_const(void)
2168 {
2169         const_t *cnst = allocate_ast_zero(sizeof(cnst[0]));
2170
2171         cnst->expression.type     = EXPR_CONST;
2172         cnst->expression.datatype = type_double;
2173         cnst->v.float_value       = token.v.floatvalue;
2174
2175         next_token();
2176
2177         return (expression_t*) cnst;
2178 }
2179
2180 static declaration_t *create_implicit_function(symbol_t *symbol,
2181                 const source_position_t source_position)
2182 {
2183         function_type_t *function_type
2184                 = allocate_type_zero(sizeof(function_type[0]));
2185
2186         function_type->type.type              = TYPE_FUNCTION;
2187         function_type->result_type            = type_int;
2188         function_type->unspecified_parameters = true;
2189
2190         type_t *type = typehash_insert((type_t*) function_type);
2191         if(type != (type_t*) function_type) {
2192                 free_type(function_type);
2193         }
2194
2195         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2196
2197         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2198         declaration->type            = type;
2199         declaration->symbol          = symbol;
2200         declaration->source_position = source_position;
2201
2202         /* prepend the implicit definition to the global context
2203          * this is safe since the symbol wasn't declared as anything else yet
2204          */
2205         assert(symbol->declaration == NULL);
2206
2207         context_t *last_context = context;
2208         context = global_context;
2209
2210         environment_push(declaration);
2211         declaration->next     = context->declarations;
2212         context->declarations = declaration;
2213
2214         context = last_context;
2215
2216         return declaration;
2217 }
2218
2219 static expression_t *parse_reference(void)
2220 {
2221         reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0]));
2222
2223         ref->expression.type = EXPR_REFERENCE;
2224         ref->symbol          = token.v.symbol;
2225
2226         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
2227
2228         source_position_t source_position = token.source_position;
2229         next_token();
2230
2231         if(declaration == NULL) {
2232 #ifndef STRICT_C99
2233                 /* an implicitly defined function */
2234                 if(token.type == '(') {
2235                         parser_print_prefix_pos(token.source_position);
2236                         fprintf(stderr, "warning: implicit declaration of function '%s'\n",
2237                                 ref->symbol->string);
2238
2239                         declaration = create_implicit_function(ref->symbol,
2240                                                                source_position);
2241                 } else
2242 #endif
2243                 {
2244                         parser_print_error_prefix();
2245                         fprintf(stderr, "unknown symbol '%s' found.\n", ref->symbol->string);
2246                         return (expression_t*) ref;
2247                 }
2248         }
2249
2250         ref->declaration         = declaration;
2251         ref->expression.datatype = declaration->type;
2252
2253         return (expression_t*) ref;
2254 }
2255
2256 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
2257 {
2258         (void) expression;
2259         (void) dest_type;
2260         /* TODO check if explicit cast is allowed and issue warnings/errors */
2261 }
2262
2263 static expression_t *parse_cast(void)
2264 {
2265         unary_expression_t *cast = allocate_ast_zero(sizeof(cast[0]));
2266
2267         cast->expression.type            = EXPR_UNARY;
2268         cast->type                       = UNEXPR_CAST;
2269         cast->expression.source_position = token.source_position;
2270
2271         type_t *type  = parse_typename();
2272
2273         expect(')');
2274         expression_t *value = parse_sub_expression(20);
2275
2276         check_cast_allowed(value, type);
2277
2278         cast->expression.datatype = type;
2279         cast->value               = value;
2280
2281         return (expression_t*) cast;
2282 }
2283
2284 static expression_t *parse_statement_expression(void)
2285 {
2286         statement_expression_t *expression
2287                 = allocate_ast_zero(sizeof(expression[0]));
2288         expression->expression.type = EXPR_STATEMENT;
2289
2290         statement_t *statement = parse_compound_statement();
2291         expression->statement  = statement;
2292         if(statement == NULL) {
2293                 expect(')');
2294                 return NULL;
2295         }
2296
2297         assert(statement->type == STATEMENT_COMPOUND);
2298         compound_statement_t *compound_statement
2299                 = (compound_statement_t*) statement;
2300
2301         /* find last statement and use it's type */
2302         const statement_t *last_statement = NULL;
2303         const statement_t *iter           = compound_statement->statements;
2304         for( ; iter != NULL; iter = iter->next) {
2305                 last_statement = iter;
2306         }
2307
2308         if(last_statement->type == STATEMENT_EXPRESSION) {
2309                 const expression_statement_t *expression_statement =
2310                         (const expression_statement_t*) last_statement;
2311                 expression->expression.datatype
2312                         = expression_statement->expression->datatype;
2313         } else {
2314                 expression->expression.datatype = type_void;
2315         }
2316
2317         expect(')');
2318
2319         return (expression_t*) expression;
2320 }
2321
2322 static expression_t *parse_brace_expression(void)
2323 {
2324         eat('(');
2325
2326         switch(token.type) {
2327         case '{':
2328                 /* gcc extension: a stement expression */
2329                 return parse_statement_expression();
2330
2331         TYPE_QUALIFIERS
2332         TYPE_SPECIFIERS
2333                 return parse_cast();
2334         case T_IDENTIFIER:
2335                 if(is_typedef_symbol(token.v.symbol)) {
2336                         return parse_cast();
2337                 }
2338         }
2339
2340         expression_t *result = parse_expression();
2341         expect(')');
2342
2343         return result;
2344 }
2345
2346 static expression_t *parse_function_keyword(void)
2347 {
2348         eat(T___FUNCTION__);
2349         /* TODO */
2350
2351         string_literal_t *expression = allocate_ast_zero(sizeof(expression[0]));
2352         expression->expression.type     = EXPR_FUNCTION;
2353         expression->expression.datatype = type_string;
2354         expression->value               = "TODO: FUNCTION";
2355
2356         return (expression_t*) expression;
2357 }
2358
2359 static expression_t *parse_pretty_function_keyword(void)
2360 {
2361         eat(T___PRETTY_FUNCTION__);
2362         /* TODO */
2363
2364         string_literal_t *expression = allocate_ast_zero(sizeof(expression[0]));
2365         expression->expression.type     = EXPR_PRETTY_FUNCTION;
2366         expression->expression.datatype = type_string;
2367         expression->value               = "TODO: PRETTY FUNCTION";
2368
2369         return (expression_t*) expression;
2370 }
2371
2372 static designator_t *parse_designator(void)
2373 {
2374         designator_t *result = allocate_ast_zero(sizeof(result[0]));
2375
2376         if(token.type != T_IDENTIFIER) {
2377                 parse_error_expected("while parsing member designator",
2378                                      T_IDENTIFIER, 0);
2379                 eat_brace();
2380                 return NULL;
2381         }
2382         result->symbol = token.v.symbol;
2383         next_token();
2384
2385         designator_t *last_designator = result;
2386         while(true) {
2387                 if(token.type == '.') {
2388                         next_token();
2389                         if(token.type != T_IDENTIFIER) {
2390                                 parse_error_expected("while parsing member designator",
2391                                                      T_IDENTIFIER, 0);
2392                                 eat_brace();
2393                                 return NULL;
2394                         }
2395                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2396                         designator->symbol       = token.v.symbol;
2397                         next_token();
2398
2399                         last_designator->next = designator;
2400                         last_designator       = designator;
2401                         continue;
2402                 }
2403                 if(token.type == '[') {
2404                         next_token();
2405                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2406                         designator->array_access = parse_expression();
2407                         if(designator->array_access == NULL) {
2408                                 eat_brace();
2409                                 return NULL;
2410                         }
2411                         expect(']');
2412
2413                         last_designator->next = designator;
2414                         last_designator       = designator;
2415                         continue;
2416                 }
2417                 break;
2418         }
2419
2420         return result;
2421 }
2422
2423 static expression_t *parse_offsetof(void)
2424 {
2425         eat(T___builtin_offsetof);
2426
2427         offsetof_expression_t *expression
2428                 = allocate_ast_zero(sizeof(expression[0]));
2429         expression->expression.type     = EXPR_OFFSETOF;
2430         expression->expression.datatype = type_size_t;
2431
2432         expect('(');
2433         expression->type = parse_typename();
2434         expect(',');
2435         expression->designator = parse_designator();
2436         expect(')');
2437
2438         return (expression_t*) expression;
2439 }
2440
2441 static expression_t *parse_va_arg(void)
2442 {
2443         eat(T___builtin_va_arg);
2444
2445         va_arg_expression_t *expression = allocate_ast_zero(sizeof(expression[0]));
2446         expression->expression.type     = EXPR_VA_ARG;
2447
2448         expect('(');
2449         expression->arg = parse_assignment_expression();
2450         expect(',');
2451         expression->expression.datatype = parse_typename();
2452         expect(')');
2453
2454         return (expression_t*) expression;
2455 }
2456
2457 static expression_t *parse_builtin_symbol(void)
2458 {
2459         builtin_symbol_expression_t *expression
2460                 = allocate_ast_zero(sizeof(expression[0]));
2461         expression->expression.type = EXPR_BUILTIN_SYMBOL;
2462
2463         /* TODO: set datatype */
2464
2465         expression->symbol = token.v.symbol;
2466
2467         next_token();
2468
2469         return (expression_t*) expression;
2470 }
2471
2472 static expression_t *parse_primary_expression(void)
2473 {
2474         switch(token.type) {
2475         case T_INTEGER:
2476                 return parse_int_const();
2477         case T_FLOATINGPOINT:
2478                 return parse_float_const();
2479         case T_STRING_LITERAL:
2480                 return parse_string_const();
2481         case T_IDENTIFIER:
2482                 return parse_reference();
2483         case T___FUNCTION__:
2484                 return parse_function_keyword();
2485         case T___PRETTY_FUNCTION__:
2486                 return parse_pretty_function_keyword();
2487         case T___builtin_offsetof:
2488                 return parse_offsetof();
2489         case T___builtin_va_arg:
2490                 return parse_va_arg();
2491         case T___builtin_expect:
2492         case T___builtin_va_start:
2493         case T___builtin_va_end:
2494                 return parse_builtin_symbol();
2495
2496         case '(':
2497                 return parse_brace_expression();
2498         }
2499
2500         parser_print_error_prefix();
2501         fprintf(stderr, "unexpected token ");
2502         print_token(stderr, &token);
2503         fprintf(stderr, "\n");
2504         eat_statement();
2505
2506         return make_invalid_expression();
2507 }
2508
2509 static expression_t *parse_array_expression(unsigned precedence,
2510                                             expression_t *array_ref)
2511 {
2512         (void) precedence;
2513
2514         eat('[');
2515
2516         array_access_expression_t *array_access
2517                 = allocate_ast_zero(sizeof(array_access[0]));
2518
2519         array_access->expression.type     = EXPR_ARRAY_ACCESS;
2520         array_access->array_ref           = array_ref;
2521         array_access->index               = parse_expression();
2522
2523         type_t *type = array_ref->datatype;
2524         if(type != NULL) {
2525                 if(type->type == TYPE_POINTER) {
2526                         pointer_type_t *pointer           = (pointer_type_t*) type;
2527                         array_access->expression.datatype = pointer->points_to;
2528                 } else if(type->type == TYPE_ARRAY) {
2529                         array_type_t *array_type          = (array_type_t*) type;
2530                         array_access->expression.datatype = array_type->element_type;
2531                 } else {
2532                         parser_print_error_prefix();
2533                         fprintf(stderr, "array access on object with non-pointer type ");
2534                         print_type_quoted(type);
2535                         fprintf(stderr, "\n");
2536                 }
2537         }
2538
2539         if(token.type != ']') {
2540                 parse_error_expected("Problem while parsing array access", ']', 0);
2541                 return (expression_t*) array_access;
2542         }
2543         next_token();
2544
2545         return (expression_t*) array_access;
2546 }
2547
2548 static bool is_declaration_specifier(const token_t *token,
2549                                      bool only_type_specifiers)
2550 {
2551         switch(token->type) {
2552                 TYPE_SPECIFIERS
2553                         return 1;
2554                 case T_IDENTIFIER:
2555                         return is_typedef_symbol(token->v.symbol);
2556                 STORAGE_CLASSES
2557                 TYPE_QUALIFIERS
2558                         if(only_type_specifiers)
2559                                 return 0;
2560                         return 1;
2561
2562                 default:
2563                         return 0;
2564         }
2565 }
2566
2567 static expression_t *parse_sizeof(unsigned precedence)
2568 {
2569         eat(T_sizeof);
2570
2571         sizeof_expression_t *sizeof_expression
2572                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
2573         sizeof_expression->expression.type     = EXPR_SIZEOF;
2574         sizeof_expression->expression.datatype = type_size_t;
2575
2576         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
2577                 next_token();
2578                 sizeof_expression->type = parse_typename();
2579                 expect(')');
2580         } else {
2581                 expression_t *expression           = parse_sub_expression(precedence);
2582                 sizeof_expression->type            = expression->datatype;
2583                 sizeof_expression->size_expression = expression;
2584         }
2585
2586         return (expression_t*) sizeof_expression;
2587 }
2588
2589 static expression_t *parse_select_expression(unsigned precedence,
2590                                              expression_t *compound)
2591 {
2592         (void) precedence;
2593         assert(token.type == '.' || token.type == T_MINUSGREATER);
2594
2595         bool is_pointer = (token.type == T_MINUSGREATER);
2596         next_token();
2597
2598         select_expression_t *select = allocate_ast_zero(sizeof(select[0]));
2599
2600         select->expression.type = EXPR_SELECT;
2601         select->compound        = compound;
2602
2603         if(token.type != T_IDENTIFIER) {
2604                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
2605                 return (expression_t*) select;
2606         }
2607         symbol_t *symbol = token.v.symbol;
2608         select->symbol   = symbol;
2609         next_token();
2610
2611         type_t *type = compound->datatype;
2612         if(type == NULL)
2613                 return make_invalid_expression();
2614
2615         type_t *type_left = type;
2616         if(is_pointer) {
2617                 if(type->type != TYPE_POINTER) {
2618                         parser_print_error_prefix();
2619                         fprintf(stderr, "left hand side of '->' is not a pointer, but ");
2620                         print_type_quoted(type);
2621                         fputc('\n', stderr);
2622                         return make_invalid_expression();
2623                 }
2624                 pointer_type_t *pointer_type = (pointer_type_t*) type;
2625                 type_left                    = pointer_type->points_to;
2626         }
2627         type_left = skip_typeref(type_left);
2628
2629         if(type_left->type != TYPE_COMPOUND_STRUCT
2630                         && type_left->type != TYPE_COMPOUND_UNION) {
2631                 parser_print_error_prefix();
2632                 fprintf(stderr, "request for member '%s' in something not a struct or "
2633                         "union, but ", symbol->string);
2634                 print_type_quoted(type_left);
2635                 fputc('\n', stderr);
2636                 return make_invalid_expression();
2637         }
2638
2639         compound_type_t *compound_type = (compound_type_t*) type_left;
2640         declaration_t   *declaration   = compound_type->declaration;
2641
2642         if(!declaration->init.is_defined) {
2643                 parser_print_error_prefix();
2644                 fprintf(stderr, "request for member '%s' of incomplete type ",
2645                         symbol->string);
2646                 print_type_quoted(type_left);
2647                 fputc('\n', stderr);
2648                 return make_invalid_expression();
2649         }
2650
2651         declaration_t *iter = declaration->context.declarations;
2652         for( ; iter != NULL; iter = iter->next) {
2653                 if(iter->symbol == symbol) {
2654                         break;
2655                 }
2656         }
2657         if(iter == NULL) {
2658                 parser_print_error_prefix();
2659                 print_type_quoted(type_left);
2660                 fprintf(stderr, " has no member named '%s'\n", symbol->string);
2661                 return make_invalid_expression();
2662         }
2663
2664         select->compound_entry      = iter;
2665         select->expression.datatype = iter->type;
2666         return (expression_t*) select;
2667 }
2668
2669 static expression_t *parse_call_expression(unsigned precedence,
2670                                            expression_t *expression)
2671 {
2672         (void) precedence;
2673         call_expression_t *call = allocate_ast_zero(sizeof(call[0]));
2674         call->expression.type   = EXPR_CALL;
2675         call->function          = expression;
2676
2677         function_type_t *function_type;
2678         type_t          *type = expression->datatype;
2679         if (type->type == TYPE_FUNCTION) {
2680                 function_type             = (function_type_t*) type;
2681                 call->expression.datatype = function_type->result_type;
2682         } else if (type->type == TYPE_POINTER &&
2683                    ((pointer_type_t*)type)->points_to->type == TYPE_FUNCTION) {
2684                 pointer_type_t *const ptr_type = (pointer_type_t*)type;
2685                 function_type                  = (function_type_t*)ptr_type->points_to;
2686                 call->expression.datatype      = function_type->result_type;
2687         } else {
2688                 parser_print_error_prefix();
2689                 fputs("called object '", stderr);
2690                 print_expression(expression);
2691                 fputs("' (type ", stderr);
2692                 print_type_quoted(type);
2693                 fputs(") is not a function\n", stderr);
2694
2695                 function_type             = NULL;
2696                 call->expression.datatype = NULL;
2697         }
2698
2699         /* parse arguments */
2700         eat('(');
2701
2702         if(token.type != ')') {
2703                 call_argument_t *last_argument = NULL;
2704
2705                 while(true) {
2706                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
2707
2708                         argument->expression = parse_assignment_expression();
2709                         if(last_argument == NULL) {
2710                                 call->arguments = argument;
2711                         } else {
2712                                 last_argument->next = argument;
2713                         }
2714                         last_argument = argument;
2715
2716                         if(token.type != ',')
2717                                 break;
2718                         next_token();
2719                 }
2720         }
2721         expect(')');
2722
2723         if(function_type != NULL) {
2724                 function_parameter_t *parameter = function_type->parameters;
2725                 call_argument_t      *argument  = call->arguments;
2726                 for( ; parameter != NULL && argument != NULL;
2727                                 parameter = parameter->next, argument = argument->next) {
2728                         type_t *expected_type = parameter->type;
2729                         /* TODO report context in error messages */
2730                         argument->expression = create_implicit_cast(argument->expression,
2731                                                                     expected_type);
2732                 }
2733                 /* too few parameters */
2734                 if(parameter != NULL) {
2735                         parser_print_error_prefix();
2736                         fprintf(stderr, "too few arguments to function '");
2737                         print_expression(expression);
2738                         fprintf(stderr, "'\n");
2739                 } else if(argument != NULL) {
2740                         /* too many parameters */
2741                         if(!function_type->variadic
2742                                         && !function_type->unspecified_parameters) {
2743                                 parser_print_error_prefix();
2744                                 fprintf(stderr, "too many arguments to function '");
2745                                 print_expression(expression);
2746                                 fprintf(stderr, "'\n");
2747                         } else {
2748                                 /* do default promotion */
2749                                 for( ; argument != NULL; argument = argument->next) {
2750                                         type_t *type = argument->expression->datatype;
2751
2752                                         if(type == NULL)
2753                                                 continue;
2754
2755                                         if(is_type_integer(type)) {
2756                                                 type = promote_integer(type);
2757                                         } else if(type == type_float) {
2758                                                 type = type_double;
2759                                         }
2760                                         argument->expression
2761                                                 = create_implicit_cast(argument->expression, type);
2762                                 }
2763                         }
2764                 }
2765         }
2766
2767         return (expression_t*) call;
2768 }
2769
2770 static type_t *get_type_after_conversion(const type_t *type1,
2771                                          const type_t *type2)
2772 {
2773         /* TODO... */
2774         (void) type2;
2775         return (type_t*) type1;
2776 }
2777
2778 static expression_t *parse_conditional_expression(unsigned precedence,
2779                                                   expression_t *expression)
2780 {
2781         eat('?');
2782
2783         conditional_expression_t *conditional
2784                 = allocate_ast_zero(sizeof(conditional[0]));
2785         conditional->expression.type = EXPR_CONDITIONAL;
2786         conditional->condition = expression;
2787
2788         /* 6.5.15.2 */
2789         type_t *condition_type = conditional->condition->datatype;
2790         if(condition_type != NULL) {
2791                 if(!is_type_scalar(skip_typeref(condition_type))) {
2792                         type_error("expected a scalar type", expression->source_position,
2793                                    condition_type);
2794                 }
2795         }
2796
2797         conditional->true_expression = parse_expression();
2798         expect(':');
2799         conditional->false_expression = parse_sub_expression(precedence);
2800
2801         type_t *true_type  = conditional->true_expression->datatype;
2802         if(true_type == NULL)
2803                 return (expression_t*) conditional;
2804         type_t *false_type = conditional->false_expression->datatype;
2805         if(false_type == NULL)
2806                 return (expression_t*) conditional;
2807
2808         type_t *const skipped_true_type  = skip_typeref(true_type);
2809         type_t *const skipped_false_type = skip_typeref(false_type);
2810
2811         /* 6.5.15.3 */
2812         if (skipped_true_type == skipped_false_type) {
2813                 conditional->expression.datatype = skipped_true_type;
2814         } else if (is_type_arithmetic(skipped_true_type) &&
2815                    is_type_arithmetic(skipped_false_type)) {
2816                 type_t *const result = get_type_after_conversion(skipped_true_type,
2817                                                                  skipped_false_type);
2818                 /* TODO: create implicit convs if necessary */
2819                 conditional->expression.datatype = result;
2820         } else if (skipped_true_type->type == TYPE_POINTER &&
2821                    skipped_false_type->type == TYPE_POINTER &&
2822                           true /* TODO compatible points_to types */) {
2823                 /* TODO */
2824         } else if(/* (is_null_ptr_const(skipped_true_type) &&
2825                       skipped_false_type->type == TYPE_POINTER)
2826                || (is_null_ptr_const(skipped_false_type) &&
2827                    skipped_true_type->type == TYPE_POINTER) TODO*/ false) {
2828                 /* TODO */
2829         } else if(/* 1 is pointer to object type, other is void* */ false) {
2830                 /* TODO */
2831         } else {
2832                 type_error_incompatible("while parsing conditional",
2833                                         expression->source_position, true_type,
2834                                         skipped_false_type);
2835         }
2836
2837         return (expression_t*) conditional;
2838 }
2839
2840 static expression_t *parse_extension(unsigned precedence)
2841 {
2842         eat(T___extension__);
2843
2844         /* TODO enable extensions */
2845
2846         return parse_sub_expression(precedence);
2847 }
2848
2849 static void semantic_incdec(unary_expression_t *expression)
2850 {
2851         type_t *orig_type = expression->value->datatype;
2852         if(orig_type == NULL)
2853                 return;
2854
2855         type_t *type = skip_typeref(orig_type);
2856         if(!is_type_arithmetic(type) && type->type != TYPE_POINTER) {
2857                 /* TODO: improve error message */
2858                 parser_print_error_prefix();
2859                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
2860                 return;
2861         }
2862
2863         expression->expression.datatype = orig_type;
2864 }
2865
2866 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
2867 {
2868         type_t *orig_type = expression->value->datatype;
2869         if(orig_type == NULL)
2870                 return;
2871
2872         type_t *type = skip_typeref(orig_type);
2873         if(!is_type_arithmetic(type)) {
2874                 /* TODO: improve error message */
2875                 parser_print_error_prefix();
2876                 fprintf(stderr, "operation needs an arithmetic type\n");
2877                 return;
2878         }
2879
2880         expression->expression.datatype = orig_type;
2881 }
2882
2883 static void semantic_unexpr_scalar(unary_expression_t *expression)
2884 {
2885         type_t *orig_type = expression->value->datatype;
2886         if(orig_type == NULL)
2887                 return;
2888
2889         type_t *type = skip_typeref(orig_type);
2890         if (!is_type_scalar(type)) {
2891                 parse_error("operand of ! must be of scalar type\n");
2892                 return;
2893         }
2894
2895         expression->expression.datatype = orig_type;
2896 }
2897
2898 static void semantic_unexpr_integer(unary_expression_t *expression)
2899 {
2900         type_t *orig_type = expression->value->datatype;
2901         if(orig_type == NULL)
2902                 return;
2903
2904         type_t *type = skip_typeref(orig_type);
2905         if (!is_type_integer(type)) {
2906                 parse_error("operand of ~ must be of integer type\n");
2907                 return;
2908         }
2909
2910         expression->expression.datatype = orig_type;
2911 }
2912
2913 static void semantic_dereference(unary_expression_t *expression)
2914 {
2915         type_t *orig_type = expression->value->datatype;
2916         if(orig_type == NULL)
2917                 return;
2918
2919         type_t *type = skip_typeref(orig_type);
2920         switch (type->type) {
2921                 case TYPE_ARRAY: {
2922                         array_type_t *const array_type  = (array_type_t*)type;
2923                         expression->expression.datatype = array_type->element_type;
2924                         break;
2925                 }
2926
2927                 case TYPE_POINTER: {
2928                         pointer_type_t *pointer_type    = (pointer_type_t*)type;
2929                         expression->expression.datatype = pointer_type->points_to;
2930                         break;
2931                 }
2932
2933                 default:
2934                         parser_print_error_prefix();
2935                         fputs("'Unary *' needs pointer or arrray type, but type ", stderr);
2936                         print_type_quoted(orig_type);
2937                         fputs(" given.\n", stderr);
2938                         return;
2939         }
2940 }
2941
2942 static void semantic_take_addr(unary_expression_t *expression)
2943 {
2944         type_t *orig_type = expression->value->datatype;
2945         if(orig_type == NULL)
2946                 return;
2947
2948         expression_t *value = expression->value;
2949         if(value->type == EXPR_REFERENCE) {
2950                 reference_expression_t *reference   = (reference_expression_t*) value;
2951                 declaration_t          *declaration = reference->declaration;
2952                 if(declaration != NULL) {
2953                         declaration->address_taken = 1;
2954                 }
2955         }
2956
2957         expression->expression.datatype = make_pointer_type(orig_type, 0);
2958 }
2959
2960 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
2961 static expression_t *parse_##unexpression_type(unsigned precedence)            \
2962 {                                                                              \
2963         eat(token_type);                                                           \
2964                                                                                \
2965         unary_expression_t *unary_expression                                       \
2966                 = allocate_ast_zero(sizeof(unary_expression[0]));                      \
2967         unary_expression->expression.type     = EXPR_UNARY;                        \
2968         unary_expression->type                = unexpression_type;                 \
2969         unary_expression->value               = parse_sub_expression(precedence);  \
2970                                                                                    \
2971         sfunc(unary_expression);                                                   \
2972                                                                                \
2973         return (expression_t*) unary_expression;                                   \
2974 }
2975
2976 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE, semantic_unexpr_arithmetic)
2977 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS,   semantic_unexpr_arithmetic)
2978 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT,    semantic_unexpr_scalar)
2979 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE, semantic_dereference)
2980 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS, semantic_take_addr)
2981 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE,
2982                                semantic_unexpr_integer)
2983 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT,
2984                                semantic_incdec)
2985 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT,
2986                                semantic_incdec)
2987
2988 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
2989                                                sfunc)                         \
2990 static expression_t *parse_##unexpression_type(unsigned precedence,           \
2991                                                expression_t *left)            \
2992 {                                                                             \
2993         (void) precedence;                                                        \
2994         eat(token_type);                                                          \
2995                                                                               \
2996         unary_expression_t *unary_expression                                      \
2997                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
2998         unary_expression->expression.type     = EXPR_UNARY;                       \
2999         unary_expression->type                = unexpression_type;                \
3000         unary_expression->value               = left;                             \
3001                                                                                   \
3002         sfunc(unary_expression);                                                  \
3003                                                                               \
3004         return (expression_t*) unary_expression;                                  \
3005 }
3006
3007 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT,
3008                                        semantic_incdec)
3009 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT,
3010                                        semantic_incdec)
3011
3012 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
3013 {
3014         /* TODO: handle complex + imaginary types */
3015
3016         /* Â§ 6.3.1.8 Usual arithmetic conversions */
3017         if(type_left == type_long_double || type_right == type_long_double) {
3018                 return type_long_double;
3019         } else if(type_left == type_double || type_right == type_double) {
3020                 return type_double;
3021         } else if(type_left == type_float || type_right == type_float) {
3022                 return type_float;
3023         }
3024
3025         type_right = promote_integer(type_right);
3026         type_left  = promote_integer(type_left);
3027
3028         if(type_left == type_right)
3029                 return type_left;
3030
3031         bool signed_left  = is_type_signed(type_left);
3032         bool signed_right = is_type_signed(type_right);
3033         if(get_rank(type_left) < get_rank(type_right)) {
3034                 if(signed_left == signed_right || !signed_right) {
3035                         return type_right;
3036                 } else {
3037                         return type_left;
3038                 }
3039         } else {
3040                 if(signed_left == signed_right || !signed_left) {
3041                         return type_left;
3042                 } else {
3043                         return type_right;
3044                 }
3045         }
3046 }
3047
3048 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
3049 {
3050         expression_t *left       = expression->left;
3051         expression_t *right      = expression->right;
3052         type_t       *orig_type_left  = left->datatype;
3053         type_t       *orig_type_right = right->datatype;
3054
3055         if(orig_type_left == NULL || orig_type_right == NULL)
3056                 return;
3057
3058         type_t *type_left  = skip_typeref(orig_type_left);
3059         type_t *type_right = skip_typeref(orig_type_right);
3060
3061         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3062                 /* TODO: improve error message */
3063                 parser_print_error_prefix();
3064                 fprintf(stderr, "operation needs arithmetic types\n");
3065                 return;
3066         }
3067
3068         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3069         expression->left  = create_implicit_cast(left, arithmetic_type);
3070         expression->right = create_implicit_cast(right, arithmetic_type);
3071         expression->expression.datatype = arithmetic_type;
3072 }
3073
3074 static void semantic_shift_op(binary_expression_t *expression)
3075 {
3076         expression_t *left       = expression->left;
3077         expression_t *right      = expression->right;
3078         type_t       *orig_type_left  = left->datatype;
3079         type_t       *orig_type_right = right->datatype;
3080
3081         if(orig_type_left == NULL || orig_type_right == NULL)
3082                 return;
3083
3084         type_t *type_left  = skip_typeref(orig_type_left);
3085         type_t *type_right = skip_typeref(orig_type_right);
3086
3087         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
3088                 /* TODO: improve error message */
3089                 parser_print_error_prefix();
3090                 fprintf(stderr, "operation needs integer types\n");
3091                 return;
3092         }
3093
3094         type_left  = promote_integer(type_left);
3095         type_right = promote_integer(type_right);
3096
3097         expression->left  = create_implicit_cast(left, type_left);
3098         expression->right = create_implicit_cast(right, type_right);
3099         expression->expression.datatype = type_left;
3100 }
3101
3102 static void semantic_add(binary_expression_t *expression)
3103 {
3104         expression_t *left            = expression->left;
3105         expression_t *right           = expression->right;
3106         type_t       *orig_type_left  = left->datatype;
3107         type_t       *orig_type_right = right->datatype;
3108
3109         if(orig_type_left == NULL || orig_type_right == NULL)
3110                 return;
3111
3112         type_t *type_left  = skip_typeref(orig_type_left);
3113         type_t *type_right = skip_typeref(orig_type_right);
3114
3115         /* Â§ 5.6.5 */
3116         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3117                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3118                 expression->left  = create_implicit_cast(left, arithmetic_type);
3119                 expression->right = create_implicit_cast(right, arithmetic_type);
3120                 expression->expression.datatype = arithmetic_type;
3121                 return;
3122         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3123                 expression->expression.datatype = type_left;
3124         } else if(type_right->type == TYPE_POINTER && is_type_integer(type_left)) {
3125                 expression->expression.datatype = type_right;
3126         } else if (type_left->type == TYPE_ARRAY && is_type_integer(type_right)) {
3127                 const array_type_t *const arr_type = (const array_type_t*)type_left;
3128                 expression->expression.datatype =
3129                   make_pointer_type(arr_type->element_type, TYPE_QUALIFIER_NONE);
3130         } else if (type_right->type == TYPE_ARRAY && is_type_integer(type_left)) {
3131                 const array_type_t *const arr_type = (const array_type_t*)type_right;
3132                 expression->expression.datatype =
3133                         make_pointer_type(arr_type->element_type, TYPE_QUALIFIER_NONE);
3134         } else {
3135                 parser_print_error_prefix();
3136                 fprintf(stderr, "invalid operands to binary + (");
3137                 print_type_quoted(orig_type_left);
3138                 fprintf(stderr, ", ");
3139                 print_type_quoted(orig_type_right);
3140                 fprintf(stderr, ")\n");
3141         }
3142 }
3143
3144 static void semantic_sub(binary_expression_t *expression)
3145 {
3146         expression_t *left            = expression->left;
3147         expression_t *right           = expression->right;
3148         type_t       *orig_type_left  = left->datatype;
3149         type_t       *orig_type_right = right->datatype;
3150
3151         if(orig_type_left == NULL || orig_type_right == NULL)
3152                 return;
3153
3154         type_t       *type_left       = skip_typeref(orig_type_left);
3155         type_t       *type_right      = skip_typeref(orig_type_right);
3156
3157         /* Â§ 5.6.5 */
3158         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3159                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3160                 expression->left  = create_implicit_cast(left, arithmetic_type);
3161                 expression->right = create_implicit_cast(right, arithmetic_type);
3162                 expression->expression.datatype = arithmetic_type;
3163                 return;
3164         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3165                 expression->expression.datatype = type_left;
3166         } else if(type_left->type == TYPE_POINTER &&
3167                         type_right->type == TYPE_POINTER) {
3168                 if(!pointers_compatible(type_left, type_right)) {
3169                         parser_print_error_prefix();
3170                         fprintf(stderr, "pointers to incompatible objects to binary - (");
3171                         print_type_quoted(orig_type_left);
3172                         fprintf(stderr, ", ");
3173                         print_type_quoted(orig_type_right);
3174                         fprintf(stderr, ")\n");
3175                 } else {
3176                         expression->expression.datatype = type_ptrdiff_t;
3177                 }
3178         } else {
3179                 parser_print_error_prefix();
3180                 fprintf(stderr, "invalid operands to binary - (");
3181                 print_type_quoted(orig_type_left);
3182                 fprintf(stderr, ", ");
3183                 print_type_quoted(orig_type_right);
3184                 fprintf(stderr, ")\n");
3185         }
3186 }
3187
3188 static void semantic_comparison(binary_expression_t *expression)
3189 {
3190         expression_t *left            = expression->left;
3191         expression_t *right           = expression->right;
3192         type_t       *orig_type_left  = left->datatype;
3193         type_t       *orig_type_right = right->datatype;
3194
3195         if(orig_type_left == NULL || orig_type_right == NULL)
3196                 return;
3197
3198         type_t *type_left  = skip_typeref(orig_type_left);
3199         type_t *type_right = skip_typeref(orig_type_right);
3200
3201         /* TODO non-arithmetic types */
3202         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3203                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3204                 expression->left  = create_implicit_cast(left, arithmetic_type);
3205                 expression->right = create_implicit_cast(right, arithmetic_type);
3206                 expression->expression.datatype = arithmetic_type;
3207         } else if (type_left->type  == TYPE_POINTER &&
3208                    type_right->type == TYPE_POINTER) {
3209                 /* TODO check compatibility */
3210         } else if (type_left->type == TYPE_POINTER) {
3211                 expression->right = create_implicit_cast(right, type_left);
3212         } else if (type_right->type == TYPE_POINTER) {
3213                 expression->left = create_implicit_cast(left, type_right);
3214         } else {
3215                 type_error_incompatible("invalid operands in comparison",
3216                                         expression->expression.source_position,
3217                                         type_left, type_right);
3218         }
3219         expression->expression.datatype = type_int;
3220 }
3221
3222 static void semantic_arithmetic_assign(binary_expression_t *expression)
3223 {
3224         expression_t *left            = expression->left;
3225         expression_t *right           = expression->right;
3226         type_t       *orig_type_left  = left->datatype;
3227         type_t       *orig_type_right = right->datatype;
3228
3229         if(orig_type_left == NULL || orig_type_right == NULL)
3230                 return;
3231
3232         type_t *type_left  = skip_typeref(orig_type_left);
3233         type_t *type_right = skip_typeref(orig_type_right);
3234
3235         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3236                 /* TODO: improve error message */
3237                 parser_print_error_prefix();
3238                 fprintf(stderr, "operation needs arithmetic types\n");
3239                 return;
3240         }
3241
3242         /* combined instructions are tricky. We can't create an implicit cast on
3243          * the left side, because we need the uncasted form for the store.
3244          * The ast2firm pass has to know that left_type must be right_type
3245          * for the arithmeitc operation and create a cast by itself */
3246         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3247         expression->right       = create_implicit_cast(right, arithmetic_type);
3248         expression->expression.datatype = type_left;
3249 }
3250
3251 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
3252 {
3253         expression_t *left            = expression->left;
3254         expression_t *right           = expression->right;
3255         type_t       *orig_type_left  = left->datatype;
3256         type_t       *orig_type_right = right->datatype;
3257
3258         if(orig_type_left == NULL || orig_type_right == NULL)
3259                 return;
3260
3261         type_t *type_left  = skip_typeref(orig_type_left);
3262         type_t *type_right = skip_typeref(orig_type_right);
3263
3264         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3265                 /* combined instructions are tricky. We can't create an implicit cast on
3266                  * the left side, because we need the uncasted form for the store.
3267                  * The ast2firm pass has to know that left_type must be right_type
3268                  * for the arithmeitc operation and create a cast by itself */
3269                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
3270                 expression->right = create_implicit_cast(right, arithmetic_type);
3271                 expression->expression.datatype = type_left;
3272         } else if (type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3273                 expression->expression.datatype = type_left;
3274         } else {
3275                 parser_print_error_prefix();
3276                 fputs("Incompatible types ", stderr);
3277                 print_type_quoted(orig_type_left);
3278                 fputs(" and ", stderr);
3279                 print_type_quoted(orig_type_right);
3280                 fputs(" in assignment\n", stderr);
3281                 return;
3282         }
3283 }
3284
3285 static void semantic_logical_op(binary_expression_t *expression)
3286 {
3287         expression_t *left            = expression->left;
3288         expression_t *right           = expression->right;
3289         type_t       *orig_type_left  = left->datatype;
3290         type_t       *orig_type_right = right->datatype;
3291
3292         if(orig_type_left == NULL || orig_type_right == NULL)
3293                 return;
3294
3295         type_t *type_left  = skip_typeref(orig_type_left);
3296         type_t *type_right = skip_typeref(orig_type_right);
3297
3298         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
3299                 /* TODO: improve error message */
3300                 parser_print_error_prefix();
3301                 fprintf(stderr, "operation needs scalar types\n");
3302                 return;
3303         }
3304
3305         expression->expression.datatype = type_int;
3306 }
3307
3308 static void semantic_binexpr_assign(binary_expression_t *expression)
3309 {
3310         expression_t *left       = expression->left;
3311         type_t       *type_left  = left->datatype;
3312
3313         if (type_left->type == TYPE_ARRAY) {
3314                 parse_error("Cannot assign to arrays.");
3315         } else if (type_left != NULL) {
3316                 semantic_assign(type_left, &expression->right, "assignment");
3317         }
3318
3319         expression->expression.datatype = type_left;
3320 }
3321
3322 static void semantic_comma(binary_expression_t *expression)
3323 {
3324         expression->expression.datatype = expression->right->datatype;
3325 }
3326
3327 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
3328 static expression_t *parse_##binexpression_type(unsigned precedence,     \
3329                                                 expression_t *left)      \
3330 {                                                                        \
3331         eat(token_type);                                                     \
3332                                                                          \
3333         expression_t *right = parse_sub_expression(precedence + lr);         \
3334                                                                          \
3335         binary_expression_t *binexpr                                         \
3336                 = allocate_ast_zero(sizeof(binexpr[0]));                         \
3337         binexpr->expression.type     = EXPR_BINARY;                          \
3338         binexpr->type                = binexpression_type;                   \
3339         binexpr->left                = left;                                 \
3340         binexpr->right               = right;                                \
3341         sfunc(binexpr);                                                      \
3342                                                                          \
3343         return (expression_t*) binexpr;                                      \
3344 }
3345
3346 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA,          semantic_comma, 1)
3347 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL,            semantic_binexpr_arithmetic, 1)
3348 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV,            semantic_binexpr_arithmetic, 1)
3349 CREATE_BINEXPR_PARSER('%', BINEXPR_MOD,            semantic_binexpr_arithmetic, 1)
3350 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD,            semantic_add, 1)
3351 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB,            semantic_sub, 1)
3352 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS,           semantic_comparison, 1)
3353 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER,        semantic_comparison, 1)
3354 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN,         semantic_binexpr_assign, 0)
3355 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL, semantic_comparison, 1)
3356 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL,
3357                       semantic_comparison, 1)
3358 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL, semantic_comparison, 1)
3359 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL,
3360                       semantic_comparison, 1)
3361 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND,    semantic_binexpr_arithmetic, 1)
3362 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR,     semantic_binexpr_arithmetic, 1)
3363 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR,    semantic_binexpr_arithmetic, 1)
3364 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND,  semantic_logical_op, 1)
3365 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR, semantic_logical_op, 1)
3366 /* TODO shift has a bit special semantic */
3367 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT,
3368                       semantic_shift_op, 1)
3369 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT,
3370                       semantic_shift_op, 1)
3371 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN,
3372                       semantic_arithmetic_addsubb_assign, 0)
3373 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN,
3374                       semantic_arithmetic_addsubb_assign, 0)
3375 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN,
3376                       semantic_arithmetic_assign, 0)
3377 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN,
3378                       semantic_arithmetic_assign, 0)
3379 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN,
3380                       semantic_arithmetic_assign, 0)
3381 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN,
3382                       semantic_arithmetic_assign, 0)
3383 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN,
3384                       semantic_arithmetic_assign, 0)
3385 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN,
3386                       semantic_arithmetic_assign, 0)
3387 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN,
3388                       semantic_arithmetic_assign, 0)
3389 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN,
3390                       semantic_arithmetic_assign, 0)
3391
3392 static expression_t *parse_sub_expression(unsigned precedence)
3393 {
3394         if(token.type < 0) {
3395                 return expected_expression_error();
3396         }
3397
3398         expression_parser_function_t *parser
3399                 = &expression_parsers[token.type];
3400         source_position_t             source_position = token.source_position;
3401         expression_t                 *left;
3402
3403         if(parser->parser != NULL) {
3404                 left = parser->parser(parser->precedence);
3405         } else {
3406                 left = parse_primary_expression();
3407         }
3408         assert(left != NULL);
3409         left->source_position = source_position;
3410
3411         while(true) {
3412                 if(token.type < 0) {
3413                         return expected_expression_error();
3414                 }
3415
3416                 parser = &expression_parsers[token.type];
3417                 if(parser->infix_parser == NULL)
3418                         break;
3419                 if(parser->infix_precedence < precedence)
3420                         break;
3421
3422                 left = parser->infix_parser(parser->infix_precedence, left);
3423
3424                 assert(left != NULL);
3425                 assert(left->type != EXPR_UNKNOWN);
3426                 left->source_position = source_position;
3427         }
3428
3429         return left;
3430 }
3431
3432 static expression_t *parse_expression(void)
3433 {
3434         return parse_sub_expression(1);
3435 }
3436
3437
3438
3439 static void register_expression_parser(parse_expression_function parser,
3440                                        int token_type, unsigned precedence)
3441 {
3442         expression_parser_function_t *entry = &expression_parsers[token_type];
3443
3444         if(entry->parser != NULL) {
3445                 fprintf(stderr, "for token ");
3446                 print_token_type(stderr, token_type);
3447                 fprintf(stderr, "\n");
3448                 panic("trying to register multiple expression parsers for a token");
3449         }
3450         entry->parser     = parser;
3451         entry->precedence = precedence;
3452 }
3453
3454 static void register_expression_infix_parser(
3455                 parse_expression_infix_function parser, int token_type,
3456                 unsigned precedence)
3457 {
3458         expression_parser_function_t *entry = &expression_parsers[token_type];
3459
3460         if(entry->infix_parser != NULL) {
3461                 fprintf(stderr, "for token ");
3462                 print_token_type(stderr, token_type);
3463                 fprintf(stderr, "\n");
3464                 panic("trying to register multiple infix expression parsers for a "
3465                       "token");
3466         }
3467         entry->infix_parser     = parser;
3468         entry->infix_precedence = precedence;
3469 }
3470
3471 static void init_expression_parsers(void)
3472 {
3473         memset(&expression_parsers, 0, sizeof(expression_parsers));
3474
3475         register_expression_infix_parser(parse_BINEXPR_MUL,         '*',        16);
3476         register_expression_infix_parser(parse_BINEXPR_DIV,         '/',        16);
3477         register_expression_infix_parser(parse_BINEXPR_MOD,         '%',        16);
3478         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,   T_LESSLESS, 16);
3479         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
3480                                                               T_GREATERGREATER, 16);
3481         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
3482         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
3483         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
3484         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
3485         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
3486         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
3487                                                                 T_GREATEREQUAL, 14);
3488         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
3489         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
3490                                                         T_EXCLAMATIONMARKEQUAL, 13);
3491         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
3492         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
3493         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
3494         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
3495         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
3496         register_expression_infix_parser(parse_conditional_expression, '?',      7);
3497         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
3498         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
3499         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
3500         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
3501                                                                 T_ASTERISKEQUAL, 2);
3502         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
3503         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
3504                                                                  T_PERCENTEQUAL, 2);
3505         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
3506                                                                 T_LESSLESSEQUAL, 2);
3507         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
3508                                                           T_GREATERGREATEREQUAL, 2);
3509         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
3510                                                                      T_ANDEQUAL, 2);
3511         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
3512                                                                     T_PIPEEQUAL, 2);
3513         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
3514                                                                    T_CARETEQUAL, 2);
3515
3516         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
3517
3518         register_expression_infix_parser(parse_array_expression,        '[',    30);
3519         register_expression_infix_parser(parse_call_expression,         '(',    30);
3520         register_expression_infix_parser(parse_select_expression,       '.',    30);
3521         register_expression_infix_parser(parse_select_expression,
3522                                                                 T_MINUSGREATER, 30);
3523         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
3524                                          T_PLUSPLUS, 30);
3525         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
3526                                          T_MINUSMINUS, 30);
3527
3528         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
3529         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
3530         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
3531         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
3532         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
3533         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
3534         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
3535         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
3536         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
3537         register_expression_parser(parse_extension,            T___extension__, 25);
3538 }
3539
3540
3541 static statement_t *parse_case_statement(void)
3542 {
3543         eat(T_case);
3544         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
3545         label->statement.type            = STATEMENT_CASE_LABEL;
3546         label->statement.source_position = token.source_position;
3547
3548         label->expression = parse_expression();
3549
3550         expect(':');
3551         label->statement.next = parse_statement();
3552
3553         return (statement_t*) label;
3554 }
3555
3556 static statement_t *parse_default_statement(void)
3557 {
3558         eat(T_default);
3559
3560         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
3561         label->statement.type            = STATEMENT_CASE_LABEL;
3562         label->statement.source_position = token.source_position;
3563
3564         expect(':');
3565         label->statement.next = parse_statement();
3566
3567         return (statement_t*) label;
3568 }
3569
3570 static declaration_t *get_label(symbol_t *symbol)
3571 {
3572         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
3573         assert(current_function != NULL);
3574         /* if we found a label in the same function, then we already created the
3575          * declaration */
3576         if(candidate != NULL
3577                         && candidate->parent_context == &current_function->context) {
3578                 return candidate;
3579         }
3580
3581         /* otherwise we need to create a new one */
3582         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
3583         declaration->namespc     = NAMESPACE_LABEL;
3584         declaration->symbol        = symbol;
3585
3586         label_push(declaration);
3587
3588         return declaration;
3589 }
3590
3591 static statement_t *parse_label_statement(void)
3592 {
3593         assert(token.type == T_IDENTIFIER);
3594         symbol_t *symbol = token.v.symbol;
3595         next_token();
3596
3597         declaration_t *label = get_label(symbol);
3598
3599         /* if source position is already set then the label is defined twice,
3600          * otherwise it was just mentioned in a goto so far */
3601         if(label->source_position.input_name != NULL) {
3602                 parser_print_error_prefix();
3603                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
3604                 parser_print_error_prefix_pos(label->source_position);
3605                 fprintf(stderr, "previous definition of '%s' was here\n",
3606                         symbol->string);
3607         } else {
3608                 label->source_position = token.source_position;
3609         }
3610
3611         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
3612
3613         label_statement->statement.type            = STATEMENT_LABEL;
3614         label_statement->statement.source_position = token.source_position;
3615         label_statement->label                     = label;
3616
3617         expect(':');
3618
3619         if(token.type == '}') {
3620                 parse_error("label at end of compound statement");
3621                 return (statement_t*) label_statement;
3622         } else {
3623                 label_statement->label_statement = parse_statement();
3624         }
3625
3626         return (statement_t*) label_statement;
3627 }
3628
3629 static statement_t *parse_if(void)
3630 {
3631         eat(T_if);
3632
3633         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3634         statement->statement.type            = STATEMENT_IF;
3635         statement->statement.source_position = token.source_position;
3636
3637         expect('(');
3638         statement->condition = parse_expression();
3639         expect(')');
3640
3641         statement->true_statement = parse_statement();
3642         if(token.type == T_else) {
3643                 next_token();
3644                 statement->false_statement = parse_statement();
3645         }
3646
3647         return (statement_t*) statement;
3648 }
3649
3650 static statement_t *parse_switch(void)
3651 {
3652         eat(T_switch);
3653
3654         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3655         statement->statement.type            = STATEMENT_SWITCH;
3656         statement->statement.source_position = token.source_position;
3657
3658         expect('(');
3659         statement->expression = parse_expression();
3660         expect(')');
3661         statement->body = parse_statement();
3662
3663         return (statement_t*) statement;
3664 }
3665
3666 static statement_t *parse_while(void)
3667 {
3668         eat(T_while);
3669
3670         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3671         statement->statement.type            = STATEMENT_WHILE;
3672         statement->statement.source_position = token.source_position;
3673
3674         expect('(');
3675         statement->condition = parse_expression();
3676         expect(')');
3677         statement->body = parse_statement();
3678
3679         return (statement_t*) statement;
3680 }
3681
3682 static statement_t *parse_do(void)
3683 {
3684         eat(T_do);
3685
3686         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3687         statement->statement.type            = STATEMENT_DO_WHILE;
3688         statement->statement.source_position = token.source_position;
3689
3690         statement->body = parse_statement();
3691         expect(T_while);
3692         expect('(');
3693         statement->condition = parse_expression();
3694         expect(')');
3695         expect(';');
3696
3697         return (statement_t*) statement;
3698 }
3699
3700 static statement_t *parse_for(void)
3701 {
3702         eat(T_for);
3703
3704         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3705         statement->statement.type            = STATEMENT_FOR;
3706         statement->statement.source_position = token.source_position;
3707
3708         expect('(');
3709
3710         int         top          = environment_top();
3711         context_t  *last_context = context;
3712         set_context(&statement->context);
3713
3714         if(token.type != ';') {
3715                 if(is_declaration_specifier(&token, false)) {
3716                         parse_declaration();
3717                 } else {
3718                         statement->initialisation = parse_expression();
3719                         expect(';');
3720                 }
3721         } else {
3722                 expect(';');
3723         }
3724
3725         if(token.type != ';') {
3726                 statement->condition = parse_expression();
3727         }
3728         expect(';');
3729         if(token.type != ')') {
3730                 statement->step = parse_expression();
3731         }
3732         expect(')');
3733         statement->body = parse_statement();
3734
3735         assert(context == &statement->context);
3736         set_context(last_context);
3737         environment_pop_to(top);
3738
3739         return (statement_t*) statement;
3740 }
3741
3742 static statement_t *parse_goto(void)
3743 {
3744         eat(T_goto);
3745
3746         if(token.type != T_IDENTIFIER) {
3747                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
3748                 eat_statement();
3749                 return NULL;
3750         }
3751         symbol_t *symbol = token.v.symbol;
3752         next_token();
3753
3754         declaration_t *label = get_label(symbol);
3755
3756         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3757
3758         statement->statement.type            = STATEMENT_GOTO;
3759         statement->statement.source_position = token.source_position;
3760
3761         statement->label = label;
3762
3763         expect(';');
3764
3765         return (statement_t*) statement;
3766 }
3767
3768 static statement_t *parse_continue(void)
3769 {
3770         eat(T_continue);
3771         expect(';');
3772
3773         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
3774         statement->type            = STATEMENT_CONTINUE;
3775         statement->source_position = token.source_position;
3776
3777         return statement;
3778 }
3779
3780 static statement_t *parse_break(void)
3781 {
3782         eat(T_break);
3783         expect(';');
3784
3785         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
3786         statement->type            = STATEMENT_BREAK;
3787         statement->source_position = token.source_position;
3788
3789         return statement;
3790 }
3791
3792 static statement_t *parse_return(void)
3793 {
3794         eat(T_return);
3795
3796         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3797
3798         statement->statement.type            = STATEMENT_RETURN;
3799         statement->statement.source_position = token.source_position;
3800
3801         assert(current_function->type->type == TYPE_FUNCTION);
3802         function_type_t *function_type = (function_type_t*) current_function->type;
3803         type_t          *return_type   = function_type->result_type;
3804
3805         expression_t *return_value;
3806         if(token.type != ';') {
3807                 return_value = parse_expression();
3808
3809                 if(return_type == type_void && return_value->datatype != type_void) {
3810                         parse_warning("'return' with a value, in function returning void");
3811                         return_value = NULL;
3812                 } else {
3813                         if(return_type != NULL) {
3814                                 semantic_assign(return_type, &return_value, "'return'");
3815                         }
3816                 }
3817         } else {
3818                 return_value = NULL;
3819                 if(return_type != type_void) {
3820                         parse_warning("'return' without value, in function returning "
3821                                       "non-void");
3822                 }
3823         }
3824         statement->return_value = return_value;
3825
3826         expect(';');
3827
3828         return (statement_t*) statement;
3829 }
3830
3831 static statement_t *parse_declaration_statement(void)
3832 {
3833         declaration_t *before = last_declaration;
3834
3835         declaration_statement_t *statement
3836                 = allocate_ast_zero(sizeof(statement[0]));
3837         statement->statement.type            = STATEMENT_DECLARATION;
3838         statement->statement.source_position = token.source_position;
3839
3840         declaration_specifiers_t specifiers;
3841         memset(&specifiers, 0, sizeof(specifiers));
3842         parse_declaration_specifiers(&specifiers);
3843
3844         if(token.type == ';') {
3845                 eat(';');
3846         } else {
3847                 parse_init_declarators(&specifiers);
3848         }
3849
3850         if(before == NULL) {
3851                 statement->declarations_begin = context->declarations;
3852         } else {
3853                 statement->declarations_begin = before->next;
3854         }
3855         statement->declarations_end = last_declaration;
3856
3857         return (statement_t*) statement;
3858 }
3859
3860 static statement_t *parse_expression_statement(void)
3861 {
3862         expression_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3863         statement->statement.type            = STATEMENT_EXPRESSION;
3864         statement->statement.source_position = token.source_position;
3865
3866         statement->expression = parse_expression();
3867
3868         expect(';');
3869
3870         return (statement_t*) statement;
3871 }
3872
3873 static statement_t *parse_statement(void)
3874 {
3875         statement_t   *statement = NULL;
3876
3877         /* declaration or statement */
3878         switch(token.type) {
3879         case T_case:
3880                 statement = parse_case_statement();
3881                 break;
3882
3883         case T_default:
3884                 statement = parse_default_statement();
3885                 break;
3886
3887         case '{':
3888                 statement = parse_compound_statement();
3889                 break;
3890
3891         case T_if:
3892                 statement = parse_if();
3893                 break;
3894
3895         case T_switch:
3896                 statement = parse_switch();
3897                 break;
3898
3899         case T_while:
3900                 statement = parse_while();
3901                 break;
3902
3903         case T_do:
3904                 statement = parse_do();
3905                 break;
3906
3907         case T_for:
3908                 statement = parse_for();
3909                 break;
3910
3911         case T_goto:
3912                 statement = parse_goto();
3913                 break;
3914
3915         case T_continue:
3916                 statement = parse_continue();
3917                 break;
3918
3919         case T_break:
3920                 statement = parse_break();
3921                 break;
3922
3923         case T_return:
3924                 statement = parse_return();
3925                 break;
3926
3927         case ';':
3928                 next_token();
3929                 statement = NULL;
3930                 break;
3931
3932         case T_IDENTIFIER:
3933                 if(look_ahead(1)->type == ':') {
3934                         statement = parse_label_statement();
3935                         break;
3936                 }
3937
3938                 if(is_typedef_symbol(token.v.symbol)) {
3939                         statement = parse_declaration_statement();
3940                         break;
3941                 }
3942
3943                 statement = parse_expression_statement();
3944                 break;
3945
3946         case T___extension__:
3947                 /* this can be a prefix to a declaration or an expression statement */
3948                 /* we simply eat it now and parse the rest with tail recursion */
3949                 do {
3950                         next_token();
3951                 } while(token.type == T___extension__);
3952                 statement = parse_statement();
3953                 break;
3954
3955         DECLARATION_START
3956                 statement = parse_declaration_statement();
3957                 break;
3958
3959         default:
3960                 statement = parse_expression_statement();
3961                 break;
3962         }
3963
3964         assert(statement == NULL || statement->source_position.input_name != NULL);
3965
3966         return statement;
3967 }
3968
3969 static statement_t *parse_compound_statement(void)
3970 {
3971         compound_statement_t *compound_statement
3972                 = allocate_ast_zero(sizeof(compound_statement[0]));
3973         compound_statement->statement.type            = STATEMENT_COMPOUND;
3974         compound_statement->statement.source_position = token.source_position;
3975
3976         eat('{');
3977
3978         int        top          = environment_top();
3979         context_t *last_context = context;
3980         set_context(&compound_statement->context);
3981
3982         statement_t *last_statement = NULL;
3983
3984         while(token.type != '}' && token.type != T_EOF) {
3985                 statement_t *statement = parse_statement();
3986                 if(statement == NULL)
3987                         continue;
3988
3989                 if(last_statement != NULL) {
3990                         last_statement->next = statement;
3991                 } else {
3992                         compound_statement->statements = statement;
3993                 }
3994
3995                 while(statement->next != NULL)
3996                         statement = statement->next;
3997
3998                 last_statement = statement;
3999         }
4000
4001         if(token.type != '}') {
4002                 parser_print_error_prefix_pos(
4003                                 compound_statement->statement.source_position);
4004                 fprintf(stderr, "end of file while looking for closing '}'\n");
4005         }
4006         next_token();
4007
4008         assert(context == &compound_statement->context);
4009         set_context(last_context);
4010         environment_pop_to(top);
4011
4012         return (statement_t*) compound_statement;
4013 }
4014
4015 static translation_unit_t *parse_translation_unit(void)
4016 {
4017         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
4018
4019         assert(global_context == NULL);
4020         global_context = &unit->context;
4021
4022         assert(context == NULL);
4023         set_context(&unit->context);
4024
4025         while(token.type != T_EOF) {
4026                 parse_declaration();
4027         }
4028
4029         assert(context == &unit->context);
4030         context          = NULL;
4031         last_declaration = NULL;
4032
4033         assert(global_context == &unit->context);
4034         global_context = NULL;
4035
4036         return unit;
4037 }
4038
4039 translation_unit_t *parse(void)
4040 {
4041         environment_stack = NEW_ARR_F(stack_entry_t, 0);
4042         label_stack       = NEW_ARR_F(stack_entry_t, 0);
4043         found_error       = false;
4044
4045         type_set_output(stderr);
4046         ast_set_output(stderr);
4047
4048         lookahead_bufpos = 0;
4049         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
4050                 next_token();
4051         }
4052         translation_unit_t *unit = parse_translation_unit();
4053
4054         DEL_ARR_F(environment_stack);
4055         DEL_ARR_F(label_stack);
4056
4057         if(found_error)
4058                 return NULL;
4059
4060         return unit;
4061 }
4062
4063 void init_parser(void)
4064 {
4065         init_expression_parsers();
4066         obstack_init(&temp_obst);
4067
4068         type_int         = make_atomic_type(ATOMIC_TYPE_INT, 0);
4069         type_uint        = make_atomic_type(ATOMIC_TYPE_UINT, 0);
4070         type_long_double = make_atomic_type(ATOMIC_TYPE_LONG_DOUBLE, 0);
4071         type_double      = make_atomic_type(ATOMIC_TYPE_DOUBLE, 0);
4072         type_float       = make_atomic_type(ATOMIC_TYPE_FLOAT, 0);
4073         type_size_t      = make_atomic_type(ATOMIC_TYPE_ULONG, 0);
4074         type_ptrdiff_t   = make_atomic_type(ATOMIC_TYPE_LONG, 0);
4075         type_const_char  = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_CONST);
4076         type_void        = make_atomic_type(ATOMIC_TYPE_VOID, 0);
4077         type_string      = make_pointer_type(type_const_char, 0);
4078 }
4079
4080 void exit_parser(void)
4081 {
4082         obstack_free(&temp_obst, NULL);
4083 }