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