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