- countless bugfixes
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5
6 #include "parser.h"
7 #include "lexer.h"
8 #include "token_t.h"
9 #include "type_t.h"
10 #include "type_hash.h"
11 #include "ast_t.h"
12 #include "adt/bitfiddle.h"
13 #include "adt/error.h"
14 #include "adt/array.h"
15
16 //#define PRINT_TOKENS
17 //#define ABORT_ON_ERROR
18 #define MAX_LOOKAHEAD 2
19
20 struct environment_entry_t {
21         symbol_t      *symbol;
22         declaration_t *old_declaration;
23         const void    *old_context;
24 };
25
26 static token_t               token;
27 static token_t               lookahead_buffer[MAX_LOOKAHEAD];
28 static int                   lookahead_bufpos;
29 static struct obstack        environment_obstack;
30 static environment_entry_t **environment_stack = NULL;
31 static context_t            *context           = NULL;
32 static declaration_t        *last_declaration  = NULL;
33 static struct obstack        temp_obst;
34
35 static
36 statement_t *parse_compound_statement(void);
37 static
38 statement_t *parse_statement(void);
39
40 static
41 expression_t *parse_sub_expression(unsigned precedence);
42 static
43 expression_t *parse_expression(void);
44
45 static inline
46 void *allocate_ast_zero(size_t size)
47 {
48         void *res = allocate_ast(size);
49         memset(res, 0, size);
50         return res;
51 }
52
53 static inline
54 void *allocate_type_zero(size_t size)
55 {
56         void *res = obstack_alloc(type_obst, size);
57         memset(res, 0, size);
58         return res;
59 }
60
61 /**
62  * returns the top element of the environment stack
63  */
64 static inline
65 size_t environment_top(void)
66 {
67         return ARR_LEN(environment_stack);
68 }
69
70
71
72 static inline
73 void next_token(void)
74 {
75         token                              = lookahead_buffer[lookahead_bufpos];
76         lookahead_buffer[lookahead_bufpos] = lexer_token;
77         lexer_next_token();
78
79         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
80
81 #ifdef PRINT_TOKENS
82         print_token(stderr, &token);
83         fprintf(stderr, "\n");
84 #endif
85 }
86
87 static inline
88 const token_t *look_ahead(int num)
89 {
90         assert(num > 0 && num <= MAX_LOOKAHEAD);
91         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
92         return & lookahead_buffer[pos];
93 }
94
95 static inline
96 void eat(token_type_t type)
97 {
98         assert(token.type == type);
99         next_token();
100 }
101
102 void parser_print_error_prefix_pos(const source_position_t source_position)
103 {
104     fputs(source_position.input_name, stderr);
105     fputc(':', stderr);
106     fprintf(stderr, "%d", source_position.linenr);
107     fputs(": error: ", stderr);
108 #ifdef ABORT_ON_ERROR
109         abort();
110 #endif
111 }
112
113 void parser_print_error_prefix(void)
114 {
115         parser_print_error_prefix_pos(token.source_position);
116 }
117
118 static
119 void parse_error(const char *message)
120 {
121         parser_print_error_prefix();
122         fprintf(stderr, "parse error: %s\n", message);
123 }
124
125 static
126 void parse_error_expected(const char *message, ...)
127 {
128         va_list args;
129         int first = 1;
130
131         if(message != NULL) {
132                 parser_print_error_prefix();
133                 fprintf(stderr, "%s\n", message);
134         }
135         parser_print_error_prefix();
136         fputs("Parse error: got ", stderr);
137         print_token(stderr, &token);
138         fputs(", expected ", stderr);
139
140         va_start(args, message);
141         token_type_t token_type = va_arg(args, token_type_t);
142         while(token_type != 0) {
143                 if(first == 1) {
144                         first = 0;
145                 } else {
146                         fprintf(stderr, ", ");
147                 }
148                 print_token_type(stderr, token_type);
149                 token_type = va_arg(args, token_type_t);
150         }
151         va_end(args);
152         fprintf(stderr, "\n");
153 }
154
155 static void eat_block(void)
156 {
157         if(token.type == '{')
158                 next_token();
159
160         while(token.type != '}') {
161                 if(token.type == T_EOF)
162                         return;
163                 if(token.type == '{') {
164                         eat_block();
165                         continue;
166                 }
167                 next_token();
168         }
169         eat('}');
170 }
171
172 static void eat_statement(void)
173 {
174         while(token.type != ';') {
175                 if(token.type == T_EOF)
176                         return;
177                 if(token.type == '}')
178                         return;
179                 if(token.type == '{') {
180                         eat_block();
181                         continue;
182                 }
183                 next_token();
184         }
185         eat(';');
186 }
187
188 static void eat_brace(void)
189 {
190         if(token.type == '(')
191                 next_token();
192
193         while(token.type != ')') {
194                 if(token.type == T_EOF)
195                         return;
196                 if(token.type == '{') {
197                         eat_block();
198                         continue;
199                 }
200                 next_token();
201         }
202         eat(')');
203 }
204
205 #define expect(expected)                           \
206     if(UNLIKELY(token.type != (expected))) {       \
207         parse_error_expected(NULL, (expected), 0); \
208         eat_statement();                           \
209         return NULL;                               \
210     }                                              \
211     next_token();
212
213 #define expect_void(expected)                      \
214     if(UNLIKELY(token.type != (expected))) {       \
215         parse_error_expected(NULL, (expected), 0); \
216         eat_statement();                           \
217         return;                                    \
218     }                                              \
219     next_token();
220
221 static void set_context(context_t *new_context)
222 {
223         context = new_context;
224
225         declaration_t *declaration = new_context->declarations;
226         if(declaration != NULL) {
227                 while(1) {
228                         if(declaration->next == NULL)
229                                 break;
230                         declaration = declaration->next;
231                 }
232         }
233
234         last_declaration = declaration;
235 }
236
237 /**
238  * called when we find a 2nd declarator for an identifier we already have a
239  * declarator for
240  */
241 static int is_compatible_declaration (declaration_t *declaration,
242                                       declaration_t *previous)
243 {
244         /* TODO: not correct yet */
245         return declaration->type == previous->type;
246 }
247
248 /**
249  * pushs an environment_entry on the environment stack and links the
250  * corresponding symbol to the new entry
251  */
252 static inline
253 declaration_t *environment_push(declaration_t *declaration, const void *context)
254 {
255         environment_entry_t *entry
256                 = obstack_alloc(&environment_obstack, sizeof(entry[0]));
257         memset(entry, 0, sizeof(entry[0]));
258
259         int top = ARR_LEN(environment_stack);
260         ARR_RESIZE(environment_stack, top + 1);
261         environment_stack[top] = entry;
262
263         assert(declaration->source_position.input_name != NULL);
264
265         symbol_t *symbol = declaration->symbol;
266         assert(declaration != symbol->declaration);
267
268         if(symbol->context == context) {
269                 declaration_t *previous_declaration = symbol->declaration;
270                 if(symbol->declaration != NULL) {
271                         if(!is_compatible_declaration(declaration, previous_declaration)) {
272                                 parser_print_error_prefix_pos(declaration->source_position);
273                                 fprintf(stderr, "definition of symbol '%s' with type ",
274                                         declaration->symbol->string);
275                                 print_type(declaration->type);
276                                 fputc('\n', stderr);
277                                 parser_print_error_prefix_pos(
278                                                 previous_declaration->source_position);
279                                 fprintf(stderr, "is incompatible with previous declaration "
280                                         "of type ");
281                                 print_type(previous_declaration->type);
282                                 fputc('\n', stderr);
283                         }
284                         return previous_declaration;
285                 }
286         }
287
288         entry->old_declaration = symbol->declaration;
289         entry->old_context     = symbol->context;
290         entry->symbol          = symbol;
291         symbol->declaration    = declaration;
292         symbol->context        = context;
293
294         return declaration;
295 }
296
297 /**
298  * pops symbols from the environment stack until @p new_top is the top element
299  */
300 static inline
301 void environment_pop_to(size_t new_top)
302 {
303         environment_entry_t *entry = NULL;
304         size_t top = ARR_LEN(environment_stack);
305         size_t i;
306
307         if(new_top == top)
308                 return;
309
310         assert(new_top < top);
311         i = top;
312         do {
313                 entry = environment_stack[i - 1];
314
315                 symbol_t *symbol = entry->symbol;
316
317                 symbol->declaration = entry->old_declaration;
318                 symbol->context     = entry->old_context;
319
320                 --i;
321         } while(i != new_top);
322         obstack_free(&environment_obstack, entry);
323
324         ARR_SHRINKLEN(environment_stack, (int) new_top);
325 }
326
327
328
329 static expression_t *parse_constant_expression(void)
330 {
331         /* start parsing at precedence 7 (conditional expression) */
332         return parse_sub_expression(7);
333 }
334
335 static expression_t *parse_assignment_expression(void)
336 {
337         /* start parsing at precedence 2 (assignment expression) */
338         return parse_sub_expression(2);
339 }
340
341 static void parse_compound_type_entries(void);
342 static void parse_declarator(declaration_t *declaration,
343                              storage_class_t storage_class, type_t *type,
344                              int may_be_abstract);
345 static declaration_t *record_declaration(declaration_t *declaration);
346
347 typedef struct declaration_specifiers_t  declaration_specifiers_t;
348 struct declaration_specifiers_t {
349         storage_class_t  storage_class;
350         type_t          *type;
351 };
352
353 static compound_type_t *find_compound_type(compound_type_t *types,
354                                            const symbol_t *symbol)
355 {
356         compound_type_t *type = types;
357         for( ; type != NULL; type = type->next) {
358                 if(type->symbol == symbol)
359                         return type;
360         }
361
362         return NULL;
363 }
364
365 static type_t *parse_compound_type_specifier(int is_struct)
366 {
367         if(is_struct) {
368                 eat(T_struct);
369         } else {
370                 eat(T_union);
371         }
372
373         symbol_t        *symbol        = NULL;
374         compound_type_t *compound_type = NULL;
375
376         if(token.type == T_IDENTIFIER) {
377                 symbol = token.v.symbol;
378                 next_token();
379
380                 if(context != NULL) {
381                         if(is_struct) {
382                                 compound_type = find_compound_type(context->structs, symbol);
383                         } else {
384                                 compound_type = find_compound_type(context->unions, symbol);
385                         }
386                 }
387         } else if(token.type != '{') {
388                 if(is_struct) {
389                         parse_error_expected("problem while parsing struct type specifier",
390                                              T_IDENTIFIER, '{', 0);
391                 } else {
392                         parse_error_expected("problem while parsing union type specifier",
393                                              T_IDENTIFIER, '{', 0);
394                 }
395
396                 return NULL;
397         }
398
399         if(compound_type == NULL) {
400                 compound_type = allocate_type_zero(sizeof(compound_type[0]));
401
402                 if(is_struct) {
403                         compound_type->type.type = TYPE_COMPOUND_STRUCT;
404                 } else {
405                         compound_type->type.type = TYPE_COMPOUND_UNION;
406                 }
407                 compound_type->source_position = token.source_position;
408                 compound_type->symbol          = symbol;
409         }
410
411         if(token.type == '{') {
412                 if(compound_type->defined) {
413                         parser_print_error_prefix();
414                         fprintf(stderr, "multiple definition of %s %s\n",
415                                         is_struct ? "struct" : "union", symbol->string);
416                         compound_type->context.declarations = NULL;
417                 }
418                 compound_type->defined = 1;
419
420                 int         top          = environment_top();
421                 context_t  *last_context = context;
422                 set_context(&compound_type->context);
423
424                 parse_compound_type_entries();
425
426                 assert(context == &compound_type->context);
427                 set_context(last_context);
428                 environment_pop_to(top);
429         }
430
431         return (type_t*) compound_type;
432 }
433
434 static void parse_enum_entries(void)
435 {
436         eat('{');
437
438         if(token.type == '}') {
439                 next_token();
440                 parse_error("empty enum not allowed");
441                 return;
442         }
443
444         do {
445                 declaration_t *entry = allocate_ast_zero(sizeof(entry[0]));
446
447                 if(token.type != T_IDENTIFIER) {
448                         parse_error_expected("problem while parsing enum entry",
449                                              T_IDENTIFIER, 0);
450                         eat_block();
451                         return;
452                 }
453                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
454                 entry->symbol          = token.v.symbol;
455                 entry->source_position = token.source_position;
456                 next_token();
457
458                 if(token.type == '=') {
459                         next_token();
460                         entry->initializer = parse_constant_expression();
461                 }
462
463                 record_declaration(entry);
464
465                 if(token.type != ',')
466                         break;
467                 next_token();
468         } while(token.type != '}');
469
470         expect_void('}');
471 }
472
473 static enum_type_t *find_enum_type(enum_type_t *types, const symbol_t *symbol)
474 {
475         enum_type_t *type = types;
476         for( ; type != NULL; type = type->next) {
477                 if(type->symbol == symbol)
478                         return type;
479         }
480
481         return NULL;
482 }
483
484 static type_t *parse_enum_specifier(void)
485 {
486         eat(T_enum);
487
488         symbol_t    *symbol    = NULL;
489         enum_type_t *enum_type = NULL;
490
491         if(token.type == T_IDENTIFIER) {
492                 symbol = token.v.symbol;
493                 next_token();
494
495                 if(context != NULL) {
496                         enum_type = find_enum_type(context->enums, symbol);
497                 }
498         } else if(token.type != '{') {
499                 parse_error_expected("problem while parsing enum type specifier",
500                                      T_IDENTIFIER, '{', 0);
501                 return NULL;
502         }
503
504         if(enum_type == NULL) {
505                 enum_type                  = allocate_type_zero(sizeof(enum_type[0]));
506                 enum_type->type.type       = TYPE_ENUM;
507                 enum_type->source_position = token.source_position;
508                 enum_type->symbol          = symbol;
509         }
510
511         if(token.type == '{') {
512                 if(enum_type->defined) {
513                         parser_print_error_prefix();
514                         fprintf(stderr, "multiple definitions of enum %s\n",
515                                 symbol->string);
516                         enum_type->entries_begin = NULL;
517                         enum_type->entries_end   = NULL;
518                 }
519                 enum_type->defined = 1;
520
521                 declaration_t *before = last_declaration;
522
523                 parse_enum_entries();
524
525                 if(before == NULL) {
526                         enum_type->entries_begin = context->declarations;
527                 } else {
528                         enum_type->entries_begin = before->next;
529                 }
530                 enum_type->entries_end = last_declaration;
531         }
532
533         return (type_t*) enum_type;
534 }
535
536 static
537 const char *parse_string_literals(void)
538 {
539         assert(token.type == T_STRING_LITERAL);
540         const char *result = token.v.string;
541
542         next_token();
543
544         while(token.type == T_STRING_LITERAL) {
545                 result = concat_strings(result, token.v.string);
546                 next_token();
547         }
548
549         return result;
550 }
551
552 static
553 void parse_attributes(void)
554 {
555         while(1) {
556                 switch(token.type) {
557                 case T___attribute__:
558                         next_token();
559
560                         expect_void('(');
561                         int depth = 1;
562                         while(depth > 0) {
563                                 switch(token.type) {
564                                 case T_EOF:
565                                         parse_error("EOF while parsing attribute");
566                                         break;
567                                 case '(':
568                                         next_token();
569                                         depth++;
570                                         break;
571                                 case ')':
572                                         next_token();
573                                         depth--;
574                                         break;
575                                 default:
576                                         next_token();
577                                 }
578                         }
579                         break;
580                 case T_asm:
581                         next_token();
582                         expect_void('(');
583                         if(token.type != T_STRING_LITERAL) {
584                                 parse_error_expected("while parsing assembler attribute",
585                                                      T_STRING_LITERAL);
586                                 eat_brace();
587                                 break;
588                         } else {
589                                 parse_string_literals();
590                         }
591                         expect_void(')');
592                         break;
593                 default:
594                         goto attributes_finished;
595                 }
596         }
597
598 attributes_finished:
599         ;
600 }
601
602 typedef enum {
603         SPECIFIER_SIGNED    = 1 << 0,
604         SPECIFIER_UNSIGNED  = 1 << 1,
605         SPECIFIER_LONG      = 1 << 2,
606         SPECIFIER_INT       = 1 << 3,
607         SPECIFIER_DOUBLE    = 1 << 4,
608         SPECIFIER_CHAR      = 1 << 5,
609         SPECIFIER_SHORT     = 1 << 6,
610         SPECIFIER_LONG_LONG = 1 << 7,
611         SPECIFIER_FLOAT     = 1 << 8,
612         SPECIFIER_BOOL      = 1 << 9,
613         SPECIFIER_VOID      = 1 << 10,
614 #ifdef PROVIDE_COMPLEX
615         SPECIFIER_COMPLEX   = 1 << 11,
616 #endif
617 #ifdef PROVIDE_IMAGINARY
618         SPECIFIER_IMAGINARY = 1 << 12,
619 #endif
620 } specifiers_t;
621
622 #define STORAGE_CLASSES     \
623         case T_typedef:         \
624         case T_extern:          \
625         case T_static:          \
626         case T_auto:            \
627         case T_register:
628
629 #define TYPE_QUALIFIERS     \
630         case T_const:           \
631         case T_restrict:        \
632         case T_volatile:        \
633         case T_inline:
634
635 #ifdef PROVIDE_COMPLEX
636 #define COMPLEX_SPECIFIERS  \
637         case T__Complex:
638 #else
639 #define COMPLEX_SPECIFIERS
640 #endif
641
642 #ifdef PROVIDE_IMAGINARY
643 #define IMAGINARY_SPECIFIERS \
644         case T__Imaginary:
645 #else
646 #define IMAGINARY_SPECIFIERS
647 #endif
648
649 #define TYPE_SPECIFIERS     \
650         case T_void:            \
651         case T_char:            \
652         case T_short:           \
653         case T_int:             \
654         case T_long:            \
655         case T_float:           \
656         case T_double:          \
657         case T_signed:          \
658         case T_unsigned:        \
659         case T__Bool:           \
660         case T_struct:          \
661         case T_union:           \
662         case T_enum:            \
663         COMPLEX_SPECIFIERS      \
664         IMAGINARY_SPECIFIERS
665
666 #define DECLARATION_START   \
667         STORAGE_CLASSES         \
668         TYPE_QUALIFIERS         \
669         TYPE_SPECIFIERS
670
671 static
672 type_t *create_builtin_type(symbol_t *symbol)
673 {
674         builtin_type_t *type = allocate_type_zero(sizeof(type[0]));
675         type->type.type      = TYPE_BUILTIN;
676         type->symbol         = symbol;
677
678         type_t *result = typehash_insert((type_t*) type);
679         if(result != (type_t*) type) {
680                 obstack_free(type_obst, type);
681         }
682
683         return result;
684 }
685
686 static
687 void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
688 {
689         declaration_t *declaration;
690         type_t        *type            = NULL;
691         unsigned       type_qualifiers = 0;
692         unsigned       type_specifiers = 0;
693         int            newtype         = 0;
694
695         while(1) {
696                 switch(token.type) {
697
698                 /* storage class */
699 #define MATCH_STORAGE_CLASS(token, class)                                \
700                 case token:                                                      \
701                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
702                                 parse_error("multiple storage classes in declaration "   \
703                                             "specifiers");                               \
704                         }                                                            \
705                         specifiers->storage_class = class;                           \
706                         next_token();                                                \
707                         break;
708
709                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
710                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
711                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
712                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
713                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
714
715                 /* type qualifiers */
716 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
717                 case token:                                                     \
718                         type_qualifiers |= qualifier;                               \
719                         next_token();                                               \
720                         break;
721
722                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
723                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
724                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
725                 MATCH_TYPE_QUALIFIER(T_inline,   TYPE_QUALIFIER_INLINE);
726
727                 case T___extension__:
728                         /* TODO */
729                         next_token();
730                         break;
731
732                 /* type specifiers */
733 #define MATCH_SPECIFIER(token, specifier, name)                         \
734                 case token:                                                     \
735                         next_token();                                               \
736                         if(type_specifiers & specifier) {                           \
737                                 parse_error("multiple " name " type specifiers given"); \
738                         } else {                                                    \
739                                 type_specifiers |= specifier;                           \
740                         }                                                           \
741                         break;
742
743                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
744                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
745                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
746                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
747                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
748                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
749                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
750                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
751                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
752 #ifdef PROVIDE_COMPLEX
753                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
754 #endif
755 #ifdef PROVIDE_IMAGINARY
756                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
757 #endif
758                 case T_long:
759                         next_token();
760                         if(type_specifiers & SPECIFIER_LONG_LONG) {
761                                 parse_error("multiple type specifiers given");
762                         } else if(type_specifiers & SPECIFIER_LONG) {
763                                 type_specifiers |= SPECIFIER_LONG_LONG;
764                         } else {
765                                 type_specifiers |= SPECIFIER_LONG;
766                         }
767                         break;
768
769                 /* TODO: if type != NULL for the following rules issue an error */
770                 case T_struct:
771                         type = parse_compound_type_specifier(1);
772                         break;
773                 case T_union:
774                         type = parse_compound_type_specifier(0);
775                         break;
776                 case T_enum:
777                         type = parse_enum_specifier();
778                         break;
779                 case T___builtin_va_list:
780                         type = create_builtin_type(token.v.symbol);
781                         next_token();
782                         break;
783
784                 case T___attribute__:
785                         /* TODO */
786                         parse_attributes();
787                         break;
788
789                 case T_IDENTIFIER:
790                         declaration = token.v.symbol->declaration;
791                         if(declaration == NULL ||
792                                         declaration->storage_class != STORAGE_CLASS_TYPEDEF) {
793                                 goto finish_specifiers;
794                         }
795
796                         type = declaration->type;
797                         assert(type != NULL);
798                         next_token();
799                         break;
800
801                 /* function specifier */
802                 default:
803                         goto finish_specifiers;
804                 }
805         }
806
807 finish_specifiers:
808
809         if(type == NULL) {
810                 atomic_type_type_t atomic_type;
811
812                 /* match valid basic types */
813                 switch(type_specifiers) {
814                 case SPECIFIER_VOID:
815                         atomic_type = ATOMIC_TYPE_VOID;
816                         break;
817                 case SPECIFIER_CHAR:
818                         atomic_type = ATOMIC_TYPE_CHAR;
819                         break;
820                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
821                         atomic_type = ATOMIC_TYPE_SCHAR;
822                         break;
823                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
824                         atomic_type = ATOMIC_TYPE_UCHAR;
825                         break;
826                 case SPECIFIER_SHORT:
827                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
828                 case SPECIFIER_SHORT | SPECIFIER_INT:
829                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
830                         atomic_type = ATOMIC_TYPE_SHORT;
831                         break;
832                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
833                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
834                         atomic_type = ATOMIC_TYPE_USHORT;
835                         break;
836                 case SPECIFIER_INT:
837                 case SPECIFIER_SIGNED:
838                 case SPECIFIER_SIGNED | SPECIFIER_INT:
839                         atomic_type = ATOMIC_TYPE_INT;
840                         break;
841                 case SPECIFIER_UNSIGNED:
842                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
843                         atomic_type = ATOMIC_TYPE_UINT;
844                         break;
845                 case SPECIFIER_LONG:
846                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
847                 case SPECIFIER_LONG | SPECIFIER_INT:
848                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
849                         atomic_type = ATOMIC_TYPE_LONG;
850                         break;
851                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
852                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
853                         atomic_type = ATOMIC_TYPE_ULONG;
854                         break;
855                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
856                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
857                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
858                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
859                         | SPECIFIER_INT:
860                         atomic_type = ATOMIC_TYPE_LONGLONG;
861                         break;
862                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
863                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
864                         | SPECIFIER_INT:
865                         atomic_type = ATOMIC_TYPE_ULONGLONG;
866                         break;
867                 case SPECIFIER_FLOAT:
868                         atomic_type = ATOMIC_TYPE_FLOAT;
869                         break;
870                 case SPECIFIER_DOUBLE:
871                         atomic_type = ATOMIC_TYPE_DOUBLE;
872                         break;
873                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
874                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
875                         break;
876                 case SPECIFIER_BOOL:
877                         atomic_type = ATOMIC_TYPE_BOOL;
878                         break;
879 #ifdef PROVIDE_COMPLEX
880                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
881                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
882                         break;
883                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
884                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
885                         break;
886                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
887                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
888                         break;
889 #endif
890 #ifdef PROVIDE_IMAGINARY
891                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
892                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
893                         break;
894                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
895                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
896                         break;
897                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
898                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
899                         break;
900 #endif
901                 default:
902                         /* invalid specifier combination, give an error message */
903                         if(type_specifiers == 0) {
904                                 parse_error("no type specifiers given in declaration");
905                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
906                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
907                                 parse_error("signed and unsigned specifiers gives");
908                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
909                                 parse_error("only integer types can be signed or unsigned");
910                         } else {
911                                 parse_error("multiple datatypes in declaration");
912                         }
913                         atomic_type = ATOMIC_TYPE_INVALID;
914                 }
915
916                 atomic_type_t *atype = allocate_type_zero(sizeof(atype[0]));
917                 atype->type.type     = TYPE_ATOMIC;
918                 atype->atype         = atomic_type;
919                 newtype              = 1;
920
921                 type = (type_t*) atype;
922         } else {
923                 if(type_specifiers != 0) {
924                         parse_error("multiple datatypes in declaration");
925                 }
926         }
927
928         type->qualifiers = type_qualifiers;
929
930         type_t *result = typehash_insert(type);
931         if(newtype && result != (type_t*) type) {
932                 obstack_free(type_obst, type);
933         }
934
935         specifiers->type = result;
936 }
937
938 static
939 unsigned parse_type_qualifiers(void)
940 {
941         unsigned type_qualifiers = 0;
942
943         while(1) {
944                 switch(token.type) {
945                 /* type qualifiers */
946                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
947                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
948                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
949                 MATCH_TYPE_QUALIFIER(T_inline,   TYPE_QUALIFIER_INLINE);
950
951                 default:
952                         return type_qualifiers;
953                 }
954         }
955 }
956
957 typedef struct parsed_pointer_t parsed_pointer_t;
958 struct parsed_pointer_t {
959         unsigned          type_qualifiers;
960         parsed_pointer_t *next;
961 };
962
963 static
964 parsed_pointer_t *parse_pointers(void)
965 {
966         parsed_pointer_t *result       = NULL;
967         parsed_pointer_t *last_pointer = NULL;
968
969         while(token.type == '*') {
970                 next_token();
971                 parsed_pointer_t *pointer
972                         = obstack_alloc(&temp_obst, sizeof(pointer[0]));
973                 pointer->type_qualifiers = parse_type_qualifiers();
974
975                 if(last_pointer != NULL) {
976                         last_pointer->next = pointer;
977                 } else {
978                         result = pointer;
979                 }
980                 last_pointer = pointer;
981         }
982
983         return result;
984 }
985
986 static
987 type_t *make_pointers(type_t *type, parsed_pointer_t *pointer)
988 {
989         for( ; pointer != NULL; pointer = pointer->next) {
990                 pointer_type_t *pointer_type
991                         = allocate_type_zero(sizeof(pointer_type[0]));
992                 pointer_type->type.type       = TYPE_POINTER;
993                 pointer_type->points_to       = type;
994                 pointer_type->type.qualifiers = pointer->type_qualifiers;
995
996                 type_t *result = typehash_insert((type_t*) pointer_type);
997                 if(result != (type_t*) pointer_type) {
998                         obstack_free(type_obst, pointer_type);
999                 }
1000
1001                 type = result;
1002         }
1003
1004         return type;
1005 }
1006
1007 static
1008 void parse_identifier_list(void)
1009 {
1010         while(1) {
1011                 if(token.type != T_IDENTIFIER) {
1012                         parse_error_expected("problem while parsing parameter identifier "
1013                                              "list", T_IDENTIFIER, 0);
1014                         return;
1015                 }
1016                 next_token();
1017                 if(token.type != ',')
1018                         break;
1019                 next_token();
1020         }
1021 }
1022
1023 static
1024 declaration_t *parse_parameter(void)
1025 {
1026         declaration_specifiers_t specifiers;
1027         memset(&specifiers, 0, sizeof(specifiers));
1028
1029         parse_declaration_specifiers(&specifiers);
1030
1031         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
1032         parse_declarator(declaration, specifiers.storage_class,
1033                          specifiers.type, 1);
1034
1035         return declaration;
1036 }
1037
1038 static
1039 declaration_t *parse_parameters(method_type_t *type)
1040 {
1041         if(token.type == T_IDENTIFIER) {
1042                 symbol_t      *symbol      = token.v.symbol;
1043                 declaration_t *declaration = symbol->declaration;
1044                 if(declaration == NULL
1045                                 || declaration->storage_class != STORAGE_CLASS_TYPEDEF) {
1046                         /* TODO */
1047                         parse_identifier_list();
1048                         return NULL;
1049                 }
1050         }
1051
1052         if(token.type == ')') {
1053                 type->unspecified_parameters = 1;
1054                 return NULL;
1055         }
1056         if(token.type == T_void && look_ahead(1)->type == ')') {
1057                 next_token();
1058                 return NULL;
1059         }
1060
1061         declaration_t      *declarations = NULL;
1062         declaration_t      *declaration;
1063         declaration_t      *last_declaration = NULL;
1064         method_parameter_t *parameter;
1065         method_parameter_t *last_parameter = NULL;
1066
1067         while(1) {
1068                 switch(token.type) {
1069                 case T_DOTDOTDOT:
1070                         next_token();
1071                         type->variadic = 1;
1072                         return declarations;
1073
1074                 case T_IDENTIFIER:
1075                 case T___extension__:
1076                 DECLARATION_START
1077                         declaration = parse_parameter();
1078
1079                         parameter       = allocate_type_zero(sizeof(parameter[0]));
1080                         parameter->type = declaration->type;
1081
1082                         if(last_parameter != NULL) {
1083                                 last_declaration->next = declaration;
1084                                 last_parameter->next   = parameter;
1085                         } else {
1086                                 type->parameters = parameter;
1087                                 declarations     = declaration;
1088                         }
1089                         last_parameter   = parameter;
1090                         last_declaration = declaration;
1091                         break;
1092
1093                 default:
1094                         return declarations;
1095                 }
1096                 if(token.type != ',')
1097                         return declarations;
1098                 next_token();
1099         }
1100 }
1101
1102 typedef struct declarator_part declarator_part;
1103 struct declarator_part {
1104         parsed_pointer_t *pointers;
1105         method_type_t    *method_type;
1106         declarator_part  *inner;
1107 };
1108
1109
1110 static
1111 declarator_part *parse_inner_declarator(declaration_t *declaration,
1112                                         int may_be_abstract)
1113 {
1114         declarator_part *part = obstack_alloc(&temp_obst, sizeof(part[0]));
1115         memset(part, 0, sizeof(part[0]));
1116
1117         part->pointers = parse_pointers();
1118
1119         /* TODO: find out if this is correct */
1120         parse_attributes();
1121
1122         switch(token.type) {
1123         case T_IDENTIFIER:
1124                 if(declaration == NULL) {
1125                         parse_error("no identifier expected in typename");
1126                 } else {
1127                         declaration->symbol          = token.v.symbol;
1128                         declaration->source_position = token.source_position;
1129                 }
1130                 next_token();
1131                 break;
1132         case '(':
1133                 next_token();
1134                 part->inner = parse_inner_declarator(declaration, may_be_abstract);
1135                 expect(')');
1136                 break;
1137         default:
1138                 if(may_be_abstract)
1139                         break;
1140                 parse_error_expected("problem while parsing declarator", T_IDENTIFIER,
1141                                      '(', 0);
1142         }
1143
1144         while(1) {
1145                 switch(token.type) {
1146                 case '(':
1147                         next_token();
1148
1149                         method_type_t *method_type
1150                                 = allocate_type_zero(sizeof(method_type[0]));
1151                         method_type->type.type   = TYPE_METHOD;
1152
1153                         declaration_t *parameters = parse_parameters(method_type);
1154                         if(declaration != NULL) {
1155                                 declaration->context.declarations = parameters;
1156                         }
1157
1158                         part->method_type = method_type;
1159
1160                         expect(')');
1161                         break;
1162                 case '[':
1163                         next_token();
1164
1165                         if(token.type == T_static) {
1166                                 next_token();
1167                         }
1168
1169                         unsigned type_qualifiers = parse_type_qualifiers();
1170                         if(type_qualifiers != 0) {
1171                                 if(token.type == T_static) {
1172                                         next_token();
1173                                 }
1174                         }
1175
1176                         /* TODO */
1177
1178                         if(token.type == '*' && look_ahead(1)->type == ']') {
1179                                 next_token();
1180                         } else if(token.type != ']') {
1181                                 parse_assignment_expression();
1182                         }
1183
1184                         expect(']');
1185                         break;
1186                 default:
1187                         goto declarator_finished;
1188                 }
1189         }
1190
1191 declarator_finished:
1192         parse_attributes();
1193
1194         return part;
1195 }
1196
1197 static
1198 type_t *construct_declarator_type(declarator_part *part, type_t *type)
1199 {
1200         do {
1201                 type = make_pointers(type, part->pointers);
1202
1203                 method_type_t *method_type = part->method_type;
1204                 if(method_type != NULL) {
1205                         method_type->result_type = type;
1206
1207                         type_t *result = typehash_insert((type_t*) method_type);
1208                         if(result != (type_t*) method_type) {
1209                                 obstack_free(type_obst, method_type);
1210                         }
1211                         type = result;
1212                 }
1213
1214                 part = part->inner;
1215         } while(part != NULL);
1216
1217         return type;
1218 }
1219
1220 static
1221 void parse_declarator(declaration_t *declaration, storage_class_t storage_class,
1222                       type_t *type, int may_be_abstract)
1223 {
1224         declarator_part *part
1225                 = parse_inner_declarator(declaration, may_be_abstract);
1226
1227         if(part != NULL) {
1228                 declaration->type          = construct_declarator_type(part, type);
1229                 declaration->storage_class = storage_class;
1230                 obstack_free(&temp_obst, part);
1231         }
1232 }
1233
1234 static
1235 type_t *parse_abstract_declarator(type_t *base_type)
1236 {
1237         declarator_part *part = parse_inner_declarator(NULL, 1);
1238
1239         if(part == NULL)
1240                 return NULL;
1241
1242         type_t *result = construct_declarator_type(part, base_type);
1243         obstack_free(&temp_obst, part);
1244
1245         return result;
1246 }
1247
1248 static declaration_t *record_declaration(declaration_t *declaration)
1249 {
1250         if(context == NULL)
1251                 return declaration;
1252
1253         symbol_t *symbol = declaration->symbol;
1254         if(symbol != NULL) {
1255                 declaration_t *alias = environment_push(declaration, context);
1256                 if(alias != declaration)
1257                         return alias;
1258         }
1259
1260         if(last_declaration != NULL) {
1261                 last_declaration->next = declaration;
1262         } else {
1263                 context->declarations  = declaration;
1264         }
1265         last_declaration = declaration;
1266
1267         return declaration;
1268 }
1269
1270 static
1271 void parser_error_multiple_definition(declaration_t *previous,
1272                                       declaration_t *declaration)
1273 {
1274         parser_print_error_prefix_pos(declaration->source_position);
1275         fprintf(stderr, "multiple definition of symbol '%s'\n",
1276                 declaration->symbol->string);
1277         parser_print_error_prefix_pos(previous->source_position);
1278         fprintf(stderr, "this is the location of the previous "
1279                 "definition.\n");
1280 }
1281
1282 static
1283 void parse_init_declarators(const declaration_specifiers_t *specifiers)
1284 {
1285         while(1) {
1286                 declaration_t *ndeclaration
1287                         = allocate_ast_zero(sizeof(ndeclaration[0]));
1288
1289                 parse_declarator(ndeclaration, specifiers->storage_class,
1290                                  specifiers->type, 0);
1291                 declaration_t *declaration = record_declaration(ndeclaration);
1292                 if(token.type == '=') {
1293                         next_token();
1294
1295                         /* TODO: check that this is an allowed type (esp. no method type) */
1296
1297                         if(declaration->initializer != NULL) {
1298                                 parser_error_multiple_definition(declaration, ndeclaration);
1299                         }
1300
1301                         if(token.type == '{') {
1302                                 // TODO
1303                                 expect_void('}');
1304                         } else {
1305                                 declaration->initializer = parse_assignment_expression();
1306                         }
1307                 } else if(token.type == '{') {
1308                         if(declaration->type->type != TYPE_METHOD) {
1309                                 parser_print_error_prefix();
1310                                 fprintf(stderr, "Declarator ");
1311                                 print_type_ext(declaration->type, declaration->symbol, NULL);
1312                                 fprintf(stderr, " is not a method type.\n");
1313                         }
1314
1315                         if(declaration->initializer != NULL) {
1316                                 parser_error_multiple_definition(declaration, ndeclaration);
1317                         }
1318
1319                         int         top          = environment_top();
1320                         context_t  *last_context = context;
1321                         set_context(&declaration->context);
1322
1323                         /* push function parameters */
1324                         declaration_t *parameter = declaration->context.declarations;
1325                         for( ; parameter != NULL; parameter = parameter->next) {
1326                                 environment_push(parameter, context);
1327                         }
1328
1329                         statement_t *statement = parse_compound_statement();
1330
1331                         assert(context == &declaration->context);
1332                         set_context(last_context);
1333                         environment_pop_to(top);
1334
1335                         declaration->statement = statement;
1336                         return;
1337                 }
1338
1339                 if(token.type != ',')
1340                         break;
1341                 next_token();
1342         }
1343         expect_void(';');
1344 }
1345
1346 static
1347 void parse_struct_declarators(const declaration_specifiers_t *specifiers)
1348 {
1349         while(1) {
1350                 if(token.type == ':') {
1351                         next_token();
1352                         parse_constant_expression();
1353                         /* TODO (bitfields) */
1354                 } else {
1355                         declaration_t *declaration
1356                                 = allocate_ast_zero(sizeof(declaration[0]));
1357                         parse_declarator(declaration, specifiers->storage_class,
1358                                          specifiers->type, 1);
1359
1360                         /* TODO: check for doubled fields */
1361                         record_declaration(declaration);
1362
1363                         if(token.type == ':') {
1364                                 next_token();
1365                                 parse_constant_expression();
1366                                 /* TODO (bitfields) */
1367                         }
1368                 }
1369
1370                 if(token.type != ',')
1371                         break;
1372                 next_token();
1373         }
1374         expect_void(';');
1375 }
1376
1377 static void parse_compound_type_entries(void)
1378 {
1379         eat('{');
1380
1381         while(token.type != '}' && token.type != T_EOF) {
1382                 declaration_specifiers_t specifiers;
1383                 memset(&specifiers, 0, sizeof(specifiers));
1384                 /* TODO not correct as this allows storage class stuff... but only
1385                  * specifiers and qualifiers sould be allowed here */
1386                 parse_declaration_specifiers(&specifiers);
1387
1388                 parse_struct_declarators(&specifiers);
1389         }
1390         if(token.type == T_EOF) {
1391                 parse_error("unexpected error while parsing struct");
1392         }
1393         next_token();
1394 }
1395
1396 void parse_declaration(void)
1397 {
1398         declaration_specifiers_t specifiers;
1399         memset(&specifiers, 0, sizeof(specifiers));
1400         parse_declaration_specifiers(&specifiers);
1401
1402         if(token.type == ';') {
1403                 next_token();
1404                 return;
1405         }
1406         parse_init_declarators(&specifiers);
1407 }
1408
1409 type_t *parse_typename(void)
1410 {
1411         declaration_specifiers_t specifiers;
1412         memset(&specifiers, 0, sizeof(specifiers));
1413         parse_declaration_specifiers(&specifiers);
1414         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
1415                 /* TODO: improve error message, user does probably not know what a
1416                  * storage class is...
1417                  */
1418                 parse_error("typename may not have a storage class");
1419         }
1420
1421         type_t *result = parse_abstract_declarator(specifiers.type);
1422
1423         return result;
1424 }
1425
1426
1427
1428
1429 typedef expression_t* (*parse_expression_function) (unsigned precedence);
1430 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
1431                                                           expression_t *left);
1432
1433 typedef struct expression_parser_function_t expression_parser_function_t;
1434 struct expression_parser_function_t {
1435         unsigned                         precedence;
1436         parse_expression_function        parser;
1437         unsigned                         infix_precedence;
1438         parse_expression_infix_function  infix_parser;
1439 };
1440
1441 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
1442
1443 static
1444 expression_t *expected_expression_error(void)
1445 {
1446         parser_print_error_prefix();
1447         fprintf(stderr, "expected expression, got token ");
1448         print_token(stderr, & token);
1449         fprintf(stderr, "\n");
1450
1451         expression_t *expression = allocate_ast_zero(sizeof(expression[0]));
1452         expression->type = EXPR_INVALID;
1453         next_token();
1454
1455         return expression;
1456 }
1457
1458 static
1459 expression_t *parse_string_const(void)
1460 {
1461         string_literal_t *cnst = allocate_ast_zero(sizeof(cnst[0]));
1462
1463         cnst->expression.type = EXPR_STRING_LITERAL;
1464         cnst->value           = parse_string_literals();
1465
1466         return (expression_t*) cnst;
1467 }
1468
1469 static
1470 expression_t *parse_int_const(void)
1471 {
1472         const_t *cnst = allocate_ast_zero(sizeof(cnst[0]));
1473
1474         cnst->expression.type = EXPR_CONST;
1475         cnst->value           = token.v.intvalue;
1476
1477         next_token();
1478
1479         return (expression_t*) cnst;
1480 }
1481
1482 static
1483 expression_t *parse_reference(void)
1484 {
1485         reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0]));
1486
1487         ref->expression.type = EXPR_REFERENCE;
1488         ref->symbol          = token.v.symbol;
1489
1490         if(ref->symbol->declaration == NULL) {
1491                 parser_print_error_prefix();
1492                 fprintf(stderr, "unknown symbol '%s' found.\n", ref->symbol->string);
1493         }
1494         ref->declaration     = ref->symbol->declaration;
1495
1496         next_token();
1497
1498         return (expression_t*) ref;
1499 }
1500
1501 static
1502 expression_t *parse_cast(void)
1503 {
1504         unary_expression_t *cast = allocate_ast_zero(sizeof(cast[0]));
1505
1506         cast->expression.type            = EXPR_UNARY;
1507         cast->type                       = UNEXPR_CAST;
1508         cast->expression.source_position = token.source_position;
1509
1510         type_t *type  = parse_typename();
1511
1512         expect(')');
1513         expression_t *value = parse_sub_expression(20);
1514
1515         cast->expression.datatype = type;
1516         cast->value               = value;
1517
1518         return (expression_t*) cast;
1519 }
1520
1521 static
1522 expression_t *parse_statement_expression(void)
1523 {
1524         statement_expression_t *expression
1525                 = allocate_ast_zero(sizeof(expression[0]));
1526         expression->expression.type = EXPR_STATEMENT;
1527         expression->statement       = parse_compound_statement();
1528
1529         expect(')');
1530
1531         return (expression_t*) expression;
1532 }
1533
1534 static
1535 expression_t *parse_brace_expression(void)
1536 {
1537         eat('(');
1538
1539         declaration_t *declaration;
1540         switch(token.type) {
1541         case '{':
1542                 /* gcc extension: a stement expression */
1543                 return parse_statement_expression();
1544
1545         TYPE_QUALIFIERS
1546         TYPE_SPECIFIERS
1547                 return parse_cast();
1548         case T_IDENTIFIER:
1549                 declaration = token.v.symbol->declaration;
1550                 if(declaration != NULL &&
1551                                 (declaration->storage_class == STORAGE_CLASS_TYPEDEF)) {
1552                         return parse_cast();
1553                 }
1554         }
1555
1556         expression_t *result = parse_expression();
1557         expect(')');
1558
1559         return result;
1560 }
1561
1562 static
1563 expression_t *parse_function_keyword(void)
1564 {
1565         eat(T___FUNCTION__);
1566         /* TODO */
1567
1568         string_literal_t *expression = allocate_ast_zero(sizeof(expression[0]));
1569         expression->expression.type  = EXPR_FUNCTION;
1570         expression->value            = "TODO: FUNCTION";
1571
1572         return (expression_t*) expression;
1573 }
1574
1575 static
1576 expression_t *parse_pretty_function_keyword(void)
1577 {
1578         eat(T___PRETTY_FUNCTION__);
1579         /* TODO */
1580
1581         string_literal_t *expression = allocate_ast_zero(sizeof(expression[0]));
1582         expression->expression.type  = EXPR_PRETTY_FUNCTION;
1583         expression->value            = "TODO: PRETTY FUNCTION";
1584
1585         return (expression_t*) expression;
1586 }
1587
1588 static
1589 expression_t *parse_primary_expression(void)
1590 {
1591         switch(token.type) {
1592         case T_INTEGER:
1593                 return parse_int_const();
1594         case T_STRING_LITERAL:
1595                 return parse_string_const();
1596         case T_IDENTIFIER:
1597                 return parse_reference();
1598         case T___FUNCTION__:
1599                 return parse_function_keyword();
1600         case T___PRETTY_FUNCTION__:
1601                 return parse_pretty_function_keyword();
1602         case '(':
1603                 return parse_brace_expression();
1604         }
1605
1606         parser_print_error_prefix();
1607         fprintf(stderr, "unexpected token ");
1608         print_token(stderr, &token);
1609         fprintf(stderr, "\n");
1610         eat_statement();
1611         return NULL;
1612 }
1613
1614 static
1615 expression_t *parse_array_expression(unsigned precedence,
1616                                      expression_t *array_ref)
1617 {
1618         (void) precedence;
1619
1620         eat('[');
1621
1622         array_access_expression_t *array_access
1623                 = allocate_ast_zero(sizeof(array_access[0]));
1624
1625         array_access->expression.type = EXPR_ARRAY_ACCESS;
1626         array_access->array_ref       = array_ref;
1627         array_access->index           = parse_expression();
1628
1629         if(token.type != ']') {
1630                 parse_error_expected("Problem while parsing array access", ']', 0);
1631                 return NULL;
1632         }
1633         next_token();
1634
1635         return (expression_t*) array_access;
1636 }
1637
1638 static
1639 type_t *get_expression_type(const expression_t *expression)
1640 {
1641         (void) expression;
1642         /* TODO */
1643         return NULL;
1644 }
1645
1646 static
1647 int is_declaration_specifier(const token_t *token, int only_type_specifiers)
1648 {
1649         declaration_t *declaration;
1650
1651         switch(token->type) {
1652                 TYPE_SPECIFIERS
1653                         return 1;
1654                 case T_IDENTIFIER:
1655                         declaration = token->v.symbol->declaration;
1656                         if(declaration == NULL)
1657                                 return 0;
1658                         if(declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1659                                 return 0;
1660                         return 1;
1661                 STORAGE_CLASSES
1662                 TYPE_QUALIFIERS
1663                         if(only_type_specifiers)
1664                                 return 0;
1665                         return 1;
1666
1667                 default:
1668                         return 0;
1669         }
1670 }
1671
1672 static
1673 expression_t *parse_sizeof(unsigned precedence)
1674 {
1675         eat(T_sizeof);
1676
1677         sizeof_expression_t *sizeof_expression
1678                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
1679         sizeof_expression->expression.type = EXPR_SIZEOF;
1680
1681         if(token.type == '(' && is_declaration_specifier(look_ahead(1), 1)) {
1682                 next_token();
1683                 sizeof_expression->type = parse_typename();
1684                 expect(')');
1685         } else {
1686                 expression_t *expression           = parse_sub_expression(precedence);
1687                 sizeof_expression->type            = get_expression_type(expression);
1688                 sizeof_expression->size_expression = expression;
1689         }
1690
1691         return (expression_t*) sizeof_expression;
1692 }
1693
1694 static
1695 expression_t *parse_select_expression(unsigned precedence,
1696                                       expression_t *compound)
1697 {
1698         (void) precedence;
1699
1700         assert(token.type == '.' || token.type == T_MINUSGREATER);
1701         next_token();
1702
1703         select_expression_t *select = allocate_ast_zero(sizeof(select[0]));
1704
1705         select->expression.type = EXPR_SELECT;
1706         select->compound        = compound;
1707
1708         if(token.type != T_IDENTIFIER) {
1709                 parse_error_expected("Problem while parsing compound select",
1710                                      T_IDENTIFIER, 0);
1711                 return NULL;
1712         }
1713         select->symbol = token.v.symbol;
1714         next_token();
1715
1716         return (expression_t*) select;
1717 }
1718
1719 static
1720 expression_t *parse_call_expression(unsigned precedence,
1721                                     expression_t *expression)
1722 {
1723         (void) precedence;
1724         call_expression_t *call = allocate_ast_zero(sizeof(call[0]));
1725
1726         call->expression.type            = EXPR_CALL;
1727         call->method                     = expression;
1728
1729         /* parse arguments */
1730         eat('(');
1731
1732         if(token.type != ')') {
1733                 call_argument_t *last_argument = NULL;
1734
1735                 while(1) {
1736                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
1737
1738                         /* we start parsing at precedence 2 so we don't get comma operators
1739                          * parsed */
1740                         argument->expression = parse_sub_expression(2);
1741                         if(last_argument == NULL) {
1742                                 call->arguments = argument;
1743                         } else {
1744                                 last_argument->next = argument;
1745                         }
1746                         last_argument = argument;
1747
1748                         if(token.type != ',')
1749                                 break;
1750                         next_token();
1751                 }
1752         }
1753         expect(')');
1754
1755         return (expression_t*) call;
1756 }
1757
1758 static
1759 expression_t *parse_conditional_expression(unsigned precedence,
1760                                            expression_t *expression)
1761 {
1762         eat('?');
1763
1764         conditional_expression_t *conditional
1765                 = allocate_ast_zero(sizeof(conditional[0]));
1766         conditional->condition = expression;
1767
1768         conditional->true_expression = parse_expression();
1769         expect(':');
1770         conditional->false_expression = parse_sub_expression(precedence);
1771
1772         return (expression_t*) conditional;
1773 }
1774
1775 static expression_t *parse_extension(unsigned precedence)
1776 {
1777         eat(T___extension__);
1778
1779         /* TODO enable extensions */
1780
1781         return parse_sub_expression(precedence);
1782 }
1783
1784 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type)     \
1785 static                                                                    \
1786 expression_t *parse_##unexpression_type(unsigned precedence)              \
1787 {                                                                         \
1788         eat(token_type);                                                      \
1789                                                                           \
1790         unary_expression_t *unary_expression                                  \
1791                 = allocate_ast_zero(sizeof(unary_expression[0]));                 \
1792         unary_expression->expression.type = EXPR_UNARY;                       \
1793         unary_expression->type            = unexpression_type;                \
1794         unary_expression->value           = parse_sub_expression(precedence); \
1795                                                                           \
1796         return (expression_t*) unary_expression;                              \
1797 }
1798
1799 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE)
1800 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS)
1801 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT)
1802 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE)
1803 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS)
1804 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE)
1805 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT)
1806 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT)
1807
1808 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type) \
1809 static                                                                        \
1810 expression_t *parse_##unexpression_type(unsigned precedence,                  \
1811                                         expression_t *left)                   \
1812 {                                                                             \
1813         (void) precedence;                                                        \
1814         eat(token_type);                                                          \
1815                                                                               \
1816         unary_expression_t *unary_expression                                      \
1817                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
1818         unary_expression->expression.type = EXPR_UNARY;                           \
1819         unary_expression->type            = unexpression_type;                    \
1820         unary_expression->value           = left;                                 \
1821                                                                               \
1822         return (expression_t*) unary_expression;                                  \
1823 }
1824
1825 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT)
1826 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT)
1827
1828 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type)    \
1829 static                                                           \
1830 expression_t *parse_##binexpression_type(unsigned precedence,    \
1831                                          expression_t *left)     \
1832 {                                                                \
1833         eat(token_type);                                             \
1834                                                                  \
1835         expression_t *right = parse_sub_expression(precedence);      \
1836                                                                  \
1837         binary_expression_t *binexpr                                 \
1838                 = allocate_ast_zero(sizeof(binexpr[0]));                 \
1839         binexpr->expression.type = EXPR_BINARY;                      \
1840         binexpr->type            = binexpression_type;               \
1841         binexpr->left            = left;                             \
1842         binexpr->right           = right;                            \
1843                                                                  \
1844         return (expression_t*) binexpr;                              \
1845 }
1846
1847 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA)
1848 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL)
1849 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV)
1850 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD)
1851 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB)
1852 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS)
1853 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER)
1854 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN)
1855 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL)
1856 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL)
1857 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL)
1858 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL)
1859 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND)
1860 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR)
1861 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR)
1862 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND)
1863 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR)
1864 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT)
1865 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT)
1866 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN)
1867 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN)
1868 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN)
1869 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN)
1870 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN)
1871 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN)
1872 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN)
1873 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN)
1874 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN)
1875 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN)
1876
1877 static
1878 expression_t *parse_sub_expression(unsigned precedence)
1879 {
1880         if(token.type < 0) {
1881                 return expected_expression_error();
1882         }
1883
1884         expression_parser_function_t *parser
1885                 = &expression_parsers[token.type];
1886         source_position_t             source_position = token.source_position;
1887         expression_t                 *left;
1888
1889         if(parser->parser != NULL) {
1890                 left = parser->parser(parser->precedence);
1891         } else {
1892                 left = parse_primary_expression();
1893         }
1894         if(left != NULL)
1895                 left->source_position = source_position;
1896
1897         while(1) {
1898                 if(token.type < 0) {
1899                         return expected_expression_error();
1900                 }
1901
1902                 parser = &expression_parsers[token.type];
1903                 if(parser->infix_parser == NULL)
1904                         break;
1905                 if(parser->infix_precedence < precedence)
1906                         break;
1907
1908                 left = parser->infix_parser(parser->infix_precedence, left);
1909                 if(left != NULL)
1910                         left->source_position = source_position;
1911         }
1912
1913         return left;
1914 }
1915
1916 static
1917 expression_t *parse_expression(void)
1918 {
1919         return parse_sub_expression(1);
1920 }
1921
1922
1923
1924 void register_expression_parser(parse_expression_function parser,
1925                                 int token_type, unsigned precedence)
1926 {
1927         expression_parser_function_t *entry = &expression_parsers[token_type];
1928
1929         if(entry->parser != NULL) {
1930                 fprintf(stderr, "for token ");
1931                 print_token_type(stderr, token_type);
1932                 fprintf(stderr, "\n");
1933                 panic("trying to register multiple expression parsers for a token");
1934         }
1935         entry->parser     = parser;
1936         entry->precedence = precedence;
1937 }
1938
1939 void register_expression_infix_parser(parse_expression_infix_function parser,
1940                                       int token_type, unsigned precedence)
1941 {
1942         expression_parser_function_t *entry = &expression_parsers[token_type];
1943
1944         if(entry->infix_parser != NULL) {
1945                 fprintf(stderr, "for token ");
1946                 print_token_type(stderr, token_type);
1947                 fprintf(stderr, "\n");
1948                 panic("trying to register multiple infix expression parsers for a "
1949                       "token");
1950         }
1951         entry->infix_parser     = parser;
1952         entry->infix_precedence = precedence;
1953 }
1954
1955 static
1956 void init_expression_parsers(void)
1957 {
1958         memset(&expression_parsers, 0, sizeof(expression_parsers));
1959
1960         register_expression_infix_parser(parse_BINEXPR_MUL,       '*', 16);
1961         register_expression_infix_parser(parse_BINEXPR_DIV,       '/', 16);
1962         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,
1963                                    T_LESSLESS, 16);
1964         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
1965                                    T_GREATERGREATER, 16);
1966         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
1967         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
1968         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
1969         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
1970         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
1971         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
1972                                                                 T_GREATEREQUAL, 14);
1973         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
1974         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
1975                                                         T_EXCLAMATIONMARKEQUAL, 13);
1976         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
1977         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
1978         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
1979         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
1980         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
1981         register_expression_infix_parser(parse_conditional_expression, '?',      7);
1982         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
1983         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
1984         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
1985         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
1986                                                                 T_ASTERISKEQUAL, 2);
1987         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
1988         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
1989                                                                  T_PERCENTEQUAL, 2);
1990         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
1991                                                                 T_LESSLESSEQUAL, 2);
1992         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
1993                                                           T_GREATERGREATEREQUAL, 2);
1994         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
1995                                                                      T_ANDEQUAL, 2);
1996         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
1997                                                                     T_PIPEEQUAL, 2);
1998         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
1999                                                                    T_CARETEQUAL, 2);
2000
2001         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
2002
2003         register_expression_infix_parser(parse_array_expression,        '[',    30);
2004         register_expression_infix_parser(parse_call_expression,         '(',    30);
2005         register_expression_infix_parser(parse_select_expression,       '.',    30);
2006         register_expression_infix_parser(parse_select_expression,
2007                                                                 T_MINUSGREATER, 30);
2008         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
2009                                          T_PLUSPLUS, 30);
2010         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
2011                                          T_MINUSMINUS, 30);
2012
2013         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
2014         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
2015         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
2016         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
2017         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
2018         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
2019         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
2020         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
2021         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
2022         register_expression_parser(parse_extension,            T___extension__, 25);
2023 }
2024
2025
2026 static
2027 statement_t *parse_case_statement(void)
2028 {
2029         eat(T_case);
2030         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
2031         label->statement.type            = STATEMENT_CASE_LABEL;
2032         label->statement.source_position = token.source_position;
2033
2034         label->expression = parse_expression();
2035
2036         expect(':');
2037         label->statement.next = parse_statement();
2038
2039         return (statement_t*) label;
2040 }
2041
2042 static
2043 statement_t *parse_default_statement(void)
2044 {
2045         eat(T_default);
2046
2047         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
2048         label->statement.type            = STATEMENT_CASE_LABEL;
2049         label->statement.source_position = token.source_position;
2050
2051         expect(':');
2052         label->statement.next = parse_statement();
2053
2054         return (statement_t*) label;
2055 }
2056
2057 static
2058 statement_t *parse_label_statement(void)
2059 {
2060         eat(T_IDENTIFIER);
2061         expect(':');
2062         parse_statement();
2063
2064         return NULL;
2065 }
2066
2067 static
2068 statement_t *parse_if(void)
2069 {
2070         eat(T_if);
2071
2072         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2073         statement->statement.type            = STATEMENT_IF;
2074         statement->statement.source_position = token.source_position;
2075
2076         expect('(');
2077         statement->condition = parse_expression();
2078         expect(')');
2079
2080         statement->true_statement = parse_statement();
2081         if(token.type == T_else) {
2082                 next_token();
2083                 statement->false_statement = parse_statement();
2084         }
2085
2086         return (statement_t*) statement;
2087 }
2088
2089 static
2090 statement_t *parse_switch(void)
2091 {
2092         eat(T_switch);
2093
2094         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2095         statement->statement.type            = STATEMENT_SWITCH;
2096         statement->statement.source_position = token.source_position;
2097
2098         expect('(');
2099         statement->expression = parse_expression();
2100         expect(')');
2101         statement->body = parse_statement();
2102
2103         return (statement_t*) statement;
2104 }
2105
2106 static
2107 statement_t *parse_while(void)
2108 {
2109         eat(T_while);
2110
2111         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2112         statement->statement.type            = STATEMENT_WHILE;
2113         statement->statement.source_position = token.source_position;
2114
2115         expect('(');
2116         statement->condition = parse_expression();
2117         expect(')');
2118         statement->body = parse_statement();
2119
2120         return (statement_t*) statement;
2121 }
2122
2123 static
2124 statement_t *parse_do(void)
2125 {
2126         eat(T_do);
2127
2128         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2129         statement->statement.type            = STATEMENT_DO_WHILE;
2130         statement->statement.source_position = token.source_position;
2131
2132         statement->body = parse_statement();
2133         expect(T_while);
2134         expect('(');
2135         statement->condition = parse_expression();
2136         expect(')');
2137         expect(';');
2138
2139         return (statement_t*) statement;
2140 }
2141
2142 static
2143 statement_t *parse_for(void)
2144 {
2145         eat(T_for);
2146
2147         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2148         statement->statement.type            = STATEMENT_FOR;
2149         statement->statement.source_position = token.source_position;
2150
2151         expect('(');
2152
2153         int         top          = environment_top();
2154         context_t  *last_context = context;
2155         set_context(&statement->context);
2156
2157         if(token.type != ';') {
2158                 if(is_declaration_specifier(&token, 0)) {
2159                         parse_declaration();
2160                 } else {
2161                         statement->initialisation = parse_expression();
2162                         expect(';');
2163                 }
2164         } else {
2165                 expect(';');
2166         }
2167
2168         if(token.type != ';') {
2169                 statement->condition = parse_expression();
2170         }
2171         expect(';');
2172         if(token.type != ')') {
2173                 statement->step = parse_expression();
2174         }
2175         expect(')');
2176         statement->body = parse_statement();
2177
2178         assert(context == &statement->context);
2179         set_context(last_context);
2180         environment_pop_to(top);
2181
2182         return (statement_t*) statement;
2183 }
2184
2185 static
2186 statement_t *parse_goto(void)
2187 {
2188         eat(T_goto);
2189         expect(T_IDENTIFIER);
2190         expect(';');
2191
2192         return NULL;
2193 }
2194
2195 static
2196 statement_t *parse_continue(void)
2197 {
2198         eat(T_continue);
2199         expect(';');
2200
2201         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
2202         statement->source_position = token.source_position;
2203         statement->type            = STATEMENT_CONTINUE;
2204
2205         return statement;
2206 }
2207
2208 static
2209 statement_t *parse_break(void)
2210 {
2211         eat(T_break);
2212         expect(';');
2213
2214         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
2215         statement->source_position = token.source_position;
2216         statement->type            = STATEMENT_BREAK;
2217
2218         return statement;
2219 }
2220
2221 static
2222 statement_t *parse_return(void)
2223 {
2224         eat(T_return);
2225
2226         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2227
2228         statement->statement.type            = STATEMENT_RETURN;
2229         statement->statement.source_position = token.source_position;
2230         if(token.type != ';') {
2231                 statement->return_value = parse_expression();
2232         }
2233         expect(';');
2234
2235         return (statement_t*) statement;
2236 }
2237
2238 static
2239 statement_t *parse_declaration_statement(void)
2240 {
2241         declaration_t *before = last_declaration;
2242
2243         declaration_statement_t *statement
2244                 = allocate_ast_zero(sizeof(statement[0]));
2245         statement->statement.type            = STATEMENT_DECLARATION;
2246         statement->statement.source_position = token.source_position;
2247
2248         declaration_specifiers_t specifiers;
2249         memset(&specifiers, 0, sizeof(specifiers));
2250         parse_declaration_specifiers(&specifiers);
2251
2252         if(token.type == ';') {
2253                 eat(';');
2254         } else {
2255                 parse_init_declarators(&specifiers);
2256         }
2257
2258         if(before == NULL) {
2259                 statement->declarations_begin = context->declarations;
2260         } else {
2261                 statement->declarations_begin = before->next;
2262         }
2263         statement->declarations_end = last_declaration;
2264
2265         return (statement_t*) statement;
2266 }
2267
2268 static
2269 statement_t *parse_expression_statement(void)
2270 {
2271         expression_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
2272         statement->statement.type            = STATEMENT_EXPRESSION;
2273         statement->statement.source_position = token.source_position;
2274
2275         statement->expression = parse_expression();
2276
2277         expect(';');
2278
2279         return (statement_t*) statement;
2280 }
2281
2282 static
2283 statement_t *parse_statement(void)
2284 {
2285         declaration_t *declaration;
2286         statement_t   *statement = NULL;
2287
2288         /* declaration or statement */
2289         switch(token.type) {
2290         case T_case:
2291                 statement = parse_case_statement();
2292                 break;
2293
2294         case T_default:
2295                 statement = parse_default_statement();
2296                 break;
2297
2298         case '{':
2299                 statement = parse_compound_statement();
2300                 break;
2301
2302         case T_if:
2303                 statement = parse_if();
2304                 break;
2305
2306         case T_switch:
2307                 statement = parse_switch();
2308                 break;
2309
2310         case T_while:
2311                 statement = parse_while();
2312                 break;
2313
2314         case T_do:
2315                 statement = parse_do();
2316                 break;
2317
2318         case T_for:
2319                 statement = parse_for();
2320                 break;
2321
2322         case T_goto:
2323                 statement = parse_goto();
2324                 break;
2325
2326         case T_continue:
2327                 statement = parse_continue();
2328                 break;
2329
2330         case T_break:
2331                 statement = parse_break();
2332                 break;
2333
2334         case T_return:
2335                 statement = parse_return();
2336                 break;
2337
2338         case ';':
2339                 next_token();
2340                 statement = NULL;
2341                 break;
2342
2343         case T_IDENTIFIER:
2344                 if(look_ahead(1)->type == ':') {
2345                         statement = parse_label_statement();
2346                         break;
2347                 }
2348
2349                 declaration = token.v.symbol->declaration;
2350                 if(declaration != NULL &&
2351                                 declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
2352                         statement = parse_declaration_statement();
2353                         break;
2354                 }
2355
2356                 statement = parse_expression_statement();
2357                 break;
2358
2359         case T___extension__:
2360                 /* this can be a prefix to a declaration or an expression statement */
2361                 /* we simply eat it now and parse the rest with tail recursion */
2362                 do {
2363                         next_token();
2364                 } while(token.type == T___extension__);
2365                 statement = parse_statement();
2366                 break;
2367
2368         DECLARATION_START
2369                 statement = parse_declaration_statement();
2370                 break;
2371
2372         default:
2373                 statement = parse_expression_statement();
2374                 break;
2375         }
2376
2377         assert(statement == NULL || statement->source_position.input_name != NULL);
2378
2379         return statement;
2380 }
2381
2382 static
2383 statement_t *parse_compound_statement(void)
2384 {
2385         eat('{');
2386
2387         compound_statement_t *compound_statement
2388                 = allocate_ast_zero(sizeof(compound_statement[0]));
2389         compound_statement->statement.type            = STATEMENT_COMPOUND;
2390         compound_statement->statement.source_position = token.source_position;
2391
2392         int        top          = environment_top();
2393         context_t *last_context = context;
2394         set_context(&compound_statement->context);
2395
2396         statement_t *last_statement = NULL;
2397
2398         while(token.type != '}' && token.type != T_EOF) {
2399                 statement_t *statement = parse_statement();
2400                 if(statement == NULL)
2401                         continue;
2402
2403                 if(last_statement != NULL) {
2404                         last_statement->next = statement;
2405                 } else {
2406                         compound_statement->statements = statement;
2407                 }
2408
2409                 while(statement->next != NULL)
2410                         statement = statement->next;
2411
2412                 last_statement = statement;
2413         }
2414
2415         assert(context == &compound_statement->context);
2416         set_context(last_context);
2417         environment_pop_to(top);
2418
2419         next_token();
2420
2421         return (statement_t*) compound_statement;
2422 }
2423
2424 static
2425 translation_unit_t *parse_translation_unit(void)
2426 {
2427         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
2428
2429         assert(context == NULL);
2430         set_context(&unit->context);
2431
2432         while(token.type != T_EOF) {
2433                 parse_declaration();
2434         }
2435
2436         assert(context == &unit->context);
2437         context          = NULL;
2438         last_declaration = NULL;
2439
2440         return unit;
2441 }
2442
2443 translation_unit_t *parse(void)
2444 {
2445         obstack_init(&environment_obstack);
2446         environment_stack = NEW_ARR_F(environment_entry_t*, 0);
2447
2448         type_set_output(stderr);
2449
2450         lookahead_bufpos = 0;
2451         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
2452                 next_token();
2453         }
2454         translation_unit_t *unit = parse_translation_unit();
2455
2456         DEL_ARR_F(environment_stack);
2457         obstack_free(&environment_obstack, NULL);
2458
2459         return unit;
2460 }
2461
2462 void init_parser(void)
2463 {
2464         init_expression_parsers();
2465         obstack_init(&temp_obst);
2466 }
2467
2468 void exit_parser(void)
2469 {
2470         obstack_free(&temp_obst, NULL);
2471 }