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