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