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