5ad72c2b770ed0dc4a12416ea049842c0bafcda5
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "diagnostic.h"
8 #include "format_check.h"
9 #include "parser.h"
10 #include "lexer.h"
11 #include "token_t.h"
12 #include "types.h"
13 #include "type_t.h"
14 #include "type_hash.h"
15 #include "ast_t.h"
16 #include "adt/bitfiddle.h"
17 #include "adt/error.h"
18 #include "adt/array.h"
19
20 //#define PRINT_TOKENS
21 //#define ABORT_ON_ERROR
22 #define MAX_LOOKAHEAD 2
23 //#define STRICT_C99
24
25 typedef struct {
26         declaration_t *old_declaration;
27         symbol_t      *symbol;
28         unsigned short namespc;
29 } stack_entry_t;
30
31 typedef struct declaration_specifiers_t  declaration_specifiers_t;
32 struct declaration_specifiers_t {
33         source_position_t  source_position;
34         unsigned char      storage_class;
35         bool               is_inline;
36         decl_modifiers_t   decl_modifiers;
37         type_t            *type;
38 };
39
40 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
41
42 static token_t         token;
43 static token_t         lookahead_buffer[MAX_LOOKAHEAD];
44 static int             lookahead_bufpos;
45 static stack_entry_t  *environment_stack = NULL;
46 static stack_entry_t  *label_stack       = NULL;
47 static context_t      *global_context    = NULL;
48 static context_t      *context           = NULL;
49 static declaration_t  *last_declaration  = NULL;
50 static declaration_t  *current_function  = NULL;
51 static struct obstack  temp_obst;
52 static bool            found_error;
53
54 static type_t *type_valist;
55
56 static statement_t *parse_compound_statement(void);
57 static statement_t *parse_statement(void);
58
59 static expression_t *parse_sub_expression(unsigned precedence);
60 static expression_t *parse_expression(void);
61 static type_t       *parse_typename(void);
62
63 static void parse_compound_type_entries(void);
64 static declaration_t *parse_declarator(
65                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
66 static declaration_t *record_declaration(declaration_t *declaration);
67
68 static void semantic_comparison(binary_expression_t *expression);
69
70 #define STORAGE_CLASSES     \
71         case T_typedef:         \
72         case T_extern:          \
73         case T_static:          \
74         case T_auto:            \
75         case T_register:
76
77 #define TYPE_QUALIFIERS     \
78         case T_const:           \
79         case T_restrict:        \
80         case T_volatile:        \
81         case T_inline:          \
82         case T_forceinline:
83
84 #ifdef PROVIDE_COMPLEX
85 #define COMPLEX_SPECIFIERS  \
86         case T__Complex:
87 #define IMAGINARY_SPECIFIERS \
88         case T__Imaginary:
89 #else
90 #define COMPLEX_SPECIFIERS
91 #define IMAGINARY_SPECIFIERS
92 #endif
93
94 #define TYPE_SPECIFIERS       \
95         case T_void:              \
96         case T_char:              \
97         case T_short:             \
98         case T_int:               \
99         case T_long:              \
100         case T_float:             \
101         case T_double:            \
102         case T_signed:            \
103         case T_unsigned:          \
104         case T__Bool:             \
105         case T_struct:            \
106         case T_union:             \
107         case T_enum:              \
108         case T___typeof__:        \
109         case T___builtin_va_list: \
110         COMPLEX_SPECIFIERS        \
111         IMAGINARY_SPECIFIERS
112
113 #define DECLARATION_START   \
114         STORAGE_CLASSES         \
115         TYPE_QUALIFIERS         \
116         TYPE_SPECIFIERS
117
118 #define TYPENAME_START      \
119         TYPE_QUALIFIERS         \
120         TYPE_SPECIFIERS
121
122 static void *allocate_ast_zero(size_t size)
123 {
124         void *res = allocate_ast(size);
125         memset(res, 0, size);
126         return res;
127 }
128
129 static size_t get_statement_struct_size(statement_kind_t kind)
130 {
131         static const size_t sizes[] = {
132                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
133                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
134                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
135                 [STATEMENT_IF]          = sizeof(if_statement_t),
136                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
137                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
138                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
139                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
140                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
141                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
142                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
143                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
144                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
145                 [STATEMENT_FOR]         = sizeof(for_statement_t),
146                 [STATEMENT_ASM]         = sizeof(asm_statement_t)
147         };
148         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
149         assert(sizes[kind] != 0);
150         return sizes[kind];
151 }
152
153 static statement_t *allocate_statement_zero(statement_kind_t kind)
154 {
155         size_t       size = get_statement_struct_size(kind);
156         statement_t *res  = allocate_ast_zero(size);
157
158         res->base.kind = kind;
159         return res;
160 }
161
162
163 static size_t get_expression_struct_size(expression_kind_t type)
164 {
165         static const size_t sizes[] = {
166                 [EXPR_INVALID]             = sizeof(expression_base_t),
167                 [EXPR_REFERENCE]           = sizeof(reference_expression_t),
168                 [EXPR_CONST]               = sizeof(const_expression_t),
169                 [EXPR_STRING_LITERAL]      = sizeof(string_literal_expression_t),
170                 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
171                 [EXPR_CALL]                = sizeof(call_expression_t),
172                 [EXPR_UNARY_FIRST]         = sizeof(unary_expression_t),
173                 [EXPR_BINARY_FIRST]        = sizeof(binary_expression_t),
174                 [EXPR_CONDITIONAL]         = sizeof(conditional_expression_t),
175                 [EXPR_SELECT]              = sizeof(select_expression_t),
176                 [EXPR_ARRAY_ACCESS]        = sizeof(array_access_expression_t),
177                 [EXPR_SIZEOF]              = sizeof(sizeof_expression_t),
178                 [EXPR_CLASSIFY_TYPE]       = sizeof(classify_type_expression_t),
179                 [EXPR_FUNCTION]            = sizeof(string_literal_expression_t),
180                 [EXPR_PRETTY_FUNCTION]     = sizeof(string_literal_expression_t),
181                 [EXPR_BUILTIN_SYMBOL]      = sizeof(builtin_symbol_expression_t),
182                 [EXPR_OFFSETOF]            = sizeof(offsetof_expression_t),
183                 [EXPR_VA_START]            = sizeof(va_start_expression_t),
184                 [EXPR_VA_ARG]              = sizeof(va_arg_expression_t),
185                 [EXPR_STATEMENT]           = sizeof(statement_expression_t),
186         };
187         if(type >= EXPR_UNARY_FIRST && type <= EXPR_UNARY_LAST) {
188                 return sizes[EXPR_UNARY_FIRST];
189         }
190         if(type >= EXPR_BINARY_FIRST && type <= EXPR_BINARY_LAST) {
191                 return sizes[EXPR_BINARY_FIRST];
192         }
193         assert(type <= sizeof(sizes) / sizeof(sizes[0]));
194         assert(sizes[type] != 0);
195         return sizes[type];
196 }
197
198 static expression_t *allocate_expression_zero(expression_kind_t kind)
199 {
200         size_t        size = get_expression_struct_size(kind);
201         expression_t *res  = allocate_ast_zero(size);
202
203         res->base.kind = kind;
204         return res;
205 }
206
207 static size_t get_type_struct_size(type_kind_t kind)
208 {
209         static const size_t sizes[] = {
210                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
211                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
212                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
213                 [TYPE_ENUM]            = sizeof(enum_type_t),
214                 [TYPE_FUNCTION]        = sizeof(function_type_t),
215                 [TYPE_POINTER]         = sizeof(pointer_type_t),
216                 [TYPE_ARRAY]           = sizeof(array_type_t),
217                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
218                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
219                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
220         };
221         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
222         assert(kind <= TYPE_TYPEOF);
223         assert(sizes[kind] != 0);
224         return sizes[kind];
225 }
226
227 static type_t *allocate_type_zero(type_kind_t kind)
228 {
229         size_t  size = get_type_struct_size(kind);
230         type_t *res  = obstack_alloc(type_obst, size);
231         memset(res, 0, size);
232
233         res->base.kind = kind;
234         return res;
235 }
236
237 static size_t get_initializer_size(initializer_kind_t kind)
238 {
239         static const size_t sizes[] = {
240                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
241                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
242                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
243                 [INITIALIZER_LIST]        = sizeof(initializer_list_t)
244         };
245         assert(kind < sizeof(sizes) / sizeof(*sizes));
246         assert(sizes[kind] != 0);
247         return sizes[kind];
248 }
249
250 static initializer_t *allocate_initializer(initializer_kind_t kind)
251 {
252         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
253         result->kind          = kind;
254
255         return result;
256 }
257
258 static void free_type(void *type)
259 {
260         obstack_free(type_obst, type);
261 }
262
263 /**
264  * returns the top element of the environment stack
265  */
266 static size_t environment_top(void)
267 {
268         return ARR_LEN(environment_stack);
269 }
270
271 static size_t label_top(void)
272 {
273         return ARR_LEN(label_stack);
274 }
275
276
277
278 static inline void next_token(void)
279 {
280         token                              = lookahead_buffer[lookahead_bufpos];
281         lookahead_buffer[lookahead_bufpos] = lexer_token;
282         lexer_next_token();
283
284         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
285
286 #ifdef PRINT_TOKENS
287         print_token(stderr, &token);
288         fprintf(stderr, "\n");
289 #endif
290 }
291
292 static inline const token_t *look_ahead(int num)
293 {
294         assert(num > 0 && num <= MAX_LOOKAHEAD);
295         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
296         return &lookahead_buffer[pos];
297 }
298
299 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
300
301 static void error(void)
302 {
303         found_error = true;
304 #ifdef ABORT_ON_ERROR
305         abort();
306 #endif
307 }
308
309 static void parser_print_error_prefix_pos(
310                 const source_position_t source_position)
311 {
312         parser_print_prefix_pos(source_position);
313         fputs("error: ", stderr);
314         error();
315 }
316
317 static void parser_print_error_prefix(void)
318 {
319         parser_print_error_prefix_pos(token.source_position);
320 }
321
322 static void parse_error(const char *message)
323 {
324         parser_print_error_prefix();
325         fprintf(stderr, "parse error: %s\n", message);
326 }
327
328 static void parser_print_warning_prefix(void)
329 {
330         parser_print_warning_prefix_pos(token.source_position);
331 }
332
333 static void parse_warning(const char *message)
334 {
335         parse_warning_pos(token.source_position, message);
336 }
337
338 static void parse_error_expected(const char *message, ...)
339 {
340         va_list args;
341         int first = 1;
342
343         if(message != NULL) {
344                 parser_print_error_prefix();
345                 fprintf(stderr, "%s\n", message);
346         }
347         parser_print_error_prefix();
348         fputs("Parse error: got ", stderr);
349         print_token(stderr, &token);
350         fputs(", expected ", stderr);
351
352         va_start(args, message);
353         token_type_t token_type = va_arg(args, token_type_t);
354         while(token_type != 0) {
355                 if(first == 1) {
356                         first = 0;
357                 } else {
358                         fprintf(stderr, ", ");
359                 }
360                 print_token_type(stderr, token_type);
361                 token_type = va_arg(args, token_type_t);
362         }
363         va_end(args);
364         fprintf(stderr, "\n");
365 }
366
367 static void print_type_quoted(type_t *type)
368 {
369         fputc('\'', stderr);
370         print_type(type);
371         fputc('\'', stderr);
372 }
373
374 static void type_error(const char *msg, const source_position_t source_position,
375                        type_t *type)
376 {
377         parser_print_error_prefix_pos(source_position);
378         fprintf(stderr, "%s, but found type ", msg);
379         print_type_quoted(type);
380         fputc('\n', stderr);
381 }
382
383 static void type_error_incompatible(const char *msg,
384                 const source_position_t source_position, type_t *type1, type_t *type2)
385 {
386         parser_print_error_prefix_pos(source_position);
387         fprintf(stderr, "%s, incompatible types: ", msg);
388         print_type_quoted(type1);
389         fprintf(stderr, " - ");
390         print_type_quoted(type2);
391         fprintf(stderr, ")\n");
392 }
393
394 static void eat_block(void)
395 {
396         if(token.type == '{')
397                 next_token();
398
399         while(token.type != '}') {
400                 if(token.type == T_EOF)
401                         return;
402                 if(token.type == '{') {
403                         eat_block();
404                         continue;
405                 }
406                 next_token();
407         }
408         eat('}');
409 }
410
411 static void eat_statement(void)
412 {
413         while(token.type != ';') {
414                 if(token.type == T_EOF)
415                         return;
416                 if(token.type == '}')
417                         return;
418                 if(token.type == '{') {
419                         eat_block();
420                         continue;
421                 }
422                 next_token();
423         }
424         eat(';');
425 }
426
427 static void eat_paren(void)
428 {
429         if(token.type == '(')
430                 next_token();
431
432         while(token.type != ')') {
433                 if(token.type == T_EOF)
434                         return;
435                 if(token.type == ')' || token.type == ';' || token.type == '}') {
436                         return;
437                 }
438                 if(token.type == '(') {
439                         eat_paren();
440                         continue;
441                 }
442                 if(token.type == '{') {
443                         eat_block();
444                         continue;
445                 }
446                 next_token();
447         }
448         eat(')');
449 }
450
451 #define expect(expected)                           \
452     if(UNLIKELY(token.type != (expected))) {       \
453         parse_error_expected(NULL, (expected), 0); \
454         eat_statement();                           \
455         return NULL;                               \
456     }                                              \
457     next_token();
458
459 #define expect_block(expected)                     \
460     if(UNLIKELY(token.type != (expected))) {       \
461         parse_error_expected(NULL, (expected), 0); \
462         eat_block();                               \
463         return NULL;                               \
464     }                                              \
465     next_token();
466
467 #define expect_void(expected)                      \
468     if(UNLIKELY(token.type != (expected))) {       \
469         parse_error_expected(NULL, (expected), 0); \
470         eat_statement();                           \
471         return;                                    \
472     }                                              \
473     next_token();
474
475 static void set_context(context_t *new_context)
476 {
477         context = new_context;
478
479         last_declaration = new_context->declarations;
480         if(last_declaration != NULL) {
481                 while(last_declaration->next != NULL) {
482                         last_declaration = last_declaration->next;
483                 }
484         }
485 }
486
487 /**
488  * called when we find a 2nd declarator for an identifier we already have a
489  * declarator for
490  */
491 static bool is_compatible_declaration(declaration_t *declaration,
492                                       declaration_t *previous)
493 {
494         /* happens for K&R style function parameters */
495         if(previous->type == NULL) {
496                 previous->type = declaration->type;
497                 return true;
498         }
499
500         type_t *type1 = skip_typeref(declaration->type);
501         type_t *type2 = skip_typeref(previous->type);
502
503         return types_compatible(type1, type2);
504 }
505
506 static declaration_t *get_declaration(symbol_t *symbol, namespace_t namespc)
507 {
508         declaration_t *declaration = symbol->declaration;
509         for( ; declaration != NULL; declaration = declaration->symbol_next) {
510                 if(declaration->namespc == namespc)
511                         return declaration;
512         }
513
514         return NULL;
515 }
516
517 static const char *get_namespace_prefix(namespace_t namespc)
518 {
519         switch(namespc) {
520         case NAMESPACE_NORMAL:
521                 return "";
522         case NAMESPACE_UNION:
523                 return "union ";
524         case NAMESPACE_STRUCT:
525                 return "struct ";
526         case NAMESPACE_ENUM:
527                 return "enum ";
528         case NAMESPACE_LABEL:
529                 return "label ";
530         }
531         panic("invalid namespace found");
532 }
533
534 /**
535  * pushs an environment_entry on the environment stack and links the
536  * corresponding symbol to the new entry
537  */
538 static declaration_t *stack_push(stack_entry_t **stack_ptr,
539                                  declaration_t *declaration,
540                                  context_t *parent_context)
541 {
542         symbol_t    *symbol    = declaration->symbol;
543         namespace_t  namespc = (namespace_t)declaration->namespc;
544
545         /* a declaration should be only pushed once */
546         declaration->parent_context = parent_context;
547
548         declaration_t *previous_declaration = get_declaration(symbol, namespc);
549         assert(declaration != previous_declaration);
550         if(previous_declaration != NULL
551                         && previous_declaration->parent_context == context) {
552                 if(!is_compatible_declaration(declaration, previous_declaration)) {
553                         parser_print_error_prefix_pos(declaration->source_position);
554                         fprintf(stderr, "definition of symbol '%s%s' with type ",
555                                         get_namespace_prefix(namespc), symbol->string);
556                         print_type_quoted(declaration->type);
557                         fputc('\n', stderr);
558                         parser_print_error_prefix_pos(
559                                         previous_declaration->source_position);
560                         fprintf(stderr, "is incompatible with previous declaration "
561                                         "of type ");
562                         print_type_quoted(previous_declaration->type);
563                         fputc('\n', stderr);
564                 } else {
565                         unsigned  old_storage_class = previous_declaration->storage_class;
566                         unsigned  new_storage_class = declaration->storage_class;
567                         type_t   *type              = previous_declaration->type;
568                         type = skip_typeref(type);
569
570                         if (current_function == NULL) {
571                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
572                                     new_storage_class == STORAGE_CLASS_STATIC) {
573                                         parser_print_error_prefix_pos(declaration->source_position);
574                                         fprintf(stderr,
575                                                 "static declaration of '%s' follows non-static declaration\n",
576                                                 symbol->string);
577                                         parser_print_error_prefix_pos(previous_declaration->source_position);
578                                         fprintf(stderr, "previous declaration of '%s' was here\n",
579                                                 symbol->string);
580                                 } else {
581                                         if (old_storage_class == STORAGE_CLASS_EXTERN) {
582                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
583                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
584                                                 }
585                                         } else if(!is_type_function(type)) {
586                                                 parser_print_warning_prefix_pos(declaration->source_position);
587                                                 fprintf(stderr, "redundant declaration for '%s'\n",
588                                                                                 symbol->string);
589                                                 parser_print_warning_prefix_pos(previous_declaration->source_position);
590                                                 fprintf(stderr, "previous declaration of '%s' was here\n",
591                                                                                 symbol->string);
592                                         }
593                                 }
594                         } else {
595                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
596                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
597                                         parser_print_warning_prefix_pos(declaration->source_position);
598                                         fprintf(stderr, "redundant extern declaration for '%s'\n",
599                                                 symbol->string);
600                                         parser_print_warning_prefix_pos(previous_declaration->source_position);
601                                         fprintf(stderr, "previous declaration of '%s' was here\n",
602                                                 symbol->string);
603                                 } else {
604                                         parser_print_error_prefix_pos(declaration->source_position);
605                                         if (old_storage_class == new_storage_class) {
606                                                 fprintf(stderr, "redeclaration of '%s'\n", symbol->string);
607                                         } else {
608                                                 fprintf(stderr, "redeclaration of '%s' with different linkage\n", symbol->string);
609                                         }
610                                         parser_print_error_prefix_pos(previous_declaration->source_position);
611                                         fprintf(stderr, "previous declaration of '%s' was here\n",
612                                                 symbol->string);
613                                 }
614                         }
615                 }
616                 return previous_declaration;
617         }
618
619         /* remember old declaration */
620         stack_entry_t entry;
621         entry.symbol          = symbol;
622         entry.old_declaration = symbol->declaration;
623         entry.namespc         = (unsigned short) namespc;
624         ARR_APP1(stack_entry_t, *stack_ptr, entry);
625
626         /* replace/add declaration into declaration list of the symbol */
627         if(symbol->declaration == NULL) {
628                 symbol->declaration = declaration;
629         } else {
630                 declaration_t *iter_last = NULL;
631                 declaration_t *iter      = symbol->declaration;
632                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
633                         /* replace an entry? */
634                         if(iter->namespc == namespc) {
635                                 if(iter_last == NULL) {
636                                         symbol->declaration = declaration;
637                                 } else {
638                                         iter_last->symbol_next = declaration;
639                                 }
640                                 declaration->symbol_next = iter->symbol_next;
641                                 break;
642                         }
643                 }
644                 if(iter == NULL) {
645                         assert(iter_last->symbol_next == NULL);
646                         iter_last->symbol_next = declaration;
647                 }
648         }
649
650         return declaration;
651 }
652
653 static declaration_t *environment_push(declaration_t *declaration)
654 {
655         assert(declaration->source_position.input_name != NULL);
656         return stack_push(&environment_stack, declaration, context);
657 }
658
659 static declaration_t *label_push(declaration_t *declaration)
660 {
661         return stack_push(&label_stack, declaration, &current_function->context);
662 }
663
664 /**
665  * pops symbols from the environment stack until @p new_top is the top element
666  */
667 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
668 {
669         stack_entry_t *stack = *stack_ptr;
670         size_t         top   = ARR_LEN(stack);
671         size_t         i;
672
673         assert(new_top <= top);
674         if(new_top == top)
675                 return;
676
677         for(i = top; i > new_top; --i) {
678                 stack_entry_t *entry = &stack[i - 1];
679
680                 declaration_t *old_declaration = entry->old_declaration;
681                 symbol_t      *symbol          = entry->symbol;
682                 namespace_t    namespc         = (namespace_t)entry->namespc;
683
684                 /* replace/remove declaration */
685                 declaration_t *declaration = symbol->declaration;
686                 assert(declaration != NULL);
687                 if(declaration->namespc == namespc) {
688                         if(old_declaration == NULL) {
689                                 symbol->declaration = declaration->symbol_next;
690                         } else {
691                                 symbol->declaration = old_declaration;
692                         }
693                 } else {
694                         declaration_t *iter_last = declaration;
695                         declaration_t *iter      = declaration->symbol_next;
696                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
697                                 /* replace an entry? */
698                                 if(iter->namespc == namespc) {
699                                         assert(iter_last != NULL);
700                                         iter_last->symbol_next = old_declaration;
701                                         old_declaration->symbol_next = iter->symbol_next;
702                                         break;
703                                 }
704                         }
705                         assert(iter != NULL);
706                 }
707         }
708
709         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
710 }
711
712 static void environment_pop_to(size_t new_top)
713 {
714         stack_pop_to(&environment_stack, new_top);
715 }
716
717 static void label_pop_to(size_t new_top)
718 {
719         stack_pop_to(&label_stack, new_top);
720 }
721
722
723 static int get_rank(const type_t *type)
724 {
725         assert(!is_typeref(type));
726         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
727          * and esp. footnote 108). However we can't fold constants (yet), so we
728          * can't decide whether unsigned int is possible, while int always works.
729          * (unsigned int would be preferable when possible... for stuff like
730          *  struct { enum { ... } bla : 4; } ) */
731         if(type->kind == TYPE_ENUM)
732                 return ATOMIC_TYPE_INT;
733
734         assert(type->kind == TYPE_ATOMIC);
735         const atomic_type_t *atomic_type = &type->atomic;
736         atomic_type_type_t   atype       = atomic_type->atype;
737         return atype;
738 }
739
740 static type_t *promote_integer(type_t *type)
741 {
742         if(get_rank(type) < ATOMIC_TYPE_INT)
743                 type = type_int;
744
745         return type;
746 }
747
748 static expression_t *create_cast_expression(expression_t *expression,
749                                             type_t *dest_type)
750 {
751         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
752
753         cast->unary.value   = expression;
754         cast->base.datatype = dest_type;
755
756         return cast;
757 }
758
759 static bool is_null_pointer_constant(const expression_t *expression)
760 {
761         /* skip void* cast */
762         if(expression->kind == EXPR_UNARY_CAST
763                         || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
764                 expression = expression->unary.value;
765         }
766
767         /* TODO: not correct yet, should be any constant integer expression
768          * which evaluates to 0 */
769         if (expression->kind != EXPR_CONST)
770                 return false;
771
772         type_t *const type = skip_typeref(expression->base.datatype);
773         if (!is_type_integer(type))
774                 return false;
775
776         return expression->conste.v.int_value == 0;
777 }
778
779 static expression_t *create_implicit_cast(expression_t *expression,
780                                           type_t *dest_type)
781 {
782         type_t *source_type = expression->base.datatype;
783
784         if(source_type == NULL)
785                 return expression;
786
787         source_type = skip_typeref(source_type);
788         dest_type   = skip_typeref(dest_type);
789
790         if(source_type == dest_type)
791                 return expression;
792
793         switch (dest_type->kind) {
794                 case TYPE_ENUM:
795                         /* TODO warning for implicitly converting to enum */
796                 case TYPE_ATOMIC:
797                         if (source_type->kind != TYPE_ATOMIC &&
798                                         source_type->kind != TYPE_ENUM) {
799                                 panic("casting of non-atomic types not implemented yet");
800                         }
801
802                         if(is_type_floating(dest_type) && !is_type_scalar(source_type)) {
803                                 type_error_incompatible("can't cast types",
804                                                 expression->base.source_position, source_type,
805                                                 dest_type);
806                                 return expression;
807                         }
808
809                         return create_cast_expression(expression, dest_type);
810
811                 case TYPE_POINTER:
812                         switch (source_type->kind) {
813                                 case TYPE_ATOMIC:
814                                         if (is_null_pointer_constant(expression)) {
815                                                 return create_cast_expression(expression, dest_type);
816                                         }
817                                         break;
818
819                                 case TYPE_POINTER:
820                                         if (pointers_compatible(source_type, dest_type)) {
821                                                 return create_cast_expression(expression, dest_type);
822                                         }
823                                         break;
824
825                                 case TYPE_ARRAY: {
826                                         array_type_t   *array_type   = &source_type->array;
827                                         pointer_type_t *pointer_type = &dest_type->pointer;
828                                         if (types_compatible(array_type->element_type,
829                                                                                  pointer_type->points_to)) {
830                                                 return create_cast_expression(expression, dest_type);
831                                         }
832                                         break;
833                                 }
834
835                                 default:
836                                         panic("casting of non-atomic types not implemented yet");
837                         }
838
839                         type_error_incompatible("can't implicitly cast types",
840                                         expression->base.source_position, source_type, dest_type);
841                         return expression;
842
843                 default:
844                         panic("casting of non-atomic types not implemented yet");
845         }
846 }
847
848 /** Implements the rules from Â§ 6.5.16.1 */
849 static void semantic_assign(type_t *orig_type_left, expression_t **right,
850                             const char *context)
851 {
852         type_t *orig_type_right = (*right)->base.datatype;
853
854         if(orig_type_right == NULL)
855                 return;
856
857         type_t *const type_left  = skip_typeref(orig_type_left);
858         type_t *const type_right = skip_typeref(orig_type_right);
859
860         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
861             (is_type_pointer(type_left) && is_null_pointer_constant(*right)) ||
862             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
863                 && is_type_pointer(type_right))) {
864                 *right = create_implicit_cast(*right, type_left);
865                 return;
866         }
867
868         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
869                 pointer_type_t *pointer_type_left  = &type_left->pointer;
870                 pointer_type_t *pointer_type_right = &type_right->pointer;
871                 type_t         *points_to_left     = pointer_type_left->points_to;
872                 type_t         *points_to_right    = pointer_type_right->points_to;
873
874                 points_to_left  = skip_typeref(points_to_left);
875                 points_to_right = skip_typeref(points_to_right);
876
877                 /* the left type has all qualifiers from the right type */
878                 unsigned missing_qualifiers
879                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
880                 if(missing_qualifiers != 0) {
881                         parser_print_error_prefix();
882                         fprintf(stderr, "destination type ");
883                         print_type_quoted(type_left);
884                         fprintf(stderr, " in %s from type ", context);
885                         print_type_quoted(type_right);
886                         fprintf(stderr, " lacks qualifiers '");
887                         print_type_qualifiers(missing_qualifiers);
888                         fprintf(stderr, "' in pointed-to type\n");
889                         return;
890                 }
891
892                 points_to_left  = get_unqualified_type(points_to_left);
893                 points_to_right = get_unqualified_type(points_to_right);
894
895                 if(!is_type_atomic(points_to_left, ATOMIC_TYPE_VOID)
896                                 && !is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)
897                                 && !types_compatible(points_to_left, points_to_right)) {
898                         goto incompatible_assign_types;
899                 }
900
901                 *right = create_implicit_cast(*right, type_left);
902                 return;
903         }
904
905         if (is_type_compound(type_left)
906                         && types_compatible(type_left, type_right)) {
907                 *right = create_implicit_cast(*right, type_left);
908                 return;
909         }
910
911 incompatible_assign_types:
912         /* TODO: improve error message */
913         parser_print_error_prefix();
914         fprintf(stderr, "incompatible types in %s\n", context);
915         parser_print_error_prefix();
916         print_type_quoted(orig_type_left);
917         fputs(" <- ", stderr);
918         print_type_quoted(orig_type_right);
919         fputs("\n", stderr);
920 }
921
922 static expression_t *parse_constant_expression(void)
923 {
924         /* start parsing at precedence 7 (conditional expression) */
925         expression_t *result = parse_sub_expression(7);
926
927         if(!is_constant_expression(result)) {
928                 parser_print_error_prefix_pos(result->base.source_position);
929                 fprintf(stderr, "expression '");
930                 print_expression(result);
931                 fprintf(stderr, "' is not constant\n");
932         }
933
934         return result;
935 }
936
937 static expression_t *parse_assignment_expression(void)
938 {
939         /* start parsing at precedence 2 (assignment expression) */
940         return parse_sub_expression(2);
941 }
942
943 static type_t *make_global_typedef(const char *name, type_t *type)
944 {
945         symbol_t *const symbol       = symbol_table_insert(name);
946
947         declaration_t *declaration   = allocate_ast_zero(sizeof(declaration[0]));
948         declaration->namespc         = NAMESPACE_NORMAL;
949         declaration->storage_class   = STORAGE_CLASS_TYPEDEF;
950         declaration->type            = type;
951         declaration->symbol          = symbol;
952         declaration->source_position = builtin_source_position;
953
954         record_declaration(declaration);
955
956         type_t *typedef_type               = allocate_type_zero(TYPE_TYPEDEF);
957         typedef_type->typedeft.declaration = declaration;
958
959         return typedef_type;
960 }
961
962 static const char *parse_string_literals(void)
963 {
964         assert(token.type == T_STRING_LITERAL);
965         const char *result = token.v.string;
966
967         next_token();
968
969         while(token.type == T_STRING_LITERAL) {
970                 result = concat_strings(result, token.v.string);
971                 next_token();
972         }
973
974         return result;
975 }
976
977 static void parse_attributes(void)
978 {
979         while(true) {
980                 switch(token.type) {
981                 case T___attribute__: {
982                         next_token();
983
984                         expect_void('(');
985                         int depth = 1;
986                         while(depth > 0) {
987                                 switch(token.type) {
988                                 case T_EOF:
989                                         parse_error("EOF while parsing attribute");
990                                         break;
991                                 case '(':
992                                         next_token();
993                                         depth++;
994                                         break;
995                                 case ')':
996                                         next_token();
997                                         depth--;
998                                         break;
999                                 default:
1000                                         next_token();
1001                                 }
1002                         }
1003                         break;
1004                 }
1005                 case T_asm:
1006                         next_token();
1007                         expect_void('(');
1008                         if(token.type != T_STRING_LITERAL) {
1009                                 parse_error_expected("while parsing assembler attribute",
1010                                                      T_STRING_LITERAL);
1011                                 eat_paren();
1012                                 break;
1013                         } else {
1014                                 parse_string_literals();
1015                         }
1016                         expect_void(')');
1017                         break;
1018                 default:
1019                         goto attributes_finished;
1020                 }
1021         }
1022
1023 attributes_finished:
1024         ;
1025 }
1026
1027 #if 0
1028 static designator_t *parse_designation(void)
1029 {
1030         if(token.type != '[' && token.type != '.')
1031                 return NULL;
1032
1033         designator_t *result = NULL;
1034         designator_t *last   = NULL;
1035
1036         while(1) {
1037                 designator_t *designator;
1038                 switch(token.type) {
1039                 case '[':
1040                         designator = allocate_ast_zero(sizeof(designator[0]));
1041                         next_token();
1042                         designator->array_access = parse_constant_expression();
1043                         expect(']');
1044                         break;
1045                 case '.':
1046                         designator = allocate_ast_zero(sizeof(designator[0]));
1047                         next_token();
1048                         if(token.type != T_IDENTIFIER) {
1049                                 parse_error_expected("while parsing designator",
1050                                                      T_IDENTIFIER, 0);
1051                                 return NULL;
1052                         }
1053                         designator->symbol = token.v.symbol;
1054                         next_token();
1055                         break;
1056                 default:
1057                         expect('=');
1058                         return result;
1059                 }
1060
1061                 assert(designator != NULL);
1062                 if(last != NULL) {
1063                         last->next = designator;
1064                 } else {
1065                         result = designator;
1066                 }
1067                 last = designator;
1068         }
1069 }
1070 #endif
1071
1072 static initializer_t *initializer_from_string(array_type_t *type,
1073                                               const char *string)
1074 {
1075         /* TODO: check len vs. size of array type */
1076         (void) type;
1077
1078         initializer_t *initializer = allocate_initializer(INITIALIZER_STRING);
1079         initializer->string.string = string;
1080
1081         return initializer;
1082 }
1083
1084 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1085                                                    wide_string_t *const string)
1086 {
1087         /* TODO: check len vs. size of array type */
1088         (void) type;
1089
1090         initializer_t *const initializer =
1091                 allocate_initializer(INITIALIZER_WIDE_STRING);
1092         initializer->wide_string.string = *string;
1093
1094         return initializer;
1095 }
1096
1097 static initializer_t *initializer_from_expression(type_t *type,
1098                                                   expression_t *expression)
1099 {
1100         /* TODO check that expression is a constant expression */
1101
1102         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
1103         type_t *const expr_type = expression->base.datatype;
1104         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1105                 array_type_t *const array_type     = &type->array;
1106                 type_t       *const element_type   = skip_typeref(array_type->element_type);
1107
1108                 if (element_type->kind == TYPE_ATOMIC) {
1109                         switch (expression->kind) {
1110                                 case EXPR_STRING_LITERAL:
1111                                         if (element_type->atomic.atype == ATOMIC_TYPE_CHAR) {
1112                                                 return initializer_from_string(array_type,
1113                                                         expression->string.value);
1114                                         }
1115
1116                                 case EXPR_WIDE_STRING_LITERAL: {
1117                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1118                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
1119                                                 return initializer_from_wide_string(array_type,
1120                                                         &expression->wide_string.value);
1121                                         }
1122                                 }
1123
1124                                 default: break;
1125                         }
1126                 }
1127         }
1128
1129         type_t *expression_type = skip_typeref(expression->base.datatype);
1130         if(is_type_scalar(type) || types_compatible(type, expression_type)) {
1131                 semantic_assign(type, &expression, "initializer");
1132
1133                 initializer_t *result = allocate_initializer(INITIALIZER_VALUE);
1134                 result->value.value   = expression;
1135
1136                 return result;
1137         }
1138
1139         return NULL;
1140 }
1141
1142 static initializer_t *parse_sub_initializer(type_t *type,
1143                                             expression_t *expression,
1144                                             type_t *expression_type);
1145
1146 static initializer_t *parse_sub_initializer_elem(type_t *type)
1147 {
1148         if(token.type == '{') {
1149                 return parse_sub_initializer(type, NULL, NULL);
1150         }
1151
1152         expression_t *expression      = parse_assignment_expression();
1153         type_t       *expression_type = skip_typeref(expression->base.datatype);
1154
1155         return parse_sub_initializer(type, expression, expression_type);
1156 }
1157
1158 static bool had_initializer_brace_warning;
1159
1160 static initializer_t *parse_sub_initializer(type_t *type,
1161                                             expression_t *expression,
1162                                             type_t *expression_type)
1163 {
1164         if(is_type_scalar(type)) {
1165                 /* there might be extra {} hierarchies */
1166                 if(token.type == '{') {
1167                         next_token();
1168                         if(!had_initializer_brace_warning) {
1169                                 parse_warning("braces around scalar initializer");
1170                                 had_initializer_brace_warning = true;
1171                         }
1172                         initializer_t *result = parse_sub_initializer(type, NULL, NULL);
1173                         if(token.type == ',') {
1174                                 next_token();
1175                                 /* TODO: warn about excessive elements */
1176                         }
1177                         expect_block('}');
1178                         return result;
1179                 }
1180
1181                 if(expression == NULL) {
1182                         expression = parse_assignment_expression();
1183                 }
1184                 return initializer_from_expression(type, expression);
1185         }
1186
1187         /* does the expression match the currently looked at object to initialize */
1188         if(expression != NULL) {
1189                 initializer_t *result = initializer_from_expression(type, expression);
1190                 if(result != NULL)
1191                         return result;
1192         }
1193
1194         bool read_paren = false;
1195         if(token.type == '{') {
1196                 next_token();
1197                 read_paren = true;
1198         }
1199
1200         /* descend into subtype */
1201         initializer_t  *result = NULL;
1202         initializer_t **elems;
1203         if(is_type_array(type)) {
1204                 array_type_t *array_type   = &type->array;
1205                 type_t       *element_type = array_type->element_type;
1206                 element_type               = skip_typeref(element_type);
1207
1208                 initializer_t *sub;
1209                 had_initializer_brace_warning = false;
1210                 if(expression == NULL) {
1211                         sub = parse_sub_initializer_elem(element_type);
1212                 } else {
1213                         sub = parse_sub_initializer(element_type, expression,
1214                                                     expression_type);
1215                 }
1216
1217                 /* didn't match the subtypes -> try the parent type */
1218                 if(sub == NULL) {
1219                         assert(!read_paren);
1220                         return NULL;
1221                 }
1222
1223                 elems = NEW_ARR_F(initializer_t*, 0);
1224                 ARR_APP1(initializer_t*, elems, sub);
1225
1226                 while(true) {
1227                         if(token.type == '}')
1228                                 break;
1229                         expect_block(',');
1230                         if(token.type == '}')
1231                                 break;
1232
1233                         sub = parse_sub_initializer_elem(element_type);
1234                         if(sub == NULL) {
1235                                 /* TODO error, do nicer cleanup */
1236                                 parse_error("member initializer didn't match");
1237                                 DEL_ARR_F(elems);
1238                                 return NULL;
1239                         }
1240                         ARR_APP1(initializer_t*, elems, sub);
1241                 }
1242         } else {
1243                 assert(is_type_compound(type));
1244                 compound_type_t *compound_type = &type->compound;
1245                 context_t       *context       = &compound_type->declaration->context;
1246
1247                 declaration_t *first = context->declarations;
1248                 if(first == NULL)
1249                         return NULL;
1250                 type_t *first_type = first->type;
1251                 first_type         = skip_typeref(first_type);
1252
1253                 initializer_t *sub;
1254                 had_initializer_brace_warning = false;
1255                 if(expression == NULL) {
1256                         sub = parse_sub_initializer_elem(first_type);
1257                 } else {
1258                         sub = parse_sub_initializer(first_type, expression,expression_type);
1259                 }
1260
1261                 /* didn't match the subtypes -> try our parent type */
1262                 if(sub == NULL) {
1263                         assert(!read_paren);
1264                         return NULL;
1265                 }
1266
1267                 elems = NEW_ARR_F(initializer_t*, 0);
1268                 ARR_APP1(initializer_t*, elems, sub);
1269
1270                 declaration_t *iter  = first->next;
1271                 for( ; iter != NULL; iter = iter->next) {
1272                         if(iter->symbol == NULL)
1273                                 continue;
1274                         if(iter->namespc != NAMESPACE_NORMAL)
1275                                 continue;
1276
1277                         if(token.type == '}')
1278                                 break;
1279                         expect_block(',');
1280                         if(token.type == '}')
1281                                 break;
1282
1283                         type_t *iter_type = iter->type;
1284                         iter_type         = skip_typeref(iter_type);
1285
1286                         sub = parse_sub_initializer_elem(iter_type);
1287                         if(sub == NULL) {
1288                                 /* TODO error, do nicer cleanup */
1289                                 parse_error("member initializer didn't match");
1290                                 DEL_ARR_F(elems);
1291                                 return NULL;
1292                         }
1293                         ARR_APP1(initializer_t*, elems, sub);
1294                 }
1295         }
1296
1297         int    len        = ARR_LEN(elems);
1298         size_t elems_size = sizeof(initializer_t*) * len;
1299
1300         initializer_list_t *init = allocate_ast_zero(sizeof(init[0]) + elems_size);
1301
1302         init->initializer.kind = INITIALIZER_LIST;
1303         init->len              = len;
1304         memcpy(init->initializers, elems, elems_size);
1305         DEL_ARR_F(elems);
1306
1307         result = (initializer_t*) init;
1308
1309         if(read_paren) {
1310                 if(token.type == ',')
1311                         next_token();
1312                 expect('}');
1313         }
1314         return result;
1315 }
1316
1317 static initializer_t *parse_initializer(type_t *type)
1318 {
1319         initializer_t *result;
1320
1321         type = skip_typeref(type);
1322
1323         if(token.type != '{') {
1324                 expression_t  *expression  = parse_assignment_expression();
1325                 initializer_t *initializer = initializer_from_expression(type, expression);
1326                 if(initializer == NULL) {
1327                         parser_print_error_prefix();
1328                         fprintf(stderr, "initializer expression '");
1329                         print_expression(expression);
1330                         fprintf(stderr, "', type ");
1331                         print_type_quoted(expression->base.datatype);
1332                         fprintf(stderr, " is incompatible with type ");
1333                         print_type_quoted(type);
1334                         fprintf(stderr, "\n");
1335                 }
1336                 return initializer;
1337         }
1338
1339         if(is_type_scalar(type)) {
1340                 /* Â§ 6.7.8.11 */
1341                 eat('{');
1342
1343                 expression_t *expression = parse_assignment_expression();
1344                 result = initializer_from_expression(type, expression);
1345
1346                 if(token.type == ',')
1347                         next_token();
1348
1349                 expect('}');
1350                 return result;
1351         } else {
1352                 result = parse_sub_initializer(type, NULL, NULL);
1353         }
1354
1355         return result;
1356 }
1357
1358
1359
1360 static declaration_t *parse_compound_type_specifier(bool is_struct)
1361 {
1362         if(is_struct) {
1363                 eat(T_struct);
1364         } else {
1365                 eat(T_union);
1366         }
1367
1368         symbol_t      *symbol      = NULL;
1369         declaration_t *declaration = NULL;
1370
1371         if (token.type == T___attribute__) {
1372                 /* TODO */
1373                 parse_attributes();
1374         }
1375
1376         if(token.type == T_IDENTIFIER) {
1377                 symbol = token.v.symbol;
1378                 next_token();
1379
1380                 if(is_struct) {
1381                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1382                 } else {
1383                         declaration = get_declaration(symbol, NAMESPACE_UNION);
1384                 }
1385         } else if(token.type != '{') {
1386                 if(is_struct) {
1387                         parse_error_expected("while parsing struct type specifier",
1388                                              T_IDENTIFIER, '{', 0);
1389                 } else {
1390                         parse_error_expected("while parsing union type specifier",
1391                                              T_IDENTIFIER, '{', 0);
1392                 }
1393
1394                 return NULL;
1395         }
1396
1397         if(declaration == NULL) {
1398                 declaration = allocate_ast_zero(sizeof(declaration[0]));
1399
1400                 if(is_struct) {
1401                         declaration->namespc = NAMESPACE_STRUCT;
1402                 } else {
1403                         declaration->namespc = NAMESPACE_UNION;
1404                 }
1405                 declaration->source_position = token.source_position;
1406                 declaration->symbol          = symbol;
1407                 record_declaration(declaration);
1408         }
1409
1410         if(token.type == '{') {
1411                 if(declaration->init.is_defined) {
1412                         assert(symbol != NULL);
1413                         parser_print_error_prefix();
1414                         fprintf(stderr, "multiple definition of %s %s\n",
1415                                         is_struct ? "struct" : "union", symbol->string);
1416                         declaration->context.declarations = NULL;
1417                 }
1418                 declaration->init.is_defined = true;
1419
1420                 int         top          = environment_top();
1421                 context_t  *last_context = context;
1422                 set_context(&declaration->context);
1423
1424                 parse_compound_type_entries();
1425                 parse_attributes();
1426
1427                 assert(context == &declaration->context);
1428                 set_context(last_context);
1429                 environment_pop_to(top);
1430         }
1431
1432         return declaration;
1433 }
1434
1435 static void parse_enum_entries(enum_type_t *const enum_type)
1436 {
1437         eat('{');
1438
1439         if(token.type == '}') {
1440                 next_token();
1441                 parse_error("empty enum not allowed");
1442                 return;
1443         }
1444
1445         do {
1446                 declaration_t *entry = allocate_ast_zero(sizeof(entry[0]));
1447
1448                 if(token.type != T_IDENTIFIER) {
1449                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1450                         eat_block();
1451                         return;
1452                 }
1453                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
1454                 entry->type            = (type_t*) enum_type;
1455                 entry->symbol          = token.v.symbol;
1456                 entry->source_position = token.source_position;
1457                 next_token();
1458
1459                 if(token.type == '=') {
1460                         next_token();
1461                         entry->init.enum_value = parse_constant_expression();
1462
1463                         /* TODO semantic */
1464                 }
1465
1466                 record_declaration(entry);
1467
1468                 if(token.type != ',')
1469                         break;
1470                 next_token();
1471         } while(token.type != '}');
1472
1473         expect_void('}');
1474 }
1475
1476 static type_t *parse_enum_specifier(void)
1477 {
1478         eat(T_enum);
1479
1480         declaration_t *declaration;
1481         symbol_t      *symbol;
1482
1483         if(token.type == T_IDENTIFIER) {
1484                 symbol = token.v.symbol;
1485                 next_token();
1486
1487                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1488         } else if(token.type != '{') {
1489                 parse_error_expected("while parsing enum type specifier",
1490                                      T_IDENTIFIER, '{', 0);
1491                 return NULL;
1492         } else {
1493                 declaration = NULL;
1494                 symbol      = NULL;
1495         }
1496
1497         if(declaration == NULL) {
1498                 declaration = allocate_ast_zero(sizeof(declaration[0]));
1499
1500                 declaration->namespc       = NAMESPACE_ENUM;
1501                 declaration->source_position = token.source_position;
1502                 declaration->symbol          = symbol;
1503         }
1504
1505         type_t *const type      = allocate_type_zero(TYPE_ENUM);
1506         type->enumt.declaration = declaration;
1507
1508         if(token.type == '{') {
1509                 if(declaration->init.is_defined) {
1510                         parser_print_error_prefix();
1511                         fprintf(stderr, "multiple definitions of enum %s\n",
1512                                 symbol->string);
1513                 }
1514                 record_declaration(declaration);
1515                 declaration->init.is_defined = 1;
1516
1517                 parse_enum_entries(&type->enumt);
1518                 parse_attributes();
1519         }
1520
1521         return type;
1522 }
1523
1524 /**
1525  * if a symbol is a typedef to another type, return true
1526  */
1527 static bool is_typedef_symbol(symbol_t *symbol)
1528 {
1529         const declaration_t *const declaration =
1530                 get_declaration(symbol, NAMESPACE_NORMAL);
1531         return
1532                 declaration != NULL &&
1533                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1534 }
1535
1536 static type_t *parse_typeof(void)
1537 {
1538         eat(T___typeof__);
1539
1540         type_t *type;
1541
1542         expect('(');
1543
1544         expression_t *expression  = NULL;
1545
1546 restart:
1547         switch(token.type) {
1548         case T___extension__:
1549                 /* this can be a prefix to a typename or an expression */
1550                 /* we simply eat it now. */
1551                 do {
1552                         next_token();
1553                 } while(token.type == T___extension__);
1554                 goto restart;
1555
1556         case T_IDENTIFIER:
1557                 if(is_typedef_symbol(token.v.symbol)) {
1558                         type = parse_typename();
1559                 } else {
1560                         expression = parse_expression();
1561                         type       = expression->base.datatype;
1562                 }
1563                 break;
1564
1565         TYPENAME_START
1566                 type = parse_typename();
1567                 break;
1568
1569         default:
1570                 expression = parse_expression();
1571                 type       = expression->base.datatype;
1572                 break;
1573         }
1574
1575         expect(')');
1576
1577         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF);
1578         typeof_type->typeoft.expression  = expression;
1579         typeof_type->typeoft.typeof_type = type;
1580
1581         return typeof_type;
1582 }
1583
1584 typedef enum {
1585         SPECIFIER_SIGNED    = 1 << 0,
1586         SPECIFIER_UNSIGNED  = 1 << 1,
1587         SPECIFIER_LONG      = 1 << 2,
1588         SPECIFIER_INT       = 1 << 3,
1589         SPECIFIER_DOUBLE    = 1 << 4,
1590         SPECIFIER_CHAR      = 1 << 5,
1591         SPECIFIER_SHORT     = 1 << 6,
1592         SPECIFIER_LONG_LONG = 1 << 7,
1593         SPECIFIER_FLOAT     = 1 << 8,
1594         SPECIFIER_BOOL      = 1 << 9,
1595         SPECIFIER_VOID      = 1 << 10,
1596 #ifdef PROVIDE_COMPLEX
1597         SPECIFIER_COMPLEX   = 1 << 11,
1598         SPECIFIER_IMAGINARY = 1 << 12,
1599 #endif
1600 } specifiers_t;
1601
1602 static type_t *create_builtin_type(symbol_t *const symbol,
1603                                    type_t *const real_type)
1604 {
1605         type_t *type            = allocate_type_zero(TYPE_BUILTIN);
1606         type->builtin.symbol    = symbol;
1607         type->builtin.real_type = real_type;
1608
1609         type_t *result = typehash_insert(type);
1610         if (type != result) {
1611                 free_type(type);
1612         }
1613
1614         return result;
1615 }
1616
1617 static type_t *get_typedef_type(symbol_t *symbol)
1618 {
1619         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1620         if(declaration == NULL
1621                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1622                 return NULL;
1623
1624         type_t *type               = allocate_type_zero(TYPE_TYPEDEF);
1625         type->typedeft.declaration = declaration;
1626
1627         return type;
1628 }
1629
1630 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1631 {
1632         type_t   *type            = NULL;
1633         unsigned  type_qualifiers = 0;
1634         unsigned  type_specifiers = 0;
1635         int       newtype         = 0;
1636
1637         specifiers->source_position = token.source_position;
1638
1639         while(true) {
1640                 switch(token.type) {
1641
1642                 /* storage class */
1643 #define MATCH_STORAGE_CLASS(token, class)                                \
1644                 case token:                                                      \
1645                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1646                                 parse_error("multiple storage classes in declaration "   \
1647                                             "specifiers");                               \
1648                         }                                                            \
1649                         specifiers->storage_class = class;                           \
1650                         next_token();                                                \
1651                         break;
1652
1653                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1654                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1655                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1656                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1657                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1658
1659                 case T___thread:
1660                         switch (specifiers->storage_class) {
1661                                 case STORAGE_CLASS_NONE:
1662                                         specifiers->storage_class = STORAGE_CLASS_THREAD;
1663                                         break;
1664
1665                                 case STORAGE_CLASS_EXTERN:
1666                                         specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
1667                                         break;
1668
1669                                 case STORAGE_CLASS_STATIC:
1670                                         specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
1671                                         break;
1672
1673                                 default:
1674                                         parse_error("multiple storage classes in declaration specifiers");
1675                                         break;
1676                         }
1677                         next_token();
1678                         break;
1679
1680                 /* type qualifiers */
1681 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1682                 case token:                                                     \
1683                         type_qualifiers |= qualifier;                               \
1684                         next_token();                                               \
1685                         break;
1686
1687                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1688                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1689                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1690
1691                 case T___extension__:
1692                         /* TODO */
1693                         next_token();
1694                         break;
1695
1696                 /* type specifiers */
1697 #define MATCH_SPECIFIER(token, specifier, name)                         \
1698                 case token:                                                     \
1699                         next_token();                                               \
1700                         if(type_specifiers & specifier) {                           \
1701                                 parse_error("multiple " name " type specifiers given"); \
1702                         } else {                                                    \
1703                                 type_specifiers |= specifier;                           \
1704                         }                                                           \
1705                         break;
1706
1707                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1708                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1709                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1710                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1711                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1712                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1713                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1714                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1715                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1716 #ifdef PROVIDE_COMPLEX
1717                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1718                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1719 #endif
1720                 case T_forceinline:
1721                         /* only in microsoft mode */
1722                         specifiers->decl_modifiers |= DM_FORCEINLINE;
1723
1724                 case T_inline:
1725                         next_token();
1726                         specifiers->is_inline = true;
1727                         break;
1728
1729                 case T_long:
1730                         next_token();
1731                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1732                                 parse_error("multiple type specifiers given");
1733                         } else if(type_specifiers & SPECIFIER_LONG) {
1734                                 type_specifiers |= SPECIFIER_LONG_LONG;
1735                         } else {
1736                                 type_specifiers |= SPECIFIER_LONG;
1737                         }
1738                         break;
1739
1740                 /* TODO: if type != NULL for the following rules should issue
1741                  * an error */
1742                 case T_struct: {
1743                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1744
1745                         type->compound.declaration = parse_compound_type_specifier(true);
1746                         break;
1747                 }
1748                 case T_union: {
1749                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1750
1751                         type->compound.declaration = parse_compound_type_specifier(false);
1752                         break;
1753                 }
1754                 case T_enum:
1755                         type = parse_enum_specifier();
1756                         break;
1757                 case T___typeof__:
1758                         type = parse_typeof();
1759                         break;
1760                 case T___builtin_va_list:
1761                         type = duplicate_type(type_valist);
1762                         next_token();
1763                         break;
1764
1765                 case T___attribute__:
1766                         /* TODO */
1767                         parse_attributes();
1768                         break;
1769
1770                 case T_IDENTIFIER: {
1771                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1772
1773                         if(typedef_type == NULL)
1774                                 goto finish_specifiers;
1775
1776                         next_token();
1777                         type = typedef_type;
1778                         break;
1779                 }
1780
1781                 /* function specifier */
1782                 default:
1783                         goto finish_specifiers;
1784                 }
1785         }
1786
1787 finish_specifiers:
1788
1789         if(type == NULL) {
1790                 atomic_type_type_t atomic_type;
1791
1792                 /* match valid basic types */
1793                 switch(type_specifiers) {
1794                 case SPECIFIER_VOID:
1795                         atomic_type = ATOMIC_TYPE_VOID;
1796                         break;
1797                 case SPECIFIER_CHAR:
1798                         atomic_type = ATOMIC_TYPE_CHAR;
1799                         break;
1800                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1801                         atomic_type = ATOMIC_TYPE_SCHAR;
1802                         break;
1803                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1804                         atomic_type = ATOMIC_TYPE_UCHAR;
1805                         break;
1806                 case SPECIFIER_SHORT:
1807                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1808                 case SPECIFIER_SHORT | SPECIFIER_INT:
1809                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1810                         atomic_type = ATOMIC_TYPE_SHORT;
1811                         break;
1812                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1813                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1814                         atomic_type = ATOMIC_TYPE_USHORT;
1815                         break;
1816                 case SPECIFIER_INT:
1817                 case SPECIFIER_SIGNED:
1818                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1819                         atomic_type = ATOMIC_TYPE_INT;
1820                         break;
1821                 case SPECIFIER_UNSIGNED:
1822                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1823                         atomic_type = ATOMIC_TYPE_UINT;
1824                         break;
1825                 case SPECIFIER_LONG:
1826                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1827                 case SPECIFIER_LONG | SPECIFIER_INT:
1828                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1829                         atomic_type = ATOMIC_TYPE_LONG;
1830                         break;
1831                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1832                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1833                         atomic_type = ATOMIC_TYPE_ULONG;
1834                         break;
1835                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1836                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1837                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1838                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1839                         | SPECIFIER_INT:
1840                         atomic_type = ATOMIC_TYPE_LONGLONG;
1841                         break;
1842                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1843                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1844                         | SPECIFIER_INT:
1845                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1846                         break;
1847                 case SPECIFIER_FLOAT:
1848                         atomic_type = ATOMIC_TYPE_FLOAT;
1849                         break;
1850                 case SPECIFIER_DOUBLE:
1851                         atomic_type = ATOMIC_TYPE_DOUBLE;
1852                         break;
1853                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1854                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1855                         break;
1856                 case SPECIFIER_BOOL:
1857                         atomic_type = ATOMIC_TYPE_BOOL;
1858                         break;
1859 #ifdef PROVIDE_COMPLEX
1860                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1861                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1862                         break;
1863                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1864                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1865                         break;
1866                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1867                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1868                         break;
1869                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1870                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1871                         break;
1872                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1873                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1874                         break;
1875                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1876                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1877                         break;
1878 #endif
1879                 default:
1880                         /* invalid specifier combination, give an error message */
1881                         if(type_specifiers == 0) {
1882 #ifndef STRICT_C99
1883                                 parse_warning("no type specifiers in declaration, using int");
1884                                 atomic_type = ATOMIC_TYPE_INT;
1885                                 break;
1886 #else
1887                                 parse_error("no type specifiers given in declaration");
1888 #endif
1889                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
1890                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
1891                                 parse_error("signed and unsigned specifiers gives");
1892                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
1893                                 parse_error("only integer types can be signed or unsigned");
1894                         } else {
1895                                 parse_error("multiple datatypes in declaration");
1896                         }
1897                         atomic_type = ATOMIC_TYPE_INVALID;
1898                 }
1899
1900                 type               = allocate_type_zero(TYPE_ATOMIC);
1901                 type->atomic.atype = atomic_type;
1902                 newtype            = 1;
1903         } else {
1904                 if(type_specifiers != 0) {
1905                         parse_error("multiple datatypes in declaration");
1906                 }
1907         }
1908
1909         type->base.qualifiers = type_qualifiers;
1910
1911         type_t *result = typehash_insert(type);
1912         if(newtype && result != type) {
1913                 free_type(type);
1914         }
1915
1916         specifiers->type = result;
1917 }
1918
1919 static type_qualifiers_t parse_type_qualifiers(void)
1920 {
1921         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
1922
1923         while(true) {
1924                 switch(token.type) {
1925                 /* type qualifiers */
1926                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1927                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1928                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1929
1930                 default:
1931                         return type_qualifiers;
1932                 }
1933         }
1934 }
1935
1936 static declaration_t *parse_identifier_list(void)
1937 {
1938         declaration_t *declarations     = NULL;
1939         declaration_t *last_declaration = NULL;
1940         do {
1941                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
1942
1943                 declaration->source_position = token.source_position;
1944                 declaration->symbol          = token.v.symbol;
1945                 next_token();
1946
1947                 if(last_declaration != NULL) {
1948                         last_declaration->next = declaration;
1949                 } else {
1950                         declarations = declaration;
1951                 }
1952                 last_declaration = declaration;
1953
1954                 if(token.type != ',')
1955                         break;
1956                 next_token();
1957         } while(token.type == T_IDENTIFIER);
1958
1959         return declarations;
1960 }
1961
1962 static void semantic_parameter(declaration_t *declaration)
1963 {
1964         /* TODO: improve error messages */
1965
1966         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
1967                 parse_error("typedef not allowed in parameter list");
1968         } else if(declaration->storage_class != STORAGE_CLASS_NONE
1969                         && declaration->storage_class != STORAGE_CLASS_REGISTER) {
1970                 parse_error("parameter may only have none or register storage class");
1971         }
1972
1973         type_t *orig_type = declaration->type;
1974         if(orig_type == NULL)
1975                 return;
1976         type_t *type = skip_typeref(orig_type);
1977
1978         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
1979          * into a pointer. Â§ 6.7.5.3 (7) */
1980         if (is_type_array(type)) {
1981                 const array_type_t *arr_type     = &type->array;
1982                 type_t             *element_type = arr_type->element_type;
1983
1984                 type = make_pointer_type(element_type, type->base.qualifiers);
1985
1986                 declaration->type = type;
1987         }
1988
1989         if(is_type_incomplete(type)) {
1990                 parser_print_error_prefix();
1991                 fprintf(stderr, "incomplete type (");
1992                 print_type_quoted(orig_type);
1993                 fprintf(stderr, ") not allowed for parameter '%s'\n",
1994                         declaration->symbol->string);
1995         }
1996 }
1997
1998 static declaration_t *parse_parameter(void)
1999 {
2000         declaration_specifiers_t specifiers;
2001         memset(&specifiers, 0, sizeof(specifiers));
2002
2003         parse_declaration_specifiers(&specifiers);
2004
2005         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2006
2007         semantic_parameter(declaration);
2008
2009         return declaration;
2010 }
2011
2012 static declaration_t *parse_parameters(function_type_t *type)
2013 {
2014         if(token.type == T_IDENTIFIER) {
2015                 symbol_t *symbol = token.v.symbol;
2016                 if(!is_typedef_symbol(symbol)) {
2017                         type->kr_style_parameters = true;
2018                         return parse_identifier_list();
2019                 }
2020         }
2021
2022         if(token.type == ')') {
2023                 type->unspecified_parameters = 1;
2024                 return NULL;
2025         }
2026         if(token.type == T_void && look_ahead(1)->type == ')') {
2027                 next_token();
2028                 return NULL;
2029         }
2030
2031         declaration_t        *declarations = NULL;
2032         declaration_t        *declaration;
2033         declaration_t        *last_declaration = NULL;
2034         function_parameter_t *parameter;
2035         function_parameter_t *last_parameter = NULL;
2036
2037         while(true) {
2038                 switch(token.type) {
2039                 case T_DOTDOTDOT:
2040                         next_token();
2041                         type->variadic = 1;
2042                         return declarations;
2043
2044                 case T_IDENTIFIER:
2045                 case T___extension__:
2046                 DECLARATION_START
2047                         declaration = parse_parameter();
2048
2049                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
2050                         memset(parameter, 0, sizeof(parameter[0]));
2051                         parameter->type = declaration->type;
2052
2053                         if(last_parameter != NULL) {
2054                                 last_declaration->next = declaration;
2055                                 last_parameter->next   = parameter;
2056                         } else {
2057                                 type->parameters = parameter;
2058                                 declarations     = declaration;
2059                         }
2060                         last_parameter   = parameter;
2061                         last_declaration = declaration;
2062                         break;
2063
2064                 default:
2065                         return declarations;
2066                 }
2067                 if(token.type != ',')
2068                         return declarations;
2069                 next_token();
2070         }
2071 }
2072
2073 typedef enum {
2074         CONSTRUCT_INVALID,
2075         CONSTRUCT_POINTER,
2076         CONSTRUCT_FUNCTION,
2077         CONSTRUCT_ARRAY
2078 } construct_type_type_t;
2079
2080 typedef struct construct_type_t construct_type_t;
2081 struct construct_type_t {
2082         construct_type_type_t  type;
2083         construct_type_t      *next;
2084 };
2085
2086 typedef struct parsed_pointer_t parsed_pointer_t;
2087 struct parsed_pointer_t {
2088         construct_type_t  construct_type;
2089         type_qualifiers_t type_qualifiers;
2090 };
2091
2092 typedef struct construct_function_type_t construct_function_type_t;
2093 struct construct_function_type_t {
2094         construct_type_t  construct_type;
2095         type_t           *function_type;
2096 };
2097
2098 typedef struct parsed_array_t parsed_array_t;
2099 struct parsed_array_t {
2100         construct_type_t  construct_type;
2101         type_qualifiers_t type_qualifiers;
2102         bool              is_static;
2103         bool              is_variable;
2104         expression_t     *size;
2105 };
2106
2107 typedef struct construct_base_type_t construct_base_type_t;
2108 struct construct_base_type_t {
2109         construct_type_t  construct_type;
2110         type_t           *type;
2111 };
2112
2113 static construct_type_t *parse_pointer_declarator(void)
2114 {
2115         eat('*');
2116
2117         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2118         memset(pointer, 0, sizeof(pointer[0]));
2119         pointer->construct_type.type = CONSTRUCT_POINTER;
2120         pointer->type_qualifiers     = parse_type_qualifiers();
2121
2122         return (construct_type_t*) pointer;
2123 }
2124
2125 static construct_type_t *parse_array_declarator(void)
2126 {
2127         eat('[');
2128
2129         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2130         memset(array, 0, sizeof(array[0]));
2131         array->construct_type.type = CONSTRUCT_ARRAY;
2132
2133         if(token.type == T_static) {
2134                 array->is_static = true;
2135                 next_token();
2136         }
2137
2138         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2139         if(type_qualifiers != 0) {
2140                 if(token.type == T_static) {
2141                         array->is_static = true;
2142                         next_token();
2143                 }
2144         }
2145         array->type_qualifiers = type_qualifiers;
2146
2147         if(token.type == '*' && look_ahead(1)->type == ']') {
2148                 array->is_variable = true;
2149                 next_token();
2150         } else if(token.type != ']') {
2151                 array->size = parse_assignment_expression();
2152         }
2153
2154         expect(']');
2155
2156         return (construct_type_t*) array;
2157 }
2158
2159 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2160 {
2161         eat('(');
2162
2163         type_t *type = allocate_type_zero(TYPE_FUNCTION);
2164
2165         declaration_t *parameters = parse_parameters(&type->function);
2166         if(declaration != NULL) {
2167                 declaration->context.declarations = parameters;
2168         }
2169
2170         construct_function_type_t *construct_function_type =
2171                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2172         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2173         construct_function_type->construct_type.type = CONSTRUCT_FUNCTION;
2174         construct_function_type->function_type       = type;
2175
2176         expect(')');
2177
2178         return (construct_type_t*) construct_function_type;
2179 }
2180
2181 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2182                 bool may_be_abstract)
2183 {
2184         /* construct a single linked list of construct_type_t's which describe
2185          * how to construct the final declarator type */
2186         construct_type_t *first = NULL;
2187         construct_type_t *last  = NULL;
2188
2189         /* pointers */
2190         while(token.type == '*') {
2191                 construct_type_t *type = parse_pointer_declarator();
2192
2193                 if(last == NULL) {
2194                         first = type;
2195                         last  = type;
2196                 } else {
2197                         last->next = type;
2198                         last       = type;
2199                 }
2200         }
2201
2202         /* TODO: find out if this is correct */
2203         parse_attributes();
2204
2205         construct_type_t *inner_types = NULL;
2206
2207         switch(token.type) {
2208         case T_IDENTIFIER:
2209                 if(declaration == NULL) {
2210                         parse_error("no identifier expected in typename");
2211                 } else {
2212                         declaration->symbol          = token.v.symbol;
2213                         declaration->source_position = token.source_position;
2214                 }
2215                 next_token();
2216                 break;
2217         case '(':
2218                 next_token();
2219                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2220                 expect(')');
2221                 break;
2222         default:
2223                 if(may_be_abstract)
2224                         break;
2225                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2226                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2227                  * eat '}' */
2228                 if(token.type == '}' && current_function == NULL) {
2229                         next_token();
2230                 } else {
2231                         eat_statement();
2232                 }
2233                 return NULL;
2234         }
2235
2236         construct_type_t *p = last;
2237
2238         while(true) {
2239                 construct_type_t *type;
2240                 switch(token.type) {
2241                 case '(':
2242                         type = parse_function_declarator(declaration);
2243                         break;
2244                 case '[':
2245                         type = parse_array_declarator();
2246                         break;
2247                 default:
2248                         goto declarator_finished;
2249                 }
2250
2251                 /* insert in the middle of the list (behind p) */
2252                 if(p != NULL) {
2253                         type->next = p->next;
2254                         p->next    = type;
2255                 } else {
2256                         type->next = first;
2257                         first      = type;
2258                 }
2259                 if(last == p) {
2260                         last = type;
2261                 }
2262         }
2263
2264 declarator_finished:
2265         parse_attributes();
2266
2267         /* append inner_types at the end of the list, we don't to set last anymore
2268          * as it's not needed anymore */
2269         if(last == NULL) {
2270                 assert(first == NULL);
2271                 first = inner_types;
2272         } else {
2273                 last->next = inner_types;
2274         }
2275
2276         return first;
2277 }
2278
2279 static type_t *construct_declarator_type(construct_type_t *construct_list,
2280                                          type_t *type)
2281 {
2282         construct_type_t *iter = construct_list;
2283         for( ; iter != NULL; iter = iter->next) {
2284                 switch(iter->type) {
2285                 case CONSTRUCT_INVALID:
2286                         panic("invalid type construction found");
2287                 case CONSTRUCT_FUNCTION: {
2288                         construct_function_type_t *construct_function_type
2289                                 = (construct_function_type_t*) iter;
2290
2291                         type_t *function_type = construct_function_type->function_type;
2292
2293                         function_type->function.return_type = type;
2294
2295                         type = function_type;
2296                         break;
2297                 }
2298
2299                 case CONSTRUCT_POINTER: {
2300                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2301                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER);
2302                         pointer_type->pointer.points_to  = type;
2303                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2304
2305                         type = pointer_type;
2306                         break;
2307                 }
2308
2309                 case CONSTRUCT_ARRAY: {
2310                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2311                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY);
2312
2313                         array_type->base.qualifiers    = parsed_array->type_qualifiers;
2314                         array_type->array.element_type = type;
2315                         array_type->array.is_static    = parsed_array->is_static;
2316                         array_type->array.is_variable  = parsed_array->is_variable;
2317                         array_type->array.size         = parsed_array->size;
2318
2319                         type = array_type;
2320                         break;
2321                 }
2322                 }
2323
2324                 type_t *hashed_type = typehash_insert(type);
2325                 if(hashed_type != type) {
2326                         /* the function type was constructed earlier freeing it here will
2327                          * destroy other types... */
2328                         if(iter->type != CONSTRUCT_FUNCTION) {
2329                                 free_type(type);
2330                         }
2331                         type = hashed_type;
2332                 }
2333         }
2334
2335         return type;
2336 }
2337
2338 static declaration_t *parse_declarator(
2339                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2340 {
2341         type_t        *type         = specifiers->type;
2342         declaration_t *declaration  = allocate_ast_zero(sizeof(declaration[0]));
2343         declaration->storage_class  = specifiers->storage_class;
2344         declaration->decl_modifiers = specifiers->decl_modifiers;
2345         declaration->is_inline      = specifiers->is_inline;
2346
2347         construct_type_t *construct_type
2348                 = parse_inner_declarator(declaration, may_be_abstract);
2349         declaration->type = construct_declarator_type(construct_type, type);
2350
2351         if(construct_type != NULL) {
2352                 obstack_free(&temp_obst, construct_type);
2353         }
2354
2355         return declaration;
2356 }
2357
2358 static type_t *parse_abstract_declarator(type_t *base_type)
2359 {
2360         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2361
2362         type_t *result = construct_declarator_type(construct_type, base_type);
2363         if(construct_type != NULL) {
2364                 obstack_free(&temp_obst, construct_type);
2365         }
2366
2367         return result;
2368 }
2369
2370 static declaration_t *record_declaration(declaration_t *declaration)
2371 {
2372         assert(declaration->parent_context == NULL);
2373         assert(context != NULL);
2374
2375         symbol_t *symbol = declaration->symbol;
2376         if(symbol != NULL) {
2377                 declaration_t *alias = environment_push(declaration);
2378                 if(alias != declaration)
2379                         return alias;
2380         } else {
2381                 declaration->parent_context = context;
2382         }
2383
2384         if(last_declaration != NULL) {
2385                 last_declaration->next = declaration;
2386         } else {
2387                 context->declarations = declaration;
2388         }
2389         last_declaration = declaration;
2390
2391         return declaration;
2392 }
2393
2394 static void parser_error_multiple_definition(declaration_t *declaration,
2395                 const source_position_t source_position)
2396 {
2397         parser_print_error_prefix_pos(source_position);
2398         fprintf(stderr, "multiple definition of symbol '%s'\n",
2399                 declaration->symbol->string);
2400         parser_print_error_prefix_pos(declaration->source_position);
2401         fprintf(stderr, "this is the location of the previous definition.\n");
2402 }
2403
2404 static bool is_declaration_specifier(const token_t *token,
2405                                      bool only_type_specifiers)
2406 {
2407         switch(token->type) {
2408                 TYPE_SPECIFIERS
2409                         return true;
2410                 case T_IDENTIFIER:
2411                         return is_typedef_symbol(token->v.symbol);
2412
2413                 case T___extension__:
2414                 STORAGE_CLASSES
2415                 TYPE_QUALIFIERS
2416                         return !only_type_specifiers;
2417
2418                 default:
2419                         return false;
2420         }
2421 }
2422
2423 static void parse_init_declarator_rest(declaration_t *declaration)
2424 {
2425         eat('=');
2426
2427         type_t *orig_type = declaration->type;
2428         type_t *type      = NULL;
2429         if(orig_type != NULL)
2430                 type = skip_typeref(orig_type);
2431
2432         if(declaration->init.initializer != NULL) {
2433                 parser_error_multiple_definition(declaration, token.source_position);
2434         }
2435
2436         initializer_t *initializer = parse_initializer(type);
2437
2438         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
2439          * the array type size */
2440         if(type != NULL && is_type_array(type) && initializer != NULL) {
2441                 array_type_t *array_type = &type->array;
2442
2443                 if(array_type->size == NULL) {
2444                         expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2445
2446                         cnst->base.datatype = type_size_t;
2447
2448                         switch (initializer->kind) {
2449                                 case INITIALIZER_LIST: {
2450                                         initializer_list_t *const list = &initializer->list;
2451                                         cnst->conste.v.int_value = list->len;
2452                                         break;
2453                                 }
2454
2455                                 case INITIALIZER_STRING: {
2456                                         initializer_string_t *const string = &initializer->string;
2457                                         cnst->conste.v.int_value = strlen(string->string) + 1;
2458                                         break;
2459                                 }
2460
2461                                 case INITIALIZER_WIDE_STRING: {
2462                                         initializer_wide_string_t *const string = &initializer->wide_string;
2463                                         cnst->conste.v.int_value = string->string.size;
2464                                         break;
2465                                 }
2466
2467                                 default:
2468                                         panic("invalid initializer type");
2469                         }
2470
2471                         array_type->size = cnst;
2472                 }
2473         }
2474
2475         if(type != NULL && is_type_function(type)) {
2476                 parser_print_error_prefix_pos(declaration->source_position);
2477                 fprintf(stderr, "initializers not allowed for function types at "
2478                                 "declator '%s' (type ", declaration->symbol->string);
2479                 print_type_quoted(orig_type);
2480                 fprintf(stderr, ")\n");
2481         } else {
2482                 declaration->init.initializer = initializer;
2483         }
2484 }
2485
2486 /* parse rest of a declaration without any declarator */
2487 static void parse_anonymous_declaration_rest(
2488                 const declaration_specifiers_t *specifiers,
2489                 parsed_declaration_func finished_declaration)
2490 {
2491         eat(';');
2492
2493         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2494
2495         declaration->type            = specifiers->type;
2496         declaration->storage_class   = specifiers->storage_class;
2497         declaration->source_position = specifiers->source_position;
2498
2499         if (declaration->storage_class != STORAGE_CLASS_NONE) {
2500                 parse_warning_pos(declaration->source_position,
2501                                 "useless storage class in empty declaration");
2502         }
2503
2504         type_t *type = declaration->type;
2505         switch (type->kind) {
2506                 case TYPE_COMPOUND_STRUCT:
2507                 case TYPE_COMPOUND_UNION: {
2508                         const compound_type_t *compound_type = &type->compound;
2509                         if (compound_type->declaration->symbol == NULL) {
2510                                 parse_warning_pos(declaration->source_position,
2511                                                 "unnamed struct/union that defines no instances");
2512                         }
2513                         break;
2514                 }
2515
2516                 case TYPE_ENUM:
2517                         break;
2518
2519                 default:
2520                         parse_warning_pos(declaration->source_position,
2521                                           "empty declaration");
2522                         break;
2523         }
2524
2525         finished_declaration(declaration);
2526 }
2527
2528 static void parse_declaration_rest(declaration_t *ndeclaration,
2529                 const declaration_specifiers_t *specifiers,
2530                 parsed_declaration_func finished_declaration)
2531 {
2532         while(true) {
2533                 declaration_t *declaration = finished_declaration(ndeclaration);
2534
2535                 type_t *orig_type = declaration->type;
2536                 type_t *type      = skip_typeref(orig_type);
2537
2538                 if(type->kind != TYPE_FUNCTION && declaration->is_inline) {
2539                         parser_print_warning_prefix_pos(declaration->source_position);
2540                         fprintf(stderr, "variable '%s' declared 'inline'\n",
2541                                         declaration->symbol->string);
2542                 }
2543
2544                 if(token.type == '=') {
2545                         parse_init_declarator_rest(declaration);
2546                 }
2547
2548                 if(token.type != ',')
2549                         break;
2550                 eat(',');
2551
2552                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2553         }
2554         expect_void(';');
2555 }
2556
2557 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2558 {
2559         /* TODO: check that it was actually a parameter that gets a type */
2560
2561         /* we should have a declaration for the parameter in the current
2562          * scope */
2563         return record_declaration(declaration);
2564 }
2565
2566 static void parse_declaration(parsed_declaration_func finished_declaration)
2567 {
2568         declaration_specifiers_t specifiers;
2569         memset(&specifiers, 0, sizeof(specifiers));
2570         parse_declaration_specifiers(&specifiers);
2571
2572         if(token.type == ';') {
2573                 parse_anonymous_declaration_rest(&specifiers, finished_declaration);
2574         } else {
2575                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2576                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2577         }
2578 }
2579
2580 static void parse_kr_declaration_list(declaration_t *declaration)
2581 {
2582         type_t *type = skip_typeref(declaration->type);
2583         if(!is_type_function(type))
2584                 return;
2585
2586         if(!type->function.kr_style_parameters)
2587                 return;
2588
2589         /* push function parameters */
2590         int         top          = environment_top();
2591         context_t  *last_context = context;
2592         set_context(&declaration->context);
2593
2594         declaration_t *parameter = declaration->context.declarations;
2595         for( ; parameter != NULL; parameter = parameter->next) {
2596                 environment_push(parameter);
2597         }
2598
2599         /* parse declaration list */
2600         while(is_declaration_specifier(&token, false)) {
2601                 parse_declaration(finished_kr_declaration);
2602         }
2603
2604         /* pop function parameters */
2605         assert(context == &declaration->context);
2606         set_context(last_context);
2607         environment_pop_to(top);
2608
2609         /* update function type */
2610         type_t *new_type = duplicate_type(type);
2611         new_type->function.kr_style_parameters = false;
2612
2613         function_parameter_t *parameters     = NULL;
2614         function_parameter_t *last_parameter = NULL;
2615
2616         declaration_t *parameter_declaration = declaration->context.declarations;
2617         for( ; parameter_declaration != NULL;
2618                         parameter_declaration = parameter_declaration->next) {
2619                 type_t *parameter_type = parameter_declaration->type;
2620                 if(parameter_type == NULL) {
2621 #ifdef STRICT_C99
2622                         parser_print_error_prefix();
2623                         fprintf(stderr, "no type specified for function parameter '%s'\n",
2624                                 parameter_declaration->symbol->string);
2625 #else
2626                         parser_print_warning_prefix();
2627                         fprintf(stderr, "no type specified for function parameter '%s', "
2628                                 "using int\n", parameter_declaration->symbol->string);
2629                         parameter_type              = type_int;
2630                         parameter_declaration->type = parameter_type;
2631 #endif
2632                 }
2633
2634                 semantic_parameter(parameter_declaration);
2635                 parameter_type = parameter_declaration->type;
2636
2637                 function_parameter_t *function_parameter
2638                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2639                 memset(function_parameter, 0, sizeof(function_parameter[0]));
2640
2641                 function_parameter->type = parameter_type;
2642                 if(last_parameter != NULL) {
2643                         last_parameter->next = function_parameter;
2644                 } else {
2645                         parameters = function_parameter;
2646                 }
2647                 last_parameter = function_parameter;
2648         }
2649         new_type->function.parameters = parameters;
2650
2651         type = typehash_insert(new_type);
2652         if(type != new_type) {
2653                 obstack_free(type_obst, new_type);
2654         }
2655
2656         declaration->type = type;
2657 }
2658
2659 static void parse_external_declaration(void)
2660 {
2661         /* function-definitions and declarations both start with declaration
2662          * specifiers */
2663         declaration_specifiers_t specifiers;
2664         memset(&specifiers, 0, sizeof(specifiers));
2665         parse_declaration_specifiers(&specifiers);
2666
2667         /* must be a declaration */
2668         if(token.type == ';') {
2669                 parse_anonymous_declaration_rest(&specifiers, record_declaration);
2670                 return;
2671         }
2672
2673         /* declarator is common to both function-definitions and declarations */
2674         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2675
2676         /* must be a declaration */
2677         if(token.type == ',' || token.type == '=' || token.type == ';') {
2678                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
2679                 return;
2680         }
2681
2682         /* must be a function definition */
2683         parse_kr_declaration_list(ndeclaration);
2684
2685         if(token.type != '{') {
2686                 parse_error_expected("while parsing function definition", '{', 0);
2687                 eat_statement();
2688                 return;
2689         }
2690
2691         type_t *type = ndeclaration->type;
2692         if(type == NULL) {
2693                 eat_block();
2694                 return;
2695         }
2696
2697         /* note that we don't skip typerefs: the standard doesn't allow them here
2698          * (so we can't use is_type_function here) */
2699         if(type->kind != TYPE_FUNCTION) {
2700                 parser_print_error_prefix();
2701                 fprintf(stderr, "declarator '");
2702                 print_type_ext(type, ndeclaration->symbol, NULL);
2703                 fprintf(stderr, "' has a body but is not a function type.\n");
2704                 eat_block();
2705                 return;
2706         }
2707
2708         /* Â§ 6.7.5.3 (14) a function definition with () means no
2709          * parameters (and not unspecified parameters) */
2710         if(type->function.unspecified_parameters) {
2711                 type_t *duplicate = duplicate_type(type);
2712                 duplicate->function.unspecified_parameters = false;
2713
2714                 type = typehash_insert(duplicate);
2715                 if(type != duplicate) {
2716                         obstack_free(type_obst, duplicate);
2717                 }
2718                 ndeclaration->type = type;
2719         }
2720
2721         declaration_t *declaration = record_declaration(ndeclaration);
2722         if(ndeclaration != declaration) {
2723                 memcpy(&declaration->context, &ndeclaration->context,
2724                                 sizeof(declaration->context));
2725         }
2726         type = skip_typeref(declaration->type);
2727
2728         /* push function parameters and switch context */
2729         int         top          = environment_top();
2730         context_t  *last_context = context;
2731         set_context(&declaration->context);
2732
2733         declaration_t *parameter = declaration->context.declarations;
2734         for( ; parameter != NULL; parameter = parameter->next) {
2735                 environment_push(parameter);
2736         }
2737
2738         if(declaration->init.statement != NULL) {
2739                 parser_error_multiple_definition(declaration, token.source_position);
2740                 eat_block();
2741                 goto end_of_parse_external_declaration;
2742         } else {
2743                 /* parse function body */
2744                 int            label_stack_top      = label_top();
2745                 declaration_t *old_current_function = current_function;
2746                 current_function                    = declaration;
2747
2748                 declaration->init.statement = parse_compound_statement();
2749
2750                 assert(current_function == declaration);
2751                 current_function = old_current_function;
2752                 label_pop_to(label_stack_top);
2753         }
2754
2755 end_of_parse_external_declaration:
2756         assert(context == &declaration->context);
2757         set_context(last_context);
2758         environment_pop_to(top);
2759 }
2760
2761 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2762 {
2763         while(1) {
2764                 if(token.type == ':') {
2765                         next_token();
2766                         parse_constant_expression();
2767                         /* TODO (bitfields) */
2768                 } else {
2769                         declaration_t *declaration = parse_declarator(specifiers, /*may_be_abstract=*/true);
2770
2771                         /* TODO: check constraints for struct declarations */
2772                         /* TODO: check for doubled fields */
2773                         record_declaration(declaration);
2774
2775                         if(token.type == ':') {
2776                                 next_token();
2777                                 parse_constant_expression();
2778                                 /* TODO (bitfields) */
2779                         }
2780                 }
2781
2782                 if(token.type != ',')
2783                         break;
2784                 next_token();
2785         }
2786         expect_void(';');
2787 }
2788
2789 static void parse_compound_type_entries(void)
2790 {
2791         eat('{');
2792
2793         while(token.type != '}' && token.type != T_EOF) {
2794                 declaration_specifiers_t specifiers;
2795                 memset(&specifiers, 0, sizeof(specifiers));
2796                 parse_declaration_specifiers(&specifiers);
2797
2798                 parse_struct_declarators(&specifiers);
2799         }
2800         if(token.type == T_EOF) {
2801                 parse_error("EOF while parsing struct");
2802         }
2803         next_token();
2804 }
2805
2806 static type_t *parse_typename(void)
2807 {
2808         declaration_specifiers_t specifiers;
2809         memset(&specifiers, 0, sizeof(specifiers));
2810         parse_declaration_specifiers(&specifiers);
2811         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2812                 /* TODO: improve error message, user does probably not know what a
2813                  * storage class is...
2814                  */
2815                 parse_error("typename may not have a storage class");
2816         }
2817
2818         type_t *result = parse_abstract_declarator(specifiers.type);
2819
2820         return result;
2821 }
2822
2823
2824
2825
2826 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2827 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2828                                                           expression_t *left);
2829
2830 typedef struct expression_parser_function_t expression_parser_function_t;
2831 struct expression_parser_function_t {
2832         unsigned                         precedence;
2833         parse_expression_function        parser;
2834         unsigned                         infix_precedence;
2835         parse_expression_infix_function  infix_parser;
2836 };
2837
2838 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2839
2840 static expression_t *create_invalid_expression(void)
2841 {
2842         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2843         expression->base.source_position = token.source_position;
2844         return expression;
2845 }
2846
2847 static expression_t *expected_expression_error(void)
2848 {
2849         parser_print_error_prefix();
2850         fprintf(stderr, "expected expression, got token ");
2851         print_token(stderr, &token);
2852         fprintf(stderr, "\n");
2853
2854         next_token();
2855
2856         return create_invalid_expression();
2857 }
2858
2859 static expression_t *parse_string_const(void)
2860 {
2861         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2862         cnst->base.datatype = type_string;
2863         cnst->string.value  = parse_string_literals();
2864
2865         return cnst;
2866 }
2867
2868 static expression_t *parse_wide_string_const(void)
2869 {
2870         expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
2871         cnst->base.datatype      = type_wchar_t_ptr;
2872         cnst->wide_string.value  = token.v.wide_string; /* TODO concatenate */
2873         next_token();
2874         return cnst;
2875 }
2876
2877 static expression_t *parse_int_const(void)
2878 {
2879         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2880         cnst->base.datatype      = token.datatype;
2881         cnst->conste.v.int_value = token.v.intvalue;
2882
2883         next_token();
2884
2885         return cnst;
2886 }
2887
2888 static expression_t *parse_float_const(void)
2889 {
2890         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2891         cnst->base.datatype        = token.datatype;
2892         cnst->conste.v.float_value = token.v.floatvalue;
2893
2894         next_token();
2895
2896         return cnst;
2897 }
2898
2899 static declaration_t *create_implicit_function(symbol_t *symbol,
2900                 const source_position_t source_position)
2901 {
2902         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2903         ntype->function.return_type            = type_int;
2904         ntype->function.unspecified_parameters = true;
2905
2906         type_t *type = typehash_insert(ntype);
2907         if(type != ntype) {
2908                 free_type(ntype);
2909         }
2910
2911         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2912
2913         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2914         declaration->type            = type;
2915         declaration->symbol          = symbol;
2916         declaration->source_position = source_position;
2917
2918         /* prepend the implicit definition to the global context
2919          * this is safe since the symbol wasn't declared as anything else yet
2920          */
2921         assert(symbol->declaration == NULL);
2922
2923         context_t *last_context = context;
2924         context = global_context;
2925
2926         environment_push(declaration);
2927         declaration->next     = context->declarations;
2928         context->declarations = declaration;
2929
2930         context = last_context;
2931
2932         return declaration;
2933 }
2934
2935 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
2936 {
2937         function_parameter_t *parameter
2938                 = obstack_alloc(type_obst, sizeof(parameter[0]));
2939         memset(parameter, 0, sizeof(parameter[0]));
2940         parameter->type = argument_type;
2941
2942         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
2943         type->function.return_type = return_type;
2944         type->function.parameters  = parameter;
2945
2946         type_t *result = typehash_insert(type);
2947         if(result != type) {
2948                 free_type(type);
2949         }
2950
2951         return result;
2952 }
2953
2954 static type_t *get_builtin_symbol_type(symbol_t *symbol)
2955 {
2956         switch(symbol->ID) {
2957         case T___builtin_alloca:
2958                 return make_function_1_type(type_void_ptr, type_size_t);
2959         case T___builtin_nan:
2960                 return make_function_1_type(type_double, type_string);
2961         case T___builtin_nanf:
2962                 return make_function_1_type(type_float, type_string);
2963         case T___builtin_nand:
2964                 return make_function_1_type(type_long_double, type_string);
2965         case T___builtin_va_end:
2966                 return make_function_1_type(type_void, type_valist);
2967         default:
2968                 panic("not implemented builtin symbol found");
2969         }
2970 }
2971
2972 /**
2973  * performs automatic type cast as described in Â§ 6.3.2.1
2974  */
2975 static type_t *automatic_type_conversion(type_t *orig_type)
2976 {
2977         if(orig_type == NULL)
2978                 return NULL;
2979
2980         type_t *type = skip_typeref(orig_type);
2981         if(is_type_array(type)) {
2982                 array_type_t *array_type   = &type->array;
2983                 type_t       *element_type = array_type->element_type;
2984                 unsigned      qualifiers   = array_type->type.qualifiers;
2985
2986                 return make_pointer_type(element_type, qualifiers);
2987         }
2988
2989         if(is_type_function(type)) {
2990                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
2991         }
2992
2993         return orig_type;
2994 }
2995
2996 /**
2997  * reverts the automatic casts of array to pointer types and function
2998  * to function-pointer types as defined Â§ 6.3.2.1
2999  */
3000 type_t *revert_automatic_type_conversion(const expression_t *expression)
3001 {
3002         if(expression->base.datatype == NULL)
3003                 return NULL;
3004
3005         switch(expression->kind) {
3006         case EXPR_REFERENCE: {
3007                 const reference_expression_t *ref = &expression->reference;
3008                 return ref->declaration->type;
3009         }
3010         case EXPR_SELECT: {
3011                 const select_expression_t *select = &expression->select;
3012                 return select->compound_entry->type;
3013         }
3014         case EXPR_UNARY_DEREFERENCE: {
3015                 expression_t   *value        = expression->unary.value;
3016                 type_t         *type         = skip_typeref(value->base.datatype);
3017                 pointer_type_t *pointer_type = &type->pointer;
3018
3019                 return pointer_type->points_to;
3020         }
3021         case EXPR_BUILTIN_SYMBOL: {
3022                 const builtin_symbol_expression_t *builtin
3023                         = &expression->builtin_symbol;
3024                 return get_builtin_symbol_type(builtin->symbol);
3025         }
3026         case EXPR_ARRAY_ACCESS: {
3027                 const array_access_expression_t *array_access
3028                         = &expression->array_access;
3029                 const expression_t *array_ref = array_access->array_ref;
3030                 type_t *type_left  = skip_typeref(array_ref->base.datatype);
3031                 assert(is_type_pointer(type_left));
3032                 pointer_type_t *pointer_type = &type_left->pointer;
3033                 return pointer_type->points_to;
3034         }
3035
3036         default:
3037                 break;
3038         }
3039
3040         return expression->base.datatype;
3041 }
3042
3043 static expression_t *parse_reference(void)
3044 {
3045         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3046
3047         reference_expression_t *ref = &expression->reference;
3048         ref->symbol = token.v.symbol;
3049
3050         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3051
3052         source_position_t source_position = token.source_position;
3053         next_token();
3054
3055         if(declaration == NULL) {
3056 #ifndef STRICT_C99
3057                 /* an implicitly defined function */
3058                 if(token.type == '(') {
3059                         parser_print_prefix_pos(token.source_position);
3060                         fprintf(stderr, "warning: implicit declaration of function '%s'\n",
3061                                 ref->symbol->string);
3062
3063                         declaration = create_implicit_function(ref->symbol,
3064                                                                source_position);
3065                 } else
3066 #endif
3067                 {
3068                         parser_print_error_prefix();
3069                         fprintf(stderr, "unknown symbol '%s' found.\n", ref->symbol->string);
3070                         return expression;
3071                 }
3072         }
3073
3074         type_t *type = declaration->type;
3075         /* we always do the auto-type conversions; the & and sizeof parser contains
3076          * code to revert this! */
3077         type = automatic_type_conversion(type);
3078
3079         ref->declaration         = declaration;
3080         ref->expression.datatype = type;
3081
3082         return expression;
3083 }
3084
3085 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3086 {
3087         (void) expression;
3088         (void) dest_type;
3089         /* TODO check if explicit cast is allowed and issue warnings/errors */
3090 }
3091
3092 static expression_t *parse_cast(void)
3093 {
3094         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3095
3096         cast->base.source_position = token.source_position;
3097
3098         type_t *type  = parse_typename();
3099
3100         expect(')');
3101         expression_t *value = parse_sub_expression(20);
3102
3103         check_cast_allowed(value, type);
3104
3105         cast->base.datatype = type;
3106         cast->unary.value   = value;
3107
3108         return cast;
3109 }
3110
3111 static expression_t *parse_statement_expression(void)
3112 {
3113         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3114
3115         statement_t *statement          = parse_compound_statement();
3116         expression->statement.statement = statement;
3117         if(statement == NULL) {
3118                 expect(')');
3119                 return NULL;
3120         }
3121
3122         assert(statement->kind == STATEMENT_COMPOUND);
3123         compound_statement_t *compound_statement = &statement->compound;
3124
3125         /* find last statement and use it's type */
3126         const statement_t *last_statement = NULL;
3127         const statement_t *iter           = compound_statement->statements;
3128         for( ; iter != NULL; iter = iter->base.next) {
3129                 last_statement = iter;
3130         }
3131
3132         if(last_statement->kind == STATEMENT_EXPRESSION) {
3133                 const expression_statement_t *expression_statement
3134                         = &last_statement->expression;
3135                 expression->base.datatype
3136                         = expression_statement->expression->base.datatype;
3137         } else {
3138                 expression->base.datatype = type_void;
3139         }
3140
3141         expect(')');
3142
3143         return expression;
3144 }
3145
3146 static expression_t *parse_brace_expression(void)
3147 {
3148         eat('(');
3149
3150         switch(token.type) {
3151         case '{':
3152                 /* gcc extension: a statement expression */
3153                 return parse_statement_expression();
3154
3155         TYPE_QUALIFIERS
3156         TYPE_SPECIFIERS
3157                 return parse_cast();
3158         case T_IDENTIFIER:
3159                 if(is_typedef_symbol(token.v.symbol)) {
3160                         return parse_cast();
3161                 }
3162         }
3163
3164         expression_t *result = parse_expression();
3165         expect(')');
3166
3167         return result;
3168 }
3169
3170 static expression_t *parse_function_keyword(void)
3171 {
3172         next_token();
3173         /* TODO */
3174
3175         if (current_function == NULL) {
3176                 parse_error("'__func__' used outside of a function");
3177         }
3178
3179         string_literal_expression_t *expression
3180                 = allocate_ast_zero(sizeof(expression[0]));
3181
3182         expression->expression.kind     = EXPR_FUNCTION;
3183         expression->expression.datatype = type_string;
3184         expression->value               = current_function->symbol->string;
3185
3186         return (expression_t*) expression;
3187 }
3188
3189 static expression_t *parse_pretty_function_keyword(void)
3190 {
3191         eat(T___PRETTY_FUNCTION__);
3192         /* TODO */
3193
3194         if (current_function == NULL) {
3195                 parse_error("'__PRETTY_FUNCTION__' used outside of a function");
3196         }
3197
3198         string_literal_expression_t *expression
3199                 = allocate_ast_zero(sizeof(expression[0]));
3200
3201         expression->expression.kind     = EXPR_PRETTY_FUNCTION;
3202         expression->expression.datatype = type_string;
3203         expression->value               = current_function->symbol->string;
3204
3205         return (expression_t*) expression;
3206 }
3207
3208 static designator_t *parse_designator(void)
3209 {
3210         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3211
3212         if(token.type != T_IDENTIFIER) {
3213                 parse_error_expected("while parsing member designator",
3214                                      T_IDENTIFIER, 0);
3215                 eat_paren();
3216                 return NULL;
3217         }
3218         result->symbol = token.v.symbol;
3219         next_token();
3220
3221         designator_t *last_designator = result;
3222         while(true) {
3223                 if(token.type == '.') {
3224                         next_token();
3225                         if(token.type != T_IDENTIFIER) {
3226                                 parse_error_expected("while parsing member designator",
3227                                                      T_IDENTIFIER, 0);
3228                                 eat_paren();
3229                                 return NULL;
3230                         }
3231                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3232                         designator->symbol       = token.v.symbol;
3233                         next_token();
3234
3235                         last_designator->next = designator;
3236                         last_designator       = designator;
3237                         continue;
3238                 }
3239                 if(token.type == '[') {
3240                         next_token();
3241                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3242                         designator->array_access = parse_expression();
3243                         if(designator->array_access == NULL) {
3244                                 eat_paren();
3245                                 return NULL;
3246                         }
3247                         expect(']');
3248
3249                         last_designator->next = designator;
3250                         last_designator       = designator;
3251                         continue;
3252                 }
3253                 break;
3254         }
3255
3256         return result;
3257 }
3258
3259 static expression_t *parse_offsetof(void)
3260 {
3261         eat(T___builtin_offsetof);
3262
3263         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3264         expression->base.datatype = type_size_t;
3265
3266         expect('(');
3267         expression->offsetofe.type = parse_typename();
3268         expect(',');
3269         expression->offsetofe.designator = parse_designator();
3270         expect(')');
3271
3272         return expression;
3273 }
3274
3275 static expression_t *parse_va_start(void)
3276 {
3277         eat(T___builtin_va_start);
3278
3279         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3280
3281         expect('(');
3282         expression->va_starte.ap = parse_assignment_expression();
3283         expect(',');
3284         expression_t *const expr = parse_assignment_expression();
3285         if (expr->kind == EXPR_REFERENCE) {
3286                 declaration_t *const decl = expr->reference.declaration;
3287                 if (decl->parent_context == &current_function->context &&
3288                     decl->next == NULL) {
3289                         expression->va_starte.parameter = decl;
3290                         expect(')');
3291                         return expression;
3292                 }
3293         }
3294         parser_print_error_prefix_pos(expr->base.source_position);
3295         fprintf(stderr, "second argument of 'va_start' must be last parameter "
3296                         "of the current function\n");
3297
3298         return create_invalid_expression();
3299 }
3300
3301 static expression_t *parse_va_arg(void)
3302 {
3303         eat(T___builtin_va_arg);
3304
3305         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3306
3307         expect('(');
3308         expression->va_arge.ap = parse_assignment_expression();
3309         expect(',');
3310         expression->base.datatype = parse_typename();
3311         expect(')');
3312
3313         return expression;
3314 }
3315
3316 static expression_t *parse_builtin_symbol(void)
3317 {
3318         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3319
3320         symbol_t *symbol = token.v.symbol;
3321
3322         expression->builtin_symbol.symbol = symbol;
3323         next_token();
3324
3325         type_t *type = get_builtin_symbol_type(symbol);
3326         type = automatic_type_conversion(type);
3327
3328         expression->base.datatype = type;
3329         return expression;
3330 }
3331
3332 static expression_t *parse_compare_builtin(void)
3333 {
3334         expression_t *expression;
3335
3336         switch(token.type) {
3337         case T___builtin_isgreater:
3338                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3339                 break;
3340         case T___builtin_isgreaterequal:
3341                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3342                 break;
3343         case T___builtin_isless:
3344                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
3345                 break;
3346         case T___builtin_islessequal:
3347                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
3348                 break;
3349         case T___builtin_islessgreater:
3350                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
3351                 break;
3352         case T___builtin_isunordered:
3353                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
3354                 break;
3355         default:
3356                 panic("invalid compare builtin found");
3357                 break;
3358         }
3359         next_token();
3360
3361         expect('(');
3362         expression->binary.left = parse_assignment_expression();
3363         expect(',');
3364         expression->binary.right = parse_assignment_expression();
3365         expect(')');
3366
3367         type_t *orig_type_left  = expression->binary.left->base.datatype;
3368         type_t *orig_type_right = expression->binary.right->base.datatype;
3369         if(orig_type_left == NULL || orig_type_right == NULL)
3370                 return expression;
3371
3372         type_t *type_left  = skip_typeref(orig_type_left);
3373         type_t *type_right = skip_typeref(orig_type_right);
3374         if(!is_type_floating(type_left) && !is_type_floating(type_right)) {
3375                 type_error_incompatible("invalid operands in comparison",
3376                                         token.source_position, type_left, type_right);
3377         } else {
3378                 semantic_comparison(&expression->binary);
3379         }
3380
3381         return expression;
3382 }
3383
3384 static expression_t *parse_builtin_expect(void)
3385 {
3386         eat(T___builtin_expect);
3387
3388         expression_t *expression
3389                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
3390
3391         expect('(');
3392         expression->binary.left = parse_assignment_expression();
3393         expect(',');
3394         expression->binary.right = parse_constant_expression();
3395         expect(')');
3396
3397         expression->base.datatype = expression->binary.left->base.datatype;
3398
3399         return expression;
3400 }
3401
3402 static expression_t *parse_assume(void) {
3403         eat(T_assume);
3404
3405         expression_t *expression
3406                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
3407
3408         expect('(');
3409         expression->unary.value = parse_expression();
3410         expect(')');
3411
3412         expression->base.datatype = type_void;
3413         return expression;
3414 }
3415
3416 static expression_t *parse_alignof(void) {
3417         eat(T___alignof__);
3418
3419         expression_t *expression
3420                 = allocate_expression_zero(EXPR_ALIGNOF);
3421
3422         expect('(');
3423         expression->alignofe.type = parse_typename();
3424         expect(')');
3425
3426         expression->base.datatype = type_size_t;
3427         return expression;
3428 }
3429
3430 static expression_t *parse_primary_expression(void)
3431 {
3432         switch(token.type) {
3433         case T_INTEGER:
3434                 return parse_int_const();
3435         case T_FLOATINGPOINT:
3436                 return parse_float_const();
3437         case T_STRING_LITERAL: /* TODO merge */
3438                 return parse_string_const();
3439         case T_WIDE_STRING_LITERAL:
3440                 return parse_wide_string_const();
3441         case T_IDENTIFIER:
3442                 return parse_reference();
3443         case T___FUNCTION__:
3444         case T___func__:
3445                 return parse_function_keyword();
3446         case T___PRETTY_FUNCTION__:
3447                 return parse_pretty_function_keyword();
3448         case T___builtin_offsetof:
3449                 return parse_offsetof();
3450         case T___builtin_va_start:
3451                 return parse_va_start();
3452         case T___builtin_va_arg:
3453                 return parse_va_arg();
3454         case T___builtin_expect:
3455                 return parse_builtin_expect();
3456         case T___builtin_nanf:
3457         case T___builtin_alloca:
3458         case T___builtin_va_end:
3459                 return parse_builtin_symbol();
3460         case T___builtin_isgreater:
3461         case T___builtin_isgreaterequal:
3462         case T___builtin_isless:
3463         case T___builtin_islessequal:
3464         case T___builtin_islessgreater:
3465         case T___builtin_isunordered:
3466                 return parse_compare_builtin();
3467         case T___alignof__:
3468                 return parse_alignof();
3469         case T_assume:
3470                 return parse_assume();
3471
3472         case '(':
3473                 return parse_brace_expression();
3474         }
3475
3476         parser_print_error_prefix();
3477         fprintf(stderr, "unexpected token ");
3478         print_token(stderr, &token);
3479         fprintf(stderr, "\n");
3480         eat_statement();
3481
3482         return create_invalid_expression();
3483 }
3484
3485 static expression_t *parse_array_expression(unsigned precedence,
3486                                             expression_t *left)
3487 {
3488         (void) precedence;
3489
3490         eat('[');
3491
3492         expression_t *inside = parse_expression();
3493
3494         array_access_expression_t *array_access
3495                 = allocate_ast_zero(sizeof(array_access[0]));
3496
3497         array_access->expression.kind = EXPR_ARRAY_ACCESS;
3498
3499         type_t *type_left   = left->base.datatype;
3500         type_t *type_inside = inside->base.datatype;
3501         type_t *return_type = NULL;
3502
3503         if(type_left != NULL && type_inside != NULL) {
3504                 type_left   = skip_typeref(type_left);
3505                 type_inside = skip_typeref(type_inside);
3506
3507                 if(is_type_pointer(type_left)) {
3508                         pointer_type_t *pointer = &type_left->pointer;
3509                         return_type             = pointer->points_to;
3510                         array_access->array_ref = left;
3511                         array_access->index     = inside;
3512                 } else if(is_type_pointer(type_inside)) {
3513                         pointer_type_t *pointer = &type_inside->pointer;
3514                         return_type             = pointer->points_to;
3515                         array_access->array_ref = inside;
3516                         array_access->index     = left;
3517                         array_access->flipped   = true;
3518                 } else {
3519                         parser_print_error_prefix();
3520                         fprintf(stderr, "array access on object with non-pointer types ");
3521                         print_type_quoted(type_left);
3522                         fprintf(stderr, ", ");
3523                         print_type_quoted(type_inside);
3524                         fprintf(stderr, "\n");
3525                 }
3526         } else {
3527                 array_access->array_ref = left;
3528                 array_access->index     = inside;
3529         }
3530
3531         if(token.type != ']') {
3532                 parse_error_expected("Problem while parsing array access", ']', 0);
3533                 return (expression_t*) array_access;
3534         }
3535         next_token();
3536
3537         return_type = automatic_type_conversion(return_type);
3538         array_access->expression.datatype = return_type;
3539
3540         return (expression_t*) array_access;
3541 }
3542
3543 static expression_t *parse_sizeof(unsigned precedence)
3544 {
3545         eat(T_sizeof);
3546
3547         sizeof_expression_t *sizeof_expression
3548                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3549         sizeof_expression->expression.kind     = EXPR_SIZEOF;
3550         sizeof_expression->expression.datatype = type_size_t;
3551
3552         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3553                 next_token();
3554                 sizeof_expression->type = parse_typename();
3555                 expect(')');
3556         } else {
3557                 expression_t *expression  = parse_sub_expression(precedence);
3558                 expression->base.datatype = revert_automatic_type_conversion(expression);
3559
3560                 sizeof_expression->type            = expression->base.datatype;
3561                 sizeof_expression->size_expression = expression;
3562         }
3563
3564         return (expression_t*) sizeof_expression;
3565 }
3566
3567 static expression_t *parse_select_expression(unsigned precedence,
3568                                              expression_t *compound)
3569 {
3570         (void) precedence;
3571         assert(token.type == '.' || token.type == T_MINUSGREATER);
3572
3573         bool is_pointer = (token.type == T_MINUSGREATER);
3574         next_token();
3575
3576         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3577         select->select.compound = compound;
3578
3579         if(token.type != T_IDENTIFIER) {
3580                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3581                 return select;
3582         }
3583         symbol_t *symbol      = token.v.symbol;
3584         select->select.symbol = symbol;
3585         next_token();
3586
3587         type_t *orig_type = compound->base.datatype;
3588         if(orig_type == NULL)
3589                 return create_invalid_expression();
3590
3591         type_t *type = skip_typeref(orig_type);
3592
3593         type_t *type_left = type;
3594         if(is_pointer) {
3595                 if(type->kind != TYPE_POINTER) {
3596                         parser_print_error_prefix();
3597                         fprintf(stderr, "left hand side of '->' is not a pointer, but ");
3598                         print_type_quoted(orig_type);
3599                         fputc('\n', stderr);
3600                         return create_invalid_expression();
3601                 }
3602                 pointer_type_t *pointer_type = &type->pointer;
3603                 type_left                    = pointer_type->points_to;
3604         }
3605         type_left = skip_typeref(type_left);
3606
3607         if(type_left->kind != TYPE_COMPOUND_STRUCT
3608                         && type_left->kind != TYPE_COMPOUND_UNION) {
3609                 parser_print_error_prefix();
3610                 fprintf(stderr, "request for member '%s' in something not a struct or "
3611                         "union, but ", symbol->string);
3612                 print_type_quoted(type_left);
3613                 fputc('\n', stderr);
3614                 return create_invalid_expression();
3615         }
3616
3617         compound_type_t *compound_type = &type_left->compound;
3618         declaration_t   *declaration   = compound_type->declaration;
3619
3620         if(!declaration->init.is_defined) {
3621                 parser_print_error_prefix();
3622                 fprintf(stderr, "request for member '%s' of incomplete type ",
3623                         symbol->string);
3624                 print_type_quoted(type_left);
3625                 fputc('\n', stderr);
3626                 return create_invalid_expression();
3627         }
3628
3629         declaration_t *iter = declaration->context.declarations;
3630         for( ; iter != NULL; iter = iter->next) {
3631                 if(iter->symbol == symbol) {
3632                         break;
3633                 }
3634         }
3635         if(iter == NULL) {
3636                 parser_print_error_prefix();
3637                 print_type_quoted(type_left);
3638                 fprintf(stderr, " has no member named '%s'\n", symbol->string);
3639                 return create_invalid_expression();
3640         }
3641
3642         /* we always do the auto-type conversions; the & and sizeof parser contains
3643          * code to revert this! */
3644         type_t *expression_type = automatic_type_conversion(iter->type);
3645
3646         select->select.compound_entry = iter;
3647         select->base.datatype         = expression_type;
3648         return select;
3649 }
3650
3651 static expression_t *parse_call_expression(unsigned precedence,
3652                                            expression_t *expression)
3653 {
3654         (void) precedence;
3655         expression_t *result = allocate_expression_zero(EXPR_CALL);
3656
3657         call_expression_t *call  = &result->call;
3658         call->function           = expression;
3659
3660         function_type_t *function_type = NULL;
3661         type_t          *orig_type     = expression->base.datatype;
3662         if(orig_type != NULL) {
3663                 type_t *type  = skip_typeref(orig_type);
3664
3665                 if(is_type_pointer(type)) {
3666                         pointer_type_t *pointer_type = &type->pointer;
3667
3668                         type = skip_typeref(pointer_type->points_to);
3669
3670                         if (is_type_function(type)) {
3671                                 function_type             = &type->function;
3672                                 call->expression.datatype = function_type->return_type;
3673                         }
3674                 }
3675                 if(function_type == NULL) {
3676                         parser_print_error_prefix();
3677                         fputs("called object '", stderr);
3678                         print_expression(expression);
3679                         fputs("' (type ", stderr);
3680                         print_type_quoted(orig_type);
3681                         fputs(") is not a pointer to a function\n", stderr);
3682
3683                         function_type             = NULL;
3684                         call->expression.datatype = NULL;
3685                 }
3686         }
3687
3688         /* parse arguments */
3689         eat('(');
3690
3691         if(token.type != ')') {
3692                 call_argument_t *last_argument = NULL;
3693
3694                 while(true) {
3695                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3696
3697                         argument->expression = parse_assignment_expression();
3698                         if(last_argument == NULL) {
3699                                 call->arguments = argument;
3700                         } else {
3701                                 last_argument->next = argument;
3702                         }
3703                         last_argument = argument;
3704
3705                         if(token.type != ',')
3706                                 break;
3707                         next_token();
3708                 }
3709         }
3710         expect(')');
3711
3712         if(function_type != NULL) {
3713                 function_parameter_t *parameter = function_type->parameters;
3714                 call_argument_t      *argument  = call->arguments;
3715                 for( ; parameter != NULL && argument != NULL;
3716                                 parameter = parameter->next, argument = argument->next) {
3717                         type_t *expected_type = parameter->type;
3718                         /* TODO report context in error messages */
3719                         argument->expression = create_implicit_cast(argument->expression,
3720                                                                     expected_type);
3721                 }
3722                 /* too few parameters */
3723                 if(parameter != NULL) {
3724                         parser_print_error_prefix();
3725                         fprintf(stderr, "too few arguments to function '");
3726                         print_expression(expression);
3727                         fprintf(stderr, "'\n");
3728                 } else if(argument != NULL) {
3729                         /* too many parameters */
3730                         if(!function_type->variadic
3731                                         && !function_type->unspecified_parameters) {
3732                                 parser_print_error_prefix();
3733                                 fprintf(stderr, "too many arguments to function '");
3734                                 print_expression(expression);
3735                                 fprintf(stderr, "'\n");
3736                         } else {
3737                                 /* do default promotion */
3738                                 for( ; argument != NULL; argument = argument->next) {
3739                                         type_t *type = argument->expression->base.datatype;
3740
3741                                         if(type == NULL)
3742                                                 continue;
3743
3744                                         type = skip_typeref(type);
3745                                         if(is_type_integer(type)) {
3746                                                 type = promote_integer(type);
3747                                         } else if(type == type_float) {
3748                                                 type = type_double;
3749                                         }
3750
3751                                         argument->expression
3752                                                 = create_implicit_cast(argument->expression, type);
3753                                 }
3754
3755                                 check_format(&result->call);
3756                         }
3757                 } else {
3758                         check_format(&result->call);
3759                 }
3760         }
3761
3762         return result;
3763 }
3764
3765 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3766
3767 static bool same_compound_type(const type_t *type1, const type_t *type2)
3768 {
3769         if(!is_type_compound(type1))
3770                 return false;
3771         if(type1->kind != type2->kind)
3772                 return false;
3773
3774         const compound_type_t *compound1 = &type1->compound;
3775         const compound_type_t *compound2 = &type2->compound;
3776
3777         return compound1->declaration == compound2->declaration;
3778 }
3779
3780 static expression_t *parse_conditional_expression(unsigned precedence,
3781                                                   expression_t *expression)
3782 {
3783         eat('?');
3784
3785         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3786
3787         conditional_expression_t *conditional = &result->conditional;
3788         conditional->condition = expression;
3789
3790         /* 6.5.15.2 */
3791         type_t *condition_type_orig = expression->base.datatype;
3792         if(condition_type_orig != NULL) {
3793                 type_t *condition_type = skip_typeref(condition_type_orig);
3794                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3795                         type_error("expected a scalar type in conditional condition",
3796                                    expression->base.source_position, condition_type_orig);
3797                 }
3798         }
3799
3800         expression_t *true_expression = parse_expression();
3801         expect(':');
3802         expression_t *false_expression = parse_sub_expression(precedence);
3803
3804         conditional->true_expression  = true_expression;
3805         conditional->false_expression = false_expression;
3806
3807         type_t *orig_true_type  = true_expression->base.datatype;
3808         type_t *orig_false_type = false_expression->base.datatype;
3809         if(orig_true_type == NULL || orig_false_type == NULL)
3810                 return result;
3811
3812         type_t *true_type  = skip_typeref(orig_true_type);
3813         type_t *false_type = skip_typeref(orig_false_type);
3814
3815         /* 6.5.15.3 */
3816         type_t *result_type = NULL;
3817         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3818                 result_type = semantic_arithmetic(true_type, false_type);
3819
3820                 true_expression  = create_implicit_cast(true_expression, result_type);
3821                 false_expression = create_implicit_cast(false_expression, result_type);
3822
3823                 conditional->true_expression     = true_expression;
3824                 conditional->false_expression    = false_expression;
3825                 conditional->expression.datatype = result_type;
3826         } else if (same_compound_type(true_type, false_type)
3827                         || (is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3828                                 is_type_atomic(false_type, ATOMIC_TYPE_VOID))) {
3829                 /* just take 1 of the 2 types */
3830                 result_type = true_type;
3831         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3832                         && pointers_compatible(true_type, false_type)) {
3833                 /* ok */
3834                 result_type = true_type;
3835         } else {
3836                 /* TODO */
3837                 type_error_incompatible("while parsing conditional",
3838                                         expression->base.source_position, true_type,
3839                                         false_type);
3840         }
3841
3842         conditional->expression.datatype = result_type;
3843         return result;
3844 }
3845
3846 static expression_t *parse_extension(unsigned precedence)
3847 {
3848         eat(T___extension__);
3849
3850         /* TODO enable extensions */
3851
3852         return parse_sub_expression(precedence);
3853 }
3854
3855 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3856 {
3857         eat(T___builtin_classify_type);
3858
3859         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
3860         result->base.datatype = type_int;
3861
3862         expect('(');
3863         expression_t *expression = parse_sub_expression(precedence);
3864         expect(')');
3865         result->classify_type.type_expression = expression;
3866
3867         return result;
3868 }
3869
3870 static void semantic_incdec(unary_expression_t *expression)
3871 {
3872         type_t *orig_type = expression->value->base.datatype;
3873         if(orig_type == NULL)
3874                 return;
3875
3876         type_t *type = skip_typeref(orig_type);
3877         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
3878                 /* TODO: improve error message */
3879                 parser_print_error_prefix();
3880                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
3881                 return;
3882         }
3883
3884         expression->expression.datatype = orig_type;
3885 }
3886
3887 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3888 {
3889         type_t *orig_type = expression->value->base.datatype;
3890         if(orig_type == NULL)
3891                 return;
3892
3893         type_t *type = skip_typeref(orig_type);
3894         if(!is_type_arithmetic(type)) {
3895                 /* TODO: improve error message */
3896                 parser_print_error_prefix();
3897                 fprintf(stderr, "operation needs an arithmetic type\n");
3898                 return;
3899         }
3900
3901         expression->expression.datatype = orig_type;
3902 }
3903
3904 static void semantic_unexpr_scalar(unary_expression_t *expression)
3905 {
3906         type_t *orig_type = expression->value->base.datatype;
3907         if(orig_type == NULL)
3908                 return;
3909
3910         type_t *type = skip_typeref(orig_type);
3911         if (!is_type_scalar(type)) {
3912                 parse_error("operand of ! must be of scalar type\n");
3913                 return;
3914         }
3915
3916         expression->expression.datatype = orig_type;
3917 }
3918
3919 static void semantic_unexpr_integer(unary_expression_t *expression)
3920 {
3921         type_t *orig_type = expression->value->base.datatype;
3922         if(orig_type == NULL)
3923                 return;
3924
3925         type_t *type = skip_typeref(orig_type);
3926         if (!is_type_integer(type)) {
3927                 parse_error("operand of ~ must be of integer type\n");
3928                 return;
3929         }
3930
3931         expression->expression.datatype = orig_type;
3932 }
3933
3934 static void semantic_dereference(unary_expression_t *expression)
3935 {
3936         type_t *orig_type = expression->value->base.datatype;
3937         if(orig_type == NULL)
3938                 return;
3939
3940         type_t *type = skip_typeref(orig_type);
3941         if(!is_type_pointer(type)) {
3942                 parser_print_error_prefix();
3943                 fputs("Unary '*' needs pointer or arrray type, but type ", stderr);
3944                 print_type_quoted(orig_type);
3945                 fputs(" given.\n", stderr);
3946                 return;
3947         }
3948
3949         pointer_type_t *pointer_type = &type->pointer;
3950         type_t         *result_type  = pointer_type->points_to;
3951
3952         result_type = automatic_type_conversion(result_type);
3953         expression->expression.datatype = result_type;
3954 }
3955
3956 static void semantic_take_addr(unary_expression_t *expression)
3957 {
3958         expression_t *value  = expression->value;
3959         value->base.datatype = revert_automatic_type_conversion(value);
3960
3961         type_t *orig_type = value->base.datatype;
3962         if(orig_type == NULL)
3963                 return;
3964
3965         if(value->kind == EXPR_REFERENCE) {
3966                 reference_expression_t *reference   = (reference_expression_t*) value;
3967                 declaration_t          *declaration = reference->declaration;
3968                 if(declaration != NULL) {
3969                         declaration->address_taken = 1;
3970                 }
3971         }
3972
3973         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3974 }
3975
3976 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3977 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3978 {                                                                              \
3979         eat(token_type);                                                           \
3980                                                                                \
3981         expression_t *unary_expression                                             \
3982                 = allocate_expression_zero(unexpression_type);                         \
3983         unary_expression->unary.value = parse_sub_expression(precedence);          \
3984                                                                                    \
3985         sfunc(&unary_expression->unary);                                           \
3986                                                                                \
3987         return unary_expression;                                                   \
3988 }
3989
3990 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
3991                                semantic_unexpr_arithmetic)
3992 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
3993                                semantic_unexpr_arithmetic)
3994 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
3995                                semantic_unexpr_scalar)
3996 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
3997                                semantic_dereference)
3998 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
3999                                semantic_take_addr)
4000 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4001                                semantic_unexpr_integer)
4002 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4003                                semantic_incdec)
4004 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4005                                semantic_incdec)
4006
4007 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4008                                                sfunc)                         \
4009 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4010                                                expression_t *left)            \
4011 {                                                                             \
4012         (void) precedence;                                                        \
4013         eat(token_type);                                                          \
4014                                                                               \
4015         expression_t *unary_expression                                            \
4016                 = allocate_expression_zero(unexpression_type);                        \
4017         unary_expression->unary.value = left;                                     \
4018                                                                                   \
4019         sfunc(&unary_expression->unary);                                          \
4020                                                                               \
4021         return unary_expression;                                                  \
4022 }
4023
4024 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4025                                        EXPR_UNARY_POSTFIX_INCREMENT,
4026                                        semantic_incdec)
4027 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4028                                        EXPR_UNARY_POSTFIX_DECREMENT,
4029                                        semantic_incdec)
4030
4031 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4032 {
4033         /* TODO: handle complex + imaginary types */
4034
4035         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4036         if(type_left == type_long_double || type_right == type_long_double) {
4037                 return type_long_double;
4038         } else if(type_left == type_double || type_right == type_double) {
4039                 return type_double;
4040         } else if(type_left == type_float || type_right == type_float) {
4041                 return type_float;
4042         }
4043
4044         type_right = promote_integer(type_right);
4045         type_left  = promote_integer(type_left);
4046
4047         if(type_left == type_right)
4048                 return type_left;
4049
4050         bool signed_left  = is_type_signed(type_left);
4051         bool signed_right = is_type_signed(type_right);
4052         int  rank_left    = get_rank(type_left);
4053         int  rank_right   = get_rank(type_right);
4054         if(rank_left < rank_right) {
4055                 if(signed_left == signed_right || !signed_right) {
4056                         return type_right;
4057                 } else {
4058                         return type_left;
4059                 }
4060         } else {
4061                 if(signed_left == signed_right || !signed_left) {
4062                         return type_left;
4063                 } else {
4064                         return type_right;
4065                 }
4066         }
4067 }
4068
4069 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4070 {
4071         expression_t *left       = expression->left;
4072         expression_t *right      = expression->right;
4073         type_t       *orig_type_left  = left->base.datatype;
4074         type_t       *orig_type_right = right->base.datatype;
4075
4076         if(orig_type_left == NULL || orig_type_right == NULL)
4077                 return;
4078
4079         type_t *type_left  = skip_typeref(orig_type_left);
4080         type_t *type_right = skip_typeref(orig_type_right);
4081
4082         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4083                 /* TODO: improve error message */
4084                 parser_print_error_prefix();
4085                 fprintf(stderr, "operation needs arithmetic types\n");
4086                 return;
4087         }
4088
4089         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4090         expression->left  = create_implicit_cast(left, arithmetic_type);
4091         expression->right = create_implicit_cast(right, arithmetic_type);
4092         expression->expression.datatype = arithmetic_type;
4093 }
4094
4095 static void semantic_shift_op(binary_expression_t *expression)
4096 {
4097         expression_t *left       = expression->left;
4098         expression_t *right      = expression->right;
4099         type_t       *orig_type_left  = left->base.datatype;
4100         type_t       *orig_type_right = right->base.datatype;
4101
4102         if(orig_type_left == NULL || orig_type_right == NULL)
4103                 return;
4104
4105         type_t *type_left  = skip_typeref(orig_type_left);
4106         type_t *type_right = skip_typeref(orig_type_right);
4107
4108         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4109                 /* TODO: improve error message */
4110                 parser_print_error_prefix();
4111                 fprintf(stderr, "operation needs integer types\n");
4112                 return;
4113         }
4114
4115         type_left  = promote_integer(type_left);
4116         type_right = promote_integer(type_right);
4117
4118         expression->left  = create_implicit_cast(left, type_left);
4119         expression->right = create_implicit_cast(right, type_right);
4120         expression->expression.datatype = type_left;
4121 }
4122
4123 static void semantic_add(binary_expression_t *expression)
4124 {
4125         expression_t *left            = expression->left;
4126         expression_t *right           = expression->right;
4127         type_t       *orig_type_left  = left->base.datatype;
4128         type_t       *orig_type_right = right->base.datatype;
4129
4130         if(orig_type_left == NULL || orig_type_right == NULL)
4131                 return;
4132
4133         type_t *type_left  = skip_typeref(orig_type_left);
4134         type_t *type_right = skip_typeref(orig_type_right);
4135
4136         /* Â§ 5.6.5 */
4137         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4138                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4139                 expression->left  = create_implicit_cast(left, arithmetic_type);
4140                 expression->right = create_implicit_cast(right, arithmetic_type);
4141                 expression->expression.datatype = arithmetic_type;
4142                 return;
4143         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4144                 expression->expression.datatype = type_left;
4145         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4146                 expression->expression.datatype = type_right;
4147         } else {
4148                 parser_print_error_prefix();
4149                 fprintf(stderr, "invalid operands to binary + (");
4150                 print_type_quoted(orig_type_left);
4151                 fprintf(stderr, ", ");
4152                 print_type_quoted(orig_type_right);
4153                 fprintf(stderr, ")\n");
4154         }
4155 }
4156
4157 static void semantic_sub(binary_expression_t *expression)
4158 {
4159         expression_t *left            = expression->left;
4160         expression_t *right           = expression->right;
4161         type_t       *orig_type_left  = left->base.datatype;
4162         type_t       *orig_type_right = right->base.datatype;
4163
4164         if(orig_type_left == NULL || orig_type_right == NULL)
4165                 return;
4166
4167         type_t       *type_left       = skip_typeref(orig_type_left);
4168         type_t       *type_right      = skip_typeref(orig_type_right);
4169
4170         /* Â§ 5.6.5 */
4171         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4172                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4173                 expression->left  = create_implicit_cast(left, arithmetic_type);
4174                 expression->right = create_implicit_cast(right, arithmetic_type);
4175                 expression->expression.datatype = arithmetic_type;
4176                 return;
4177         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4178                 expression->expression.datatype = type_left;
4179         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4180                 if(!pointers_compatible(type_left, type_right)) {
4181                         parser_print_error_prefix();
4182                         fprintf(stderr, "pointers to incompatible objects to binary - (");
4183                         print_type_quoted(orig_type_left);
4184                         fprintf(stderr, ", ");
4185                         print_type_quoted(orig_type_right);
4186                         fprintf(stderr, ")\n");
4187                 } else {
4188                         expression->expression.datatype = type_ptrdiff_t;
4189                 }
4190         } else {
4191                 parser_print_error_prefix();
4192                 fprintf(stderr, "invalid operands to binary - (");
4193                 print_type_quoted(orig_type_left);
4194                 fprintf(stderr, ", ");
4195                 print_type_quoted(orig_type_right);
4196                 fprintf(stderr, ")\n");
4197         }
4198 }
4199
4200 static void semantic_comparison(binary_expression_t *expression)
4201 {
4202         expression_t *left            = expression->left;
4203         expression_t *right           = expression->right;
4204         type_t       *orig_type_left  = left->base.datatype;
4205         type_t       *orig_type_right = right->base.datatype;
4206
4207         if(orig_type_left == NULL || orig_type_right == NULL)
4208                 return;
4209
4210         type_t *type_left  = skip_typeref(orig_type_left);
4211         type_t *type_right = skip_typeref(orig_type_right);
4212
4213         /* TODO non-arithmetic types */
4214         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4215                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4216                 expression->left  = create_implicit_cast(left, arithmetic_type);
4217                 expression->right = create_implicit_cast(right, arithmetic_type);
4218                 expression->expression.datatype = arithmetic_type;
4219         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4220                 /* TODO check compatibility */
4221         } else if (is_type_pointer(type_left)) {
4222                 expression->right = create_implicit_cast(right, type_left);
4223         } else if (is_type_pointer(type_right)) {
4224                 expression->left = create_implicit_cast(left, type_right);
4225         } else {
4226                 type_error_incompatible("invalid operands in comparison",
4227                                         token.source_position, type_left, type_right);
4228         }
4229         expression->expression.datatype = type_int;
4230 }
4231
4232 static void semantic_arithmetic_assign(binary_expression_t *expression)
4233 {
4234         expression_t *left            = expression->left;
4235         expression_t *right           = expression->right;
4236         type_t       *orig_type_left  = left->base.datatype;
4237         type_t       *orig_type_right = right->base.datatype;
4238
4239         if(orig_type_left == NULL || orig_type_right == NULL)
4240                 return;
4241
4242         type_t *type_left  = skip_typeref(orig_type_left);
4243         type_t *type_right = skip_typeref(orig_type_right);
4244
4245         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4246                 /* TODO: improve error message */
4247                 parser_print_error_prefix();
4248                 fprintf(stderr, "operation needs arithmetic types\n");
4249                 return;
4250         }
4251
4252         /* combined instructions are tricky. We can't create an implicit cast on
4253          * the left side, because we need the uncasted form for the store.
4254          * The ast2firm pass has to know that left_type must be right_type
4255          * for the arithmeitc operation and create a cast by itself */
4256         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4257         expression->right       = create_implicit_cast(right, arithmetic_type);
4258         expression->expression.datatype = type_left;
4259 }
4260
4261 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4262 {
4263         expression_t *left            = expression->left;
4264         expression_t *right           = expression->right;
4265         type_t       *orig_type_left  = left->base.datatype;
4266         type_t       *orig_type_right = right->base.datatype;
4267
4268         if(orig_type_left == NULL || orig_type_right == NULL)
4269                 return;
4270
4271         type_t *type_left  = skip_typeref(orig_type_left);
4272         type_t *type_right = skip_typeref(orig_type_right);
4273
4274         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4275                 /* combined instructions are tricky. We can't create an implicit cast on
4276                  * the left side, because we need the uncasted form for the store.
4277                  * The ast2firm pass has to know that left_type must be right_type
4278                  * for the arithmeitc operation and create a cast by itself */
4279                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4280                 expression->right = create_implicit_cast(right, arithmetic_type);
4281                 expression->expression.datatype = type_left;
4282         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4283                 expression->expression.datatype = type_left;
4284         } else {
4285                 parser_print_error_prefix();
4286                 fputs("Incompatible types ", stderr);
4287                 print_type_quoted(orig_type_left);
4288                 fputs(" and ", stderr);
4289                 print_type_quoted(orig_type_right);
4290                 fputs(" in assignment\n", stderr);
4291                 return;
4292         }
4293 }
4294
4295 static void semantic_logical_op(binary_expression_t *expression)
4296 {
4297         expression_t *left            = expression->left;
4298         expression_t *right           = expression->right;
4299         type_t       *orig_type_left  = left->base.datatype;
4300         type_t       *orig_type_right = right->base.datatype;
4301
4302         if(orig_type_left == NULL || orig_type_right == NULL)
4303                 return;
4304
4305         type_t *type_left  = skip_typeref(orig_type_left);
4306         type_t *type_right = skip_typeref(orig_type_right);
4307
4308         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4309                 /* TODO: improve error message */
4310                 parser_print_error_prefix();
4311                 fprintf(stderr, "operation needs scalar types\n");
4312                 return;
4313         }
4314
4315         expression->expression.datatype = type_int;
4316 }
4317
4318 static bool has_const_fields(type_t *type)
4319 {
4320         (void) type;
4321         /* TODO */
4322         return false;
4323 }
4324
4325 static void semantic_binexpr_assign(binary_expression_t *expression)
4326 {
4327         expression_t *left           = expression->left;
4328         type_t       *orig_type_left = left->base.datatype;
4329
4330         if(orig_type_left == NULL)
4331                 return;
4332
4333         type_t *type_left = revert_automatic_type_conversion(left);
4334         type_left         = skip_typeref(orig_type_left);
4335
4336         /* must be a modifiable lvalue */
4337         if (is_type_array(type_left)) {
4338                 parser_print_error_prefix();
4339                 fprintf(stderr, "Cannot assign to arrays ('");
4340                 print_expression(left);
4341                 fprintf(stderr, "')\n");
4342                 return;
4343         }
4344         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4345                 parser_print_error_prefix();
4346                 fprintf(stderr, "assignment to readonly location '");
4347                 print_expression(left);
4348                 fprintf(stderr, "' (type ");
4349                 print_type_quoted(orig_type_left);
4350                 fprintf(stderr, ")\n");
4351                 return;
4352         }
4353         if(is_type_incomplete(type_left)) {
4354                 parser_print_error_prefix();
4355                 fprintf(stderr, "left-hand side of assignment '");
4356                 print_expression(left);
4357                 fprintf(stderr, "' has incomplete type ");
4358                 print_type_quoted(orig_type_left);
4359                 fprintf(stderr, "\n");
4360                 return;
4361         }
4362         if(is_type_compound(type_left) && has_const_fields(type_left)) {
4363                 parser_print_error_prefix();
4364                 fprintf(stderr, "can't assign to '");
4365                 print_expression(left);
4366                 fprintf(stderr, "' because compound type ");
4367                 print_type_quoted(orig_type_left);
4368                 fprintf(stderr, " has readonly fields\n");
4369                 return;
4370         }
4371
4372         semantic_assign(orig_type_left, &expression->right, "assignment");
4373
4374         expression->expression.datatype = orig_type_left;
4375 }
4376
4377 static void semantic_comma(binary_expression_t *expression)
4378 {
4379         expression->expression.datatype = expression->right->base.datatype;
4380 }
4381
4382 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
4383 static expression_t *parse_##binexpression_type(unsigned precedence,      \
4384                                                 expression_t *left)       \
4385 {                                                                         \
4386         eat(token_type);                                                      \
4387                                                                           \
4388         expression_t *right = parse_sub_expression(precedence + lr);          \
4389                                                                           \
4390         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
4391         binexpr->binary.left  = left;                                         \
4392         binexpr->binary.right = right;                                        \
4393         sfunc(&binexpr->binary);                                              \
4394                                                                           \
4395         return binexpr;                                                       \
4396 }
4397
4398 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
4399 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
4400 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
4401 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
4402 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
4403 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
4404 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
4405 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
4406 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
4407
4408 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
4409                       semantic_comparison, 1)
4410 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
4411                       semantic_comparison, 1)
4412 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
4413                       semantic_comparison, 1)
4414 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
4415                       semantic_comparison, 1)
4416
4417 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
4418                       semantic_binexpr_arithmetic, 1)
4419 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
4420                       semantic_binexpr_arithmetic, 1)
4421 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
4422                       semantic_binexpr_arithmetic, 1)
4423 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
4424                       semantic_logical_op, 1)
4425 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
4426                       semantic_logical_op, 1)
4427 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
4428                       semantic_shift_op, 1)
4429 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
4430                       semantic_shift_op, 1)
4431 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
4432                       semantic_arithmetic_addsubb_assign, 0)
4433 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
4434                       semantic_arithmetic_addsubb_assign, 0)
4435 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
4436                       semantic_arithmetic_assign, 0)
4437 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
4438                       semantic_arithmetic_assign, 0)
4439 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
4440                       semantic_arithmetic_assign, 0)
4441 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
4442                       semantic_arithmetic_assign, 0)
4443 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4444                       semantic_arithmetic_assign, 0)
4445 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
4446                       semantic_arithmetic_assign, 0)
4447 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
4448                       semantic_arithmetic_assign, 0)
4449 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
4450                       semantic_arithmetic_assign, 0)
4451
4452 static expression_t *parse_sub_expression(unsigned precedence)
4453 {
4454         if(token.type < 0) {
4455                 return expected_expression_error();
4456         }
4457
4458         expression_parser_function_t *parser
4459                 = &expression_parsers[token.type];
4460         source_position_t             source_position = token.source_position;
4461         expression_t                 *left;
4462
4463         if(parser->parser != NULL) {
4464                 left = parser->parser(parser->precedence);
4465         } else {
4466                 left = parse_primary_expression();
4467         }
4468         assert(left != NULL);
4469         left->base.source_position = source_position;
4470
4471         while(true) {
4472                 if(token.type < 0) {
4473                         return expected_expression_error();
4474                 }
4475
4476                 parser = &expression_parsers[token.type];
4477                 if(parser->infix_parser == NULL)
4478                         break;
4479                 if(parser->infix_precedence < precedence)
4480                         break;
4481
4482                 left = parser->infix_parser(parser->infix_precedence, left);
4483
4484                 assert(left != NULL);
4485                 assert(left->kind != EXPR_UNKNOWN);
4486                 left->base.source_position = source_position;
4487         }
4488
4489         return left;
4490 }
4491
4492 static expression_t *parse_expression(void)
4493 {
4494         return parse_sub_expression(1);
4495 }
4496
4497
4498
4499 static void register_expression_parser(parse_expression_function parser,
4500                                        int token_type, unsigned precedence)
4501 {
4502         expression_parser_function_t *entry = &expression_parsers[token_type];
4503
4504         if(entry->parser != NULL) {
4505                 fprintf(stderr, "for token ");
4506                 print_token_type(stderr, (token_type_t) token_type);
4507                 fprintf(stderr, "\n");
4508                 panic("trying to register multiple expression parsers for a token");
4509         }
4510         entry->parser     = parser;
4511         entry->precedence = precedence;
4512 }
4513
4514 static void register_infix_parser(parse_expression_infix_function parser,
4515                 int token_type, unsigned precedence)
4516 {
4517         expression_parser_function_t *entry = &expression_parsers[token_type];
4518
4519         if(entry->infix_parser != NULL) {
4520                 fprintf(stderr, "for token ");
4521                 print_token_type(stderr, (token_type_t) token_type);
4522                 fprintf(stderr, "\n");
4523                 panic("trying to register multiple infix expression parsers for a "
4524                       "token");
4525         }
4526         entry->infix_parser     = parser;
4527         entry->infix_precedence = precedence;
4528 }
4529
4530 static void init_expression_parsers(void)
4531 {
4532         memset(&expression_parsers, 0, sizeof(expression_parsers));
4533
4534         register_infix_parser(parse_array_expression,         '[',              30);
4535         register_infix_parser(parse_call_expression,          '(',              30);
4536         register_infix_parser(parse_select_expression,        '.',              30);
4537         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
4538         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
4539                                                               T_PLUSPLUS,       30);
4540         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
4541                                                               T_MINUSMINUS,     30);
4542
4543         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
4544         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
4545         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
4546         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
4547         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
4548         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
4549         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
4550         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
4551         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
4552         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
4553         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
4554         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
4555         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
4556                                                     T_EXCLAMATIONMARKEQUAL, 13);
4557         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
4558         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
4559         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
4560         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
4561         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
4562         register_infix_parser(parse_conditional_expression,   '?',               7);
4563         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
4564         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
4565         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
4566         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
4567         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
4568         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
4569         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
4570                                                                 T_LESSLESSEQUAL, 2);
4571         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4572                                                           T_GREATERGREATEREQUAL, 2);
4573         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
4574                                                                      T_ANDEQUAL, 2);
4575         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
4576                                                                     T_PIPEEQUAL, 2);
4577         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
4578                                                                    T_CARETEQUAL, 2);
4579
4580         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
4581
4582         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
4583         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
4584         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
4585         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
4586         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
4587         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
4588         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
4589                                                                   T_PLUSPLUS,   25);
4590         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
4591                                                                   T_MINUSMINUS, 25);
4592         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4593         register_expression_parser(parse_extension,            T___extension__, 25);
4594         register_expression_parser(parse_builtin_classify_type,
4595                                                      T___builtin_classify_type, 25);
4596 }
4597
4598 static asm_constraint_t *parse_asm_constraints(void)
4599 {
4600         asm_constraint_t *result = NULL;
4601         asm_constraint_t *last   = NULL;
4602
4603         while(token.type == T_STRING_LITERAL || token.type == '[') {
4604                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4605                 memset(constraint, 0, sizeof(constraint[0]));
4606
4607                 if(token.type == '[') {
4608                         eat('[');
4609                         if(token.type != T_IDENTIFIER) {
4610                                 parse_error_expected("while parsing asm constraint",
4611                                                      T_IDENTIFIER, 0);
4612                                 return NULL;
4613                         }
4614                         constraint->symbol = token.v.symbol;
4615
4616                         expect(']');
4617                 }
4618
4619                 constraint->constraints = parse_string_literals();
4620                 expect('(');
4621                 constraint->expression = parse_expression();
4622                 expect(')');
4623
4624                 if(last != NULL) {
4625                         last->next = constraint;
4626                 } else {
4627                         result = constraint;
4628                 }
4629                 last = constraint;
4630
4631                 if(token.type != ',')
4632                         break;
4633                 eat(',');
4634         }
4635
4636         return result;
4637 }
4638
4639 static asm_clobber_t *parse_asm_clobbers(void)
4640 {
4641         asm_clobber_t *result = NULL;
4642         asm_clobber_t *last   = NULL;
4643
4644         while(token.type == T_STRING_LITERAL) {
4645                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4646                 clobber->clobber       = parse_string_literals();
4647
4648                 if(last != NULL) {
4649                         last->next = clobber;
4650                 } else {
4651                         result = clobber;
4652                 }
4653                 last = clobber;
4654
4655                 if(token.type != ',')
4656                         break;
4657                 eat(',');
4658         }
4659
4660         return result;
4661 }
4662
4663 static statement_t *parse_asm_statement(void)
4664 {
4665         eat(T_asm);
4666
4667         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4668         statement->base.source_position = token.source_position;
4669
4670         asm_statement_t *asm_statement = &statement->asms;
4671
4672         if(token.type == T_volatile) {
4673                 next_token();
4674                 asm_statement->is_volatile = true;
4675         }
4676
4677         expect('(');
4678         asm_statement->asm_text = parse_string_literals();
4679
4680         if(token.type != ':')
4681                 goto end_of_asm;
4682         eat(':');
4683
4684         asm_statement->inputs = parse_asm_constraints();
4685         if(token.type != ':')
4686                 goto end_of_asm;
4687         eat(':');
4688
4689         asm_statement->outputs = parse_asm_constraints();
4690         if(token.type != ':')
4691                 goto end_of_asm;
4692         eat(':');
4693
4694         asm_statement->clobbers = parse_asm_clobbers();
4695
4696 end_of_asm:
4697         expect(')');
4698         expect(';');
4699         return statement;
4700 }
4701
4702 static statement_t *parse_case_statement(void)
4703 {
4704         eat(T_case);
4705
4706         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4707
4708         statement->base.source_position  = token.source_position;
4709         statement->case_label.expression = parse_expression();
4710
4711         expect(':');
4712         statement->case_label.label_statement = parse_statement();
4713
4714         return statement;
4715 }
4716
4717 static statement_t *parse_default_statement(void)
4718 {
4719         eat(T_default);
4720
4721         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4722
4723         statement->base.source_position = token.source_position;
4724
4725         expect(':');
4726         statement->label.label_statement = parse_statement();
4727
4728         return statement;
4729 }
4730
4731 static declaration_t *get_label(symbol_t *symbol)
4732 {
4733         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4734         assert(current_function != NULL);
4735         /* if we found a label in the same function, then we already created the
4736          * declaration */
4737         if(candidate != NULL
4738                         && candidate->parent_context == &current_function->context) {
4739                 return candidate;
4740         }
4741
4742         /* otherwise we need to create a new one */
4743         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4744         declaration->namespc       = NAMESPACE_LABEL;
4745         declaration->symbol        = symbol;
4746
4747         label_push(declaration);
4748
4749         return declaration;
4750 }
4751
4752 static statement_t *parse_label_statement(void)
4753 {
4754         assert(token.type == T_IDENTIFIER);
4755         symbol_t *symbol = token.v.symbol;
4756         next_token();
4757
4758         declaration_t *label = get_label(symbol);
4759
4760         /* if source position is already set then the label is defined twice,
4761          * otherwise it was just mentioned in a goto so far */
4762         if(label->source_position.input_name != NULL) {
4763                 parser_print_error_prefix();
4764                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
4765                 parser_print_error_prefix_pos(label->source_position);
4766                 fprintf(stderr, "previous definition of '%s' was here\n",
4767                         symbol->string);
4768         } else {
4769                 label->source_position = token.source_position;
4770         }
4771
4772         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4773
4774         label_statement->statement.kind            = STATEMENT_LABEL;
4775         label_statement->statement.source_position = token.source_position;
4776         label_statement->label                     = label;
4777
4778         expect(':');
4779
4780         if(token.type == '}') {
4781                 parse_error("label at end of compound statement");
4782                 return (statement_t*) label_statement;
4783         } else {
4784                 label_statement->label_statement = parse_statement();
4785         }
4786
4787         return (statement_t*) label_statement;
4788 }
4789
4790 static statement_t *parse_if(void)
4791 {
4792         eat(T_if);
4793
4794         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4795         statement->statement.kind            = STATEMENT_IF;
4796         statement->statement.source_position = token.source_position;
4797
4798         expect('(');
4799         statement->condition = parse_expression();
4800         expect(')');
4801
4802         statement->true_statement = parse_statement();
4803         if(token.type == T_else) {
4804                 next_token();
4805                 statement->false_statement = parse_statement();
4806         }
4807
4808         return (statement_t*) statement;
4809 }
4810
4811 static statement_t *parse_switch(void)
4812 {
4813         eat(T_switch);
4814
4815         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4816         statement->statement.kind            = STATEMENT_SWITCH;
4817         statement->statement.source_position = token.source_position;
4818
4819         expect('(');
4820         statement->expression = parse_expression();
4821         expect(')');
4822         statement->body = parse_statement();
4823
4824         return (statement_t*) statement;
4825 }
4826
4827 static statement_t *parse_while(void)
4828 {
4829         eat(T_while);
4830
4831         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4832         statement->statement.kind            = STATEMENT_WHILE;
4833         statement->statement.source_position = token.source_position;
4834
4835         expect('(');
4836         statement->condition = parse_expression();
4837         expect(')');
4838         statement->body = parse_statement();
4839
4840         return (statement_t*) statement;
4841 }
4842
4843 static statement_t *parse_do(void)
4844 {
4845         eat(T_do);
4846
4847         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4848         statement->statement.kind            = STATEMENT_DO_WHILE;
4849         statement->statement.source_position = token.source_position;
4850
4851         statement->body = parse_statement();
4852         expect(T_while);
4853         expect('(');
4854         statement->condition = parse_expression();
4855         expect(')');
4856         expect(';');
4857
4858         return (statement_t*) statement;
4859 }
4860
4861 static statement_t *parse_for(void)
4862 {
4863         eat(T_for);
4864
4865         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4866         statement->statement.kind            = STATEMENT_FOR;
4867         statement->statement.source_position = token.source_position;
4868
4869         expect('(');
4870
4871         int         top          = environment_top();
4872         context_t  *last_context = context;
4873         set_context(&statement->context);
4874
4875         if(token.type != ';') {
4876                 if(is_declaration_specifier(&token, false)) {
4877                         parse_declaration(record_declaration);
4878                 } else {
4879                         statement->initialisation = parse_expression();
4880                         expect(';');
4881                 }
4882         } else {
4883                 expect(';');
4884         }
4885
4886         if(token.type != ';') {
4887                 statement->condition = parse_expression();
4888         }
4889         expect(';');
4890         if(token.type != ')') {
4891                 statement->step = parse_expression();
4892         }
4893         expect(')');
4894         statement->body = parse_statement();
4895
4896         assert(context == &statement->context);
4897         set_context(last_context);
4898         environment_pop_to(top);
4899
4900         return (statement_t*) statement;
4901 }
4902
4903 static statement_t *parse_goto(void)
4904 {
4905         eat(T_goto);
4906
4907         if(token.type != T_IDENTIFIER) {
4908                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4909                 eat_statement();
4910                 return NULL;
4911         }
4912         symbol_t *symbol = token.v.symbol;
4913         next_token();
4914
4915         declaration_t *label = get_label(symbol);
4916
4917         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4918
4919         statement->statement.kind            = STATEMENT_GOTO;
4920         statement->statement.source_position = token.source_position;
4921
4922         statement->label = label;
4923
4924         expect(';');
4925
4926         return (statement_t*) statement;
4927 }
4928
4929 static statement_t *parse_continue(void)
4930 {
4931         eat(T_continue);
4932         expect(';');
4933
4934         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4935         statement->kind                 = STATEMENT_CONTINUE;
4936         statement->base.source_position = token.source_position;
4937
4938         return statement;
4939 }
4940
4941 static statement_t *parse_break(void)
4942 {
4943         eat(T_break);
4944         expect(';');
4945
4946         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4947         statement->kind                 = STATEMENT_BREAK;
4948         statement->base.source_position = token.source_position;
4949
4950         return statement;
4951 }
4952
4953 static statement_t *parse_return(void)
4954 {
4955         eat(T_return);
4956
4957         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4958
4959         statement->statement.kind            = STATEMENT_RETURN;
4960         statement->statement.source_position = token.source_position;
4961
4962         assert(is_type_function(current_function->type));
4963         function_type_t *function_type = &current_function->type->function;
4964         type_t          *return_type   = function_type->return_type;
4965
4966         expression_t *return_value = NULL;
4967         if(token.type != ';') {
4968                 return_value = parse_expression();
4969         }
4970         expect(';');
4971
4972         if(return_type == NULL)
4973                 return (statement_t*) statement;
4974         if(return_value != NULL && return_value->base.datatype == NULL)
4975                 return (statement_t*) statement;
4976
4977         return_type = skip_typeref(return_type);
4978
4979         if(return_value != NULL) {
4980                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
4981
4982                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
4983                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
4984                         parse_warning("'return' with a value, in function returning void");
4985                         return_value = NULL;
4986                 } else {
4987                         if(return_type != NULL) {
4988                                 semantic_assign(return_type, &return_value, "'return'");
4989                         }
4990                 }
4991         } else {
4992                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
4993                         parse_warning("'return' without value, in function returning "
4994                                       "non-void");
4995                 }
4996         }
4997         statement->return_value = return_value;
4998
4999         return (statement_t*) statement;
5000 }
5001
5002 static statement_t *parse_declaration_statement(void)
5003 {
5004         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
5005
5006         statement->base.source_position = token.source_position;
5007
5008         declaration_t *before = last_declaration;
5009         parse_declaration(record_declaration);
5010
5011         if(before == NULL) {
5012                 statement->declaration.declarations_begin = context->declarations;
5013         } else {
5014                 statement->declaration.declarations_begin = before->next;
5015         }
5016         statement->declaration.declarations_end = last_declaration;
5017
5018         return statement;
5019 }
5020
5021 static statement_t *parse_expression_statement(void)
5022 {
5023         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
5024
5025         statement->base.source_position  = token.source_position;
5026         statement->expression.expression = parse_expression();
5027
5028         expect(';');
5029
5030         return statement;
5031 }
5032
5033 static statement_t *parse_statement(void)
5034 {
5035         statement_t   *statement = NULL;
5036
5037         /* declaration or statement */
5038         switch(token.type) {
5039         case T_asm:
5040                 statement = parse_asm_statement();
5041                 break;
5042
5043         case T_case:
5044                 statement = parse_case_statement();
5045                 break;
5046
5047         case T_default:
5048                 statement = parse_default_statement();
5049                 break;
5050
5051         case '{':
5052                 statement = parse_compound_statement();
5053                 break;
5054
5055         case T_if:
5056                 statement = parse_if();
5057                 break;
5058
5059         case T_switch:
5060                 statement = parse_switch();
5061                 break;
5062
5063         case T_while:
5064                 statement = parse_while();
5065                 break;
5066
5067         case T_do:
5068                 statement = parse_do();
5069                 break;
5070
5071         case T_for:
5072                 statement = parse_for();
5073                 break;
5074
5075         case T_goto:
5076                 statement = parse_goto();
5077                 break;
5078
5079         case T_continue:
5080                 statement = parse_continue();
5081                 break;
5082
5083         case T_break:
5084                 statement = parse_break();
5085                 break;
5086
5087         case T_return:
5088                 statement = parse_return();
5089                 break;
5090
5091         case ';':
5092                 next_token();
5093                 statement = NULL;
5094                 break;
5095
5096         case T_IDENTIFIER:
5097                 if(look_ahead(1)->type == ':') {
5098                         statement = parse_label_statement();
5099                         break;
5100                 }
5101
5102                 if(is_typedef_symbol(token.v.symbol)) {
5103                         statement = parse_declaration_statement();
5104                         break;
5105                 }
5106
5107                 statement = parse_expression_statement();
5108                 break;
5109
5110         case T___extension__:
5111                 /* this can be a prefix to a declaration or an expression statement */
5112                 /* we simply eat it now and parse the rest with tail recursion */
5113                 do {
5114                         next_token();
5115                 } while(token.type == T___extension__);
5116                 statement = parse_statement();
5117                 break;
5118
5119         DECLARATION_START
5120                 statement = parse_declaration_statement();
5121                 break;
5122
5123         default:
5124                 statement = parse_expression_statement();
5125                 break;
5126         }
5127
5128         assert(statement == NULL
5129                         || statement->base.source_position.input_name != NULL);
5130
5131         return statement;
5132 }
5133
5134 static statement_t *parse_compound_statement(void)
5135 {
5136         compound_statement_t *compound_statement
5137                 = allocate_ast_zero(sizeof(compound_statement[0]));
5138         compound_statement->statement.kind            = STATEMENT_COMPOUND;
5139         compound_statement->statement.source_position = token.source_position;
5140
5141         eat('{');
5142
5143         int        top          = environment_top();
5144         context_t *last_context = context;
5145         set_context(&compound_statement->context);
5146
5147         statement_t *last_statement = NULL;
5148
5149         while(token.type != '}' && token.type != T_EOF) {
5150                 statement_t *statement = parse_statement();
5151                 if(statement == NULL)
5152                         continue;
5153
5154                 if(last_statement != NULL) {
5155                         last_statement->base.next = statement;
5156                 } else {
5157                         compound_statement->statements = statement;
5158                 }
5159
5160                 while(statement->base.next != NULL)
5161                         statement = statement->base.next;
5162
5163                 last_statement = statement;
5164         }
5165
5166         if(token.type != '}') {
5167                 parser_print_error_prefix_pos(
5168                                 compound_statement->statement.source_position);
5169                 fprintf(stderr, "end of file while looking for closing '}'\n");
5170         }
5171         next_token();
5172
5173         assert(context == &compound_statement->context);
5174         set_context(last_context);
5175         environment_pop_to(top);
5176
5177         return (statement_t*) compound_statement;
5178 }
5179
5180 static void initialize_builtins(void)
5181 {
5182         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
5183         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
5184         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
5185         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
5186         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
5187         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
5188         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
5189         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
5190
5191         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
5192         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
5193         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
5194         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
5195 }
5196
5197 static translation_unit_t *parse_translation_unit(void)
5198 {
5199         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
5200
5201         assert(global_context == NULL);
5202         global_context = &unit->context;
5203
5204         assert(context == NULL);
5205         set_context(&unit->context);
5206
5207         initialize_builtins();
5208
5209         while(token.type != T_EOF) {
5210                 parse_external_declaration();
5211         }
5212
5213         assert(context == &unit->context);
5214         context          = NULL;
5215         last_declaration = NULL;
5216
5217         assert(global_context == &unit->context);
5218         global_context = NULL;
5219
5220         return unit;
5221 }
5222
5223 translation_unit_t *parse(void)
5224 {
5225         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5226         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5227         found_error       = false;
5228
5229         type_set_output(stderr);
5230         ast_set_output(stderr);
5231
5232         lookahead_bufpos = 0;
5233         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5234                 next_token();
5235         }
5236         translation_unit_t *unit = parse_translation_unit();
5237
5238         DEL_ARR_F(environment_stack);
5239         DEL_ARR_F(label_stack);
5240
5241         if(found_error)
5242                 return NULL;
5243
5244         return unit;
5245 }
5246
5247 void init_parser(void)
5248 {
5249         init_expression_parsers();
5250         obstack_init(&temp_obst);
5251
5252         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
5253         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
5254 }
5255
5256 void exit_parser(void)
5257 {
5258         obstack_free(&temp_obst, NULL);
5259 }