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