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