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