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