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