414c21f901f2866fd2190d888e9c907156661ba6
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "parser.h"
8 #include "lexer.h"
9 #include "token_t.h"
10 #include "type_t.h"
11 #include "type_hash.h"
12 #include "ast_t.h"
13 #include "adt/bitfiddle.h"
14 #include "adt/error.h"
15 #include "adt/array.h"
16
17 //#define PRINT_TOKENS
18 //#define ABORT_ON_ERROR
19 #define MAX_LOOKAHEAD 2
20 //#define STRICT_C99
21
22 typedef struct {
23         declaration_t *old_declaration;
24         symbol_t      *symbol;
25         unsigned short namespc;
26 } stack_entry_t;
27
28 typedef struct declaration_specifiers_t  declaration_specifiers_t;
29 struct declaration_specifiers_t {
30         source_position_t  source_position;
31         unsigned char      storage_class;
32         bool               is_inline;
33         type_t            *type;
34 };
35
36 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
37
38 static token_t         token;
39 static token_t         lookahead_buffer[MAX_LOOKAHEAD];
40 static int             lookahead_bufpos;
41 static stack_entry_t  *environment_stack = NULL;
42 static stack_entry_t  *label_stack       = NULL;
43 static context_t      *global_context    = NULL;
44 static context_t      *context           = NULL;
45 static declaration_t  *last_declaration  = NULL;
46 static declaration_t  *current_function  = NULL;
47 static struct obstack  temp_obst;
48 static bool            found_error;
49
50 static type_t         *type_int         = NULL;
51 static type_t         *type_long_double = NULL;
52 static type_t         *type_double      = NULL;
53 static type_t         *type_float       = NULL;
54 static type_t         *type_char        = NULL;
55 static type_t         *type_string      = NULL;
56 static type_t         *type_void        = NULL;
57 static type_t         *type_void_ptr    = NULL;
58
59 type_t *type_size_t      = NULL;
60 type_t *type_ptrdiff_t   = NULL;
61 type_t *type_wchar_t     = NULL;
62 type_t *type_wchar_t_ptr = NULL;
63
64 static statement_t *parse_compound_statement(void);
65 static statement_t *parse_statement(void);
66
67 static expression_t *parse_sub_expression(unsigned precedence);
68 static expression_t *parse_expression(void);
69 static type_t       *parse_typename(void);
70
71 static void parse_compound_type_entries(void);
72 static declaration_t *parse_declarator(
73                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
74 static declaration_t *record_declaration(declaration_t *declaration);
75
76 #define STORAGE_CLASSES     \
77         case T_typedef:         \
78         case T_extern:          \
79         case T_static:          \
80         case T_auto:            \
81         case T_register:
82
83 #define TYPE_QUALIFIERS     \
84         case T_const:           \
85         case T_restrict:        \
86         case T_volatile:        \
87         case T_inline:
88
89 #ifdef PROVIDE_COMPLEX
90 #define COMPLEX_SPECIFIERS  \
91         case T__Complex:
92 #define IMAGINARY_SPECIFIERS \
93         case T__Imaginary:
94 #else
95 #define COMPLEX_SPECIFIERS
96 #define IMAGINARY_SPECIFIERS
97 #endif
98
99 #define TYPE_SPECIFIERS     \
100         case T_void:            \
101         case T_char:            \
102         case T_short:           \
103         case T_int:             \
104         case T_long:            \
105         case T_float:           \
106         case T_double:          \
107         case T_signed:          \
108         case T_unsigned:        \
109         case T__Bool:           \
110         case T_struct:          \
111         case T_union:           \
112         case T_enum:            \
113         case T___typeof__:      \
114         COMPLEX_SPECIFIERS      \
115         IMAGINARY_SPECIFIERS
116
117 #define DECLARATION_START   \
118         STORAGE_CLASSES         \
119         TYPE_QUALIFIERS         \
120         TYPE_SPECIFIERS
121
122 #define TYPENAME_START      \
123         TYPE_QUALIFIERS         \
124         TYPE_SPECIFIERS
125
126 static void *allocate_ast_zero(size_t size)
127 {
128         void *res = allocate_ast(size);
129         memset(res, 0, size);
130         return res;
131 }
132
133 static size_t get_statement_struct_size(statement_type_t type)
134 {
135         static const size_t sizes[] = {
136                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
137                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
138                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
139                 [STATEMENT_IF]          = sizeof(if_statement_t),
140                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
141                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
142                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
143                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
144                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
145                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
146                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
147                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
148                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
149                 [STATEMENT_FOR]         = sizeof(for_statement_t),
150                 [STATEMENT_ASM]         = sizeof(asm_statement_t)
151         };
152         assert(sizeof(sizes) / sizeof(sizes[0]) == STATEMENT_ASM + 1);
153         assert(type <= STATEMENT_ASM);
154         assert(sizes[type] != 0);
155         return sizes[type];
156 }
157
158 static statement_t *allocate_statement_zero(statement_type_t type)
159 {
160         size_t       size = get_statement_struct_size(type);
161         statement_t *res  = allocate_ast_zero(size);
162
163         res->base.type = type;
164         return res;
165 }
166
167
168 static size_t get_expression_struct_size(expression_type_t type)
169 {
170         static const size_t sizes[] = {
171                 [EXPR_INVALID]             = sizeof(expression_base_t),
172                 [EXPR_REFERENCE]           = sizeof(reference_expression_t),
173                 [EXPR_CONST]               = sizeof(const_expression_t),
174                 [EXPR_STRING_LITERAL]      = sizeof(string_literal_expression_t),
175                 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
176                 [EXPR_CALL]                = sizeof(call_expression_t),
177                 [EXPR_UNARY]               = sizeof(unary_expression_t),
178                 [EXPR_BINARY]              = sizeof(binary_expression_t),
179                 [EXPR_CONDITIONAL]         = sizeof(conditional_expression_t),
180                 [EXPR_SELECT]              = sizeof(select_expression_t),
181                 [EXPR_ARRAY_ACCESS]        = sizeof(array_access_expression_t),
182                 [EXPR_SIZEOF]              = sizeof(sizeof_expression_t),
183                 [EXPR_CLASSIFY_TYPE]       = sizeof(classify_type_expression_t),
184                 [EXPR_FUNCTION]            = sizeof(string_literal_expression_t),
185                 [EXPR_PRETTY_FUNCTION]     = sizeof(string_literal_expression_t),
186                 [EXPR_BUILTIN_SYMBOL]      = sizeof(builtin_symbol_expression_t),
187                 [EXPR_OFFSETOF]            = sizeof(offsetof_expression_t),
188                 [EXPR_VA_ARG]              = sizeof(va_arg_expression_t),
189                 [EXPR_STATEMENT]           = sizeof(statement_expression_t)
190         };
191         assert(sizeof(sizes) / sizeof(sizes[0]) == EXPR_STATEMENT + 1);
192         assert(type <= EXPR_STATEMENT);
193         assert(sizes[type] != 0);
194         return sizes[type];
195 }
196
197 static expression_t *allocate_expression_zero(expression_type_t type)
198 {
199         size_t        size = get_expression_struct_size(type);
200         expression_t *res  = allocate_ast_zero(size);
201
202         res->base.type = type;
203         return res;
204 }
205
206 static size_t get_type_struct_size(type_type_t type)
207 {
208         static const size_t sizes[] = {
209                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
210                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
211                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
212                 [TYPE_ENUM]            = sizeof(enum_type_t),
213                 [TYPE_FUNCTION]        = sizeof(function_type_t),
214                 [TYPE_POINTER]         = sizeof(pointer_type_t),
215                 [TYPE_ARRAY]           = sizeof(array_type_t),
216                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
217                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
218                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
219         };
220         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
221         assert(type <= TYPE_TYPEOF);
222         assert(sizes[type] != 0);
223         return sizes[type];
224 }
225
226 static type_t *allocate_type_zero(type_type_t type)
227 {
228         size_t  size = get_type_struct_size(type);
229         type_t *res  = obstack_alloc(type_obst, size);
230         memset(res, 0, size);
231
232         res->base.type = type;
233         return res;
234 }
235
236 static size_t get_initializer_size(initializer_type_t type)
237 {
238         static const size_t sizes[] = {
239                 [INITIALIZER_VALUE]  = sizeof(initializer_value_t),
240                 [INITIALIZER_STRING] = sizeof(initializer_string_t),
241                 [INITIALIZER_LIST]   = sizeof(initializer_list_t)
242         };
243         assert(type < INITIALIZER_COUNT);
244         assert(sizes[type] != 0);
245         return sizes[type];
246 }
247
248 static initializer_t *allocate_initializer(initializer_type_t type)
249 {
250         initializer_t *result = allocate_ast_zero(get_initializer_size(type));
251         result->type          = type;
252
253         return result;
254 }
255
256 static void free_type(void *type)
257 {
258         obstack_free(type_obst, type);
259 }
260
261 /**
262  * returns the top element of the environment stack
263  */
264 static size_t environment_top(void)
265 {
266         return ARR_LEN(environment_stack);
267 }
268
269 static size_t label_top(void)
270 {
271         return ARR_LEN(label_stack);
272 }
273
274
275
276 static inline void next_token(void)
277 {
278         token                              = lookahead_buffer[lookahead_bufpos];
279         lookahead_buffer[lookahead_bufpos] = lexer_token;
280         lexer_next_token();
281
282         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
283
284 #ifdef PRINT_TOKENS
285         print_token(stderr, &token);
286         fprintf(stderr, "\n");
287 #endif
288 }
289
290 static inline const token_t *look_ahead(int num)
291 {
292         assert(num > 0 && num <= MAX_LOOKAHEAD);
293         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
294         return &lookahead_buffer[pos];
295 }
296
297 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
298
299 static void error(void)
300 {
301         found_error = true;
302 #ifdef ABORT_ON_ERROR
303         abort();
304 #endif
305 }
306
307 static void parser_print_prefix_pos(const source_position_t source_position)
308 {
309     fputs(source_position.input_name, stderr);
310     fputc(':', stderr);
311     fprintf(stderr, "%u", source_position.linenr);
312     fputs(": ", stderr);
313 }
314
315 static void parser_print_error_prefix_pos(
316                 const source_position_t source_position)
317 {
318         parser_print_prefix_pos(source_position);
319         fputs("error: ", stderr);
320         error();
321 }
322
323 static void parser_print_error_prefix(void)
324 {
325         parser_print_error_prefix_pos(token.source_position);
326 }
327
328 static void parse_error(const char *message)
329 {
330         parser_print_error_prefix();
331         fprintf(stderr, "parse error: %s\n", message);
332 }
333
334 static void parser_print_warning_prefix_pos(
335                 const source_position_t source_position)
336 {
337         parser_print_prefix_pos(source_position);
338         fputs("warning: ", stderr);
339 }
340
341 static void parser_print_warning_prefix(void)
342 {
343         parser_print_warning_prefix_pos(token.source_position);
344 }
345
346 static void parse_warning_pos(const source_position_t source_position,
347                               const char *const message)
348 {
349         parser_print_prefix_pos(source_position);
350         fprintf(stderr, "warning: %s\n", message);
351 }
352
353 static void parse_warning(const char *message)
354 {
355         parse_warning_pos(token.source_position, message);
356 }
357
358 static void parse_error_expected(const char *message, ...)
359 {
360         va_list args;
361         int first = 1;
362
363         if(message != NULL) {
364                 parser_print_error_prefix();
365                 fprintf(stderr, "%s\n", message);
366         }
367         parser_print_error_prefix();
368         fputs("Parse error: got ", stderr);
369         print_token(stderr, &token);
370         fputs(", expected ", stderr);
371
372         va_start(args, message);
373         token_type_t token_type = va_arg(args, token_type_t);
374         while(token_type != 0) {
375                 if(first == 1) {
376                         first = 0;
377                 } else {
378                         fprintf(stderr, ", ");
379                 }
380                 print_token_type(stderr, token_type);
381                 token_type = va_arg(args, token_type_t);
382         }
383         va_end(args);
384         fprintf(stderr, "\n");
385 }
386
387 static void print_type_quoted(type_t *type)
388 {
389         fputc('\'', stderr);
390         print_type(type);
391         fputc('\'', stderr);
392 }
393
394 static void type_error(const char *msg, const source_position_t source_position,
395                        type_t *type)
396 {
397         parser_print_error_prefix_pos(source_position);
398         fprintf(stderr, "%s, but found type ", msg);
399         print_type_quoted(type);
400         fputc('\n', stderr);
401 }
402
403 static void type_error_incompatible(const char *msg,
404                 const source_position_t source_position, type_t *type1, type_t *type2)
405 {
406         parser_print_error_prefix_pos(source_position);
407         fprintf(stderr, "%s, incompatible types: ", msg);
408         print_type_quoted(type1);
409         fprintf(stderr, " - ");
410         print_type_quoted(type2);
411         fprintf(stderr, ")\n");
412 }
413
414 static void eat_block(void)
415 {
416         if(token.type == '{')
417                 next_token();
418
419         while(token.type != '}') {
420                 if(token.type == T_EOF)
421                         return;
422                 if(token.type == '{') {
423                         eat_block();
424                         continue;
425                 }
426                 next_token();
427         }
428         eat('}');
429 }
430
431 static void eat_statement(void)
432 {
433         while(token.type != ';') {
434                 if(token.type == T_EOF)
435                         return;
436                 if(token.type == '}')
437                         return;
438                 if(token.type == '{') {
439                         eat_block();
440                         continue;
441                 }
442                 next_token();
443         }
444         eat(';');
445 }
446
447 static void eat_brace(void)
448 {
449         if(token.type == '(')
450                 next_token();
451
452         while(token.type != ')') {
453                 if(token.type == T_EOF)
454                         return;
455                 if(token.type == ')' || token.type == ';' || token.type == '}') {
456                         return;
457                 }
458                 if(token.type == '(') {
459                         eat_brace();
460                         continue;
461                 }
462                 if(token.type == '{') {
463                         eat_block();
464                         continue;
465                 }
466                 next_token();
467         }
468         eat(')');
469 }
470
471 #define expect(expected)                           \
472     if(UNLIKELY(token.type != (expected))) {       \
473         parse_error_expected(NULL, (expected), 0); \
474         eat_statement();                           \
475         return NULL;                               \
476     }                                              \
477     next_token();
478
479 #define expect_block(expected)                     \
480     if(UNLIKELY(token.type != (expected))) {       \
481         parse_error_expected(NULL, (expected), 0); \
482         eat_block();                               \
483         return NULL;                               \
484     }                                              \
485     next_token();
486
487 #define expect_void(expected)                      \
488     if(UNLIKELY(token.type != (expected))) {       \
489         parse_error_expected(NULL, (expected), 0); \
490         eat_statement();                           \
491         return;                                    \
492     }                                              \
493     next_token();
494
495 static void set_context(context_t *new_context)
496 {
497         context = new_context;
498
499         last_declaration = new_context->declarations;
500         if(last_declaration != NULL) {
501                 while(last_declaration->next != NULL) {
502                         last_declaration = last_declaration->next;
503                 }
504         }
505 }
506
507 /**
508  * called when we find a 2nd declarator for an identifier we already have a
509  * declarator for
510  */
511 static bool is_compatible_declaration(declaration_t *declaration,
512                                       declaration_t *previous)
513 {
514         /* happens for K&R style function parameters */
515         if(previous->type == NULL) {
516                 previous->type = declaration->type;
517                 return true;
518         }
519
520         type_t *type1 = skip_typeref(declaration->type);
521         type_t *type2 = skip_typeref(previous->type);
522
523         return types_compatible(type1, type2);
524 }
525
526 static declaration_t *get_declaration(symbol_t *symbol, namespace_t namespc)
527 {
528         declaration_t *declaration = symbol->declaration;
529         for( ; declaration != NULL; declaration = declaration->symbol_next) {
530                 if(declaration->namespc == namespc)
531                         return declaration;
532         }
533
534         return NULL;
535 }
536
537 static const char *get_namespace_prefix(namespace_t namespc)
538 {
539         switch(namespc) {
540         case NAMESPACE_NORMAL:
541                 return "";
542         case NAMESPACE_UNION:
543                 return "union ";
544         case NAMESPACE_STRUCT:
545                 return "struct ";
546         case NAMESPACE_ENUM:
547                 return "enum ";
548         case NAMESPACE_LABEL:
549                 return "label ";
550         }
551         panic("invalid namespace found");
552 }
553
554 /**
555  * pushs an environment_entry on the environment stack and links the
556  * corresponding symbol to the new entry
557  */
558 static declaration_t *stack_push(stack_entry_t **stack_ptr,
559                                  declaration_t *declaration,
560                                  context_t *parent_context)
561 {
562         symbol_t    *symbol    = declaration->symbol;
563         namespace_t  namespc = (namespace_t)declaration->namespc;
564
565         /* a declaration should be only pushed once */
566         declaration->parent_context = parent_context;
567
568         declaration_t *previous_declaration = get_declaration(symbol, namespc);
569         assert(declaration != previous_declaration);
570         if(previous_declaration != NULL
571                         && previous_declaration->parent_context == context) {
572                 if(!is_compatible_declaration(declaration, previous_declaration)) {
573                         parser_print_error_prefix_pos(declaration->source_position);
574                         fprintf(stderr, "definition of symbol '%s%s' with type ",
575                                         get_namespace_prefix(namespc), symbol->string);
576                         print_type_quoted(declaration->type);
577                         fputc('\n', stderr);
578                         parser_print_error_prefix_pos(
579                                         previous_declaration->source_position);
580                         fprintf(stderr, "is incompatible with previous declaration "
581                                         "of type ");
582                         print_type_quoted(previous_declaration->type);
583                         fputc('\n', stderr);
584                 } else {
585                         unsigned old_storage_class = previous_declaration->storage_class;
586                         unsigned new_storage_class = declaration->storage_class;
587                         if (current_function == NULL) {
588                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
589                                     new_storage_class == STORAGE_CLASS_STATIC) {
590                                         parser_print_error_prefix_pos(declaration->source_position);
591                                         fprintf(stderr,
592                                                 "static declaration of '%s' follows non-static declaration\n",
593                                                 symbol->string);
594                                         parser_print_error_prefix_pos(previous_declaration->source_position);
595                                         fprintf(stderr, "previous declaration of '%s' was here\n",
596                                                 symbol->string);
597                                 } else {
598                                         if (old_storage_class == STORAGE_CLASS_EXTERN) {
599                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
600                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
601                                                 }
602                                         } else {
603                                                 parser_print_warning_prefix_pos(declaration->source_position);
604                                                 fprintf(stderr, "redundant declaration for '%s'\n",
605                                                                                 symbol->string);
606                                                 parser_print_warning_prefix_pos(previous_declaration->source_position);
607                                                 fprintf(stderr, "previous declaration of '%s' was here\n",
608                                                                                 symbol->string);
609                                         }
610                                 }
611                         } else {
612                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
613                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
614                                         parser_print_warning_prefix_pos(declaration->source_position);
615                                         fprintf(stderr, "redundant extern declaration for '%s'\n",
616                                                 symbol->string);
617                                         parser_print_warning_prefix_pos(previous_declaration->source_position);
618                                         fprintf(stderr, "previous declaration of '%s' was here\n",
619                                                 symbol->string);
620                                 } else {
621                                         parser_print_error_prefix_pos(declaration->source_position);
622                                         if (old_storage_class == new_storage_class) {
623                                                 fprintf(stderr, "redeclaration of '%s'\n", symbol->string);
624                                         } else {
625                                                 fprintf(stderr, "redeclaration of '%s' with different linkage\n", symbol->string);
626                                         }
627                                         parser_print_error_prefix_pos(previous_declaration->source_position);
628                                         fprintf(stderr, "previous declaration of '%s' was here\n",
629                                                 symbol->string);
630                                 }
631                         }
632                 }
633                 return previous_declaration;
634         }
635
636         /* remember old declaration */
637         stack_entry_t entry;
638         entry.symbol          = symbol;
639         entry.old_declaration = symbol->declaration;
640         entry.namespc         = (unsigned short) namespc;
641         ARR_APP1(stack_entry_t, *stack_ptr, entry);
642
643         /* replace/add declaration into declaration list of the symbol */
644         if(symbol->declaration == NULL) {
645                 symbol->declaration = declaration;
646         } else {
647                 declaration_t *iter_last = NULL;
648                 declaration_t *iter      = symbol->declaration;
649                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
650                         /* replace an entry? */
651                         if(iter->namespc == namespc) {
652                                 if(iter_last == NULL) {
653                                         symbol->declaration = declaration;
654                                 } else {
655                                         iter_last->symbol_next = declaration;
656                                 }
657                                 declaration->symbol_next = iter->symbol_next;
658                                 break;
659                         }
660                 }
661                 if(iter == NULL) {
662                         assert(iter_last->symbol_next == NULL);
663                         iter_last->symbol_next = declaration;
664                 }
665         }
666
667         return declaration;
668 }
669
670 static declaration_t *environment_push(declaration_t *declaration)
671 {
672         assert(declaration->source_position.input_name != NULL);
673         return stack_push(&environment_stack, declaration, context);
674 }
675
676 static declaration_t *label_push(declaration_t *declaration)
677 {
678         return stack_push(&label_stack, declaration, &current_function->context);
679 }
680
681 /**
682  * pops symbols from the environment stack until @p new_top is the top element
683  */
684 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
685 {
686         stack_entry_t *stack = *stack_ptr;
687         size_t         top   = ARR_LEN(stack);
688         size_t         i;
689
690         assert(new_top <= top);
691         if(new_top == top)
692                 return;
693
694         for(i = top; i > new_top; --i) {
695                 stack_entry_t *entry = &stack[i - 1];
696
697                 declaration_t *old_declaration = entry->old_declaration;
698                 symbol_t      *symbol          = entry->symbol;
699                 namespace_t    namespc         = (namespace_t)entry->namespc;
700
701                 /* replace/remove declaration */
702                 declaration_t *declaration = symbol->declaration;
703                 assert(declaration != NULL);
704                 if(declaration->namespc == namespc) {
705                         if(old_declaration == NULL) {
706                                 symbol->declaration = declaration->symbol_next;
707                         } else {
708                                 symbol->declaration = old_declaration;
709                         }
710                 } else {
711                         declaration_t *iter_last = declaration;
712                         declaration_t *iter      = declaration->symbol_next;
713                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
714                                 /* replace an entry? */
715                                 if(iter->namespc == namespc) {
716                                         assert(iter_last != NULL);
717                                         iter_last->symbol_next = old_declaration;
718                                         old_declaration->symbol_next = iter->symbol_next;
719                                         break;
720                                 }
721                         }
722                         assert(iter != NULL);
723                 }
724         }
725
726         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
727 }
728
729 static void environment_pop_to(size_t new_top)
730 {
731         stack_pop_to(&environment_stack, new_top);
732 }
733
734 static void label_pop_to(size_t new_top)
735 {
736         stack_pop_to(&label_stack, new_top);
737 }
738
739
740 static int get_rank(const type_t *type)
741 {
742         assert(!is_typeref(type));
743         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
744          * and esp. footnote 108). However we can't fold constants (yet), so we
745          * can't decide wether unsigned int is possible, while int always works.
746          * (unsigned int would be preferable when possible... for stuff like
747          *  struct { enum { ... } bla : 4; } ) */
748         if(type->type == TYPE_ENUM)
749                 return ATOMIC_TYPE_INT;
750
751         assert(type->type == TYPE_ATOMIC);
752         const atomic_type_t *atomic_type = &type->atomic;
753         atomic_type_type_t   atype       = atomic_type->atype;
754         return atype;
755 }
756
757 static type_t *promote_integer(type_t *type)
758 {
759         if(get_rank(type) < ATOMIC_TYPE_INT)
760                 type = type_int;
761
762         return type;
763 }
764
765 static expression_t *create_cast_expression(expression_t *expression,
766                                             type_t *dest_type)
767 {
768         expression_t *cast = allocate_expression_zero(EXPR_UNARY);
769
770         cast->unary.type    = UNEXPR_CAST_IMPLICIT;
771         cast->unary.value   = expression;
772         cast->base.datatype = dest_type;
773
774         return cast;
775 }
776
777 static bool is_null_pointer_constant(const expression_t *expression)
778 {
779         /* skip void* cast */
780         if(expression->type == EXPR_UNARY) {
781                 const unary_expression_t *unary = &expression->unary;
782                 if(unary->type == UNEXPR_CAST
783                                 && expression->base.datatype == type_void_ptr) {
784                         expression = unary->value;
785                 }
786         }
787
788         /* TODO: not correct yet, should be any constant integer expression
789          * which evaluates to 0 */
790         if (expression->type != EXPR_CONST)
791                 return false;
792
793         type_t *const type = skip_typeref(expression->base.datatype);
794         if (!is_type_integer(type))
795                 return false;
796
797         return expression->conste.v.int_value == 0;
798 }
799
800 static expression_t *create_implicit_cast(expression_t *expression,
801                                           type_t *dest_type)
802 {
803         type_t *source_type = expression->base.datatype;
804
805         if(source_type == NULL)
806                 return expression;
807
808         source_type = skip_typeref(source_type);
809         dest_type   = skip_typeref(dest_type);
810
811         if(source_type == dest_type)
812                 return expression;
813
814         switch (dest_type->type) {
815                 case TYPE_ENUM:
816                         /* TODO warning for implicitly converting to enum */
817                 case TYPE_ATOMIC:
818                         if (source_type->type != TYPE_ATOMIC &&
819                                         source_type->type != TYPE_ENUM) {
820                                 panic("casting of non-atomic types not implemented yet");
821                         }
822
823                         if(is_type_floating(dest_type) && !is_type_scalar(source_type)) {
824                                 type_error_incompatible("can't cast types",
825                                                 expression->base.source_position, source_type,
826                                                 dest_type);
827                                 return expression;
828                         }
829
830                         return create_cast_expression(expression, dest_type);
831
832                 case TYPE_POINTER:
833                         switch (source_type->type) {
834                                 case TYPE_ATOMIC:
835                                         if (is_null_pointer_constant(expression)) {
836                                                 return create_cast_expression(expression, dest_type);
837                                         }
838                                         break;
839
840                                 case TYPE_POINTER:
841                                         if (pointers_compatible(source_type, dest_type)) {
842                                                 return create_cast_expression(expression, dest_type);
843                                         }
844                                         break;
845
846                                 case TYPE_ARRAY: {
847                                         array_type_t   *array_type   = &source_type->array;
848                                         pointer_type_t *pointer_type = &dest_type->pointer;
849                                         if (types_compatible(array_type->element_type,
850                                                                                  pointer_type->points_to)) {
851                                                 return create_cast_expression(expression, dest_type);
852                                         }
853                                         break;
854                                 }
855
856                                 default:
857                                         panic("casting of non-atomic types not implemented yet");
858                         }
859
860                         type_error_incompatible("can't implicitly cast types",
861                                         expression->base.source_position, source_type, dest_type);
862                         return expression;
863
864                 default:
865                         panic("casting of non-atomic types not implemented yet");
866         }
867 }
868
869 /** Implements the rules from Â§ 6.5.16.1 */
870 static void semantic_assign(type_t *orig_type_left, expression_t **right,
871                             const char *context)
872 {
873         type_t *orig_type_right = (*right)->base.datatype;
874
875         if(orig_type_right == NULL)
876                 return;
877
878         type_t *const type_left  = skip_typeref(orig_type_left);
879         type_t *const type_right = skip_typeref(orig_type_right);
880
881         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
882             (is_type_pointer(type_left) && is_null_pointer_constant(*right)) ||
883             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
884                 && is_type_pointer(type_right))) {
885                 *right = create_implicit_cast(*right, type_left);
886                 return;
887         }
888
889         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
890                 pointer_type_t *pointer_type_left  = &type_left->pointer;
891                 pointer_type_t *pointer_type_right = &type_right->pointer;
892                 type_t         *points_to_left     = pointer_type_left->points_to;
893                 type_t         *points_to_right    = pointer_type_right->points_to;
894
895                 points_to_left  = skip_typeref(points_to_left);
896                 points_to_right = skip_typeref(points_to_right);
897
898                 /* the left type has all qualifiers from the right type */
899                 unsigned missing_qualifiers
900                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
901                 if(missing_qualifiers != 0) {
902                         parser_print_error_prefix();
903                         fprintf(stderr, "destination type ");
904                         print_type_quoted(type_left);
905                         fprintf(stderr, " in %s from type ", context);
906                         print_type_quoted(type_right);
907                         fprintf(stderr, " lacks qualifiers '");
908                         print_type_qualifiers(missing_qualifiers);
909                         fprintf(stderr, "' in pointed-to type\n");
910                         return;
911                 }
912
913                 points_to_left  = get_unqualified_type(points_to_left);
914                 points_to_right = get_unqualified_type(points_to_right);
915
916                 if(!is_type_atomic(points_to_left, ATOMIC_TYPE_VOID)
917                                 && !is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)
918                                 && !types_compatible(points_to_left, points_to_right)) {
919                         goto incompatible_assign_types;
920                 }
921
922                 *right = create_implicit_cast(*right, type_left);
923                 return;
924         }
925
926         if (is_type_compound(type_left)
927                         && types_compatible(type_left, type_right)) {
928                 *right = create_implicit_cast(*right, type_left);
929                 return;
930         }
931
932 incompatible_assign_types:
933         /* TODO: improve error message */
934         parser_print_error_prefix();
935         fprintf(stderr, "incompatible types in %s\n", context);
936         parser_print_error_prefix();
937         print_type_quoted(orig_type_left);
938         fputs(" <- ", stderr);
939         print_type_quoted(orig_type_right);
940         fputs("\n", stderr);
941 }
942
943 static expression_t *parse_constant_expression(void)
944 {
945         /* start parsing at precedence 7 (conditional expression) */
946         return parse_sub_expression(7);
947 }
948
949 static expression_t *parse_assignment_expression(void)
950 {
951         /* start parsing at precedence 2 (assignment expression) */
952         return parse_sub_expression(2);
953 }
954
955 static type_t *make_global_typedef(const char *name, type_t *type)
956 {
957         symbol_t *symbol       = symbol_table_insert(name);
958
959         declaration_t *declaration   = allocate_ast_zero(sizeof(declaration[0]));
960         declaration->namespc         = NAMESPACE_NORMAL;
961         declaration->storage_class   = STORAGE_CLASS_TYPEDEF;
962         declaration->type            = type;
963         declaration->symbol          = symbol;
964         declaration->source_position = builtin_source_position;
965
966         record_declaration(declaration);
967
968         type_t *typedef_type               = allocate_type_zero(TYPE_TYPEDEF);
969         typedef_type->typedeft.declaration = declaration;
970
971         return typedef_type;
972 }
973
974 static const char *parse_string_literals(void)
975 {
976         assert(token.type == T_STRING_LITERAL);
977         const char *result = token.v.string;
978
979         next_token();
980
981         while(token.type == T_STRING_LITERAL) {
982                 result = concat_strings(result, token.v.string);
983                 next_token();
984         }
985
986         return result;
987 }
988
989 static void parse_attributes(void)
990 {
991         while(true) {
992                 switch(token.type) {
993                 case T___attribute__: {
994                         next_token();
995
996                         expect_void('(');
997                         int depth = 1;
998                         while(depth > 0) {
999                                 switch(token.type) {
1000                                 case T_EOF:
1001                                         parse_error("EOF while parsing attribute");
1002                                         break;
1003                                 case '(':
1004                                         next_token();
1005                                         depth++;
1006                                         break;
1007                                 case ')':
1008                                         next_token();
1009                                         depth--;
1010                                         break;
1011                                 default:
1012                                         next_token();
1013                                 }
1014                         }
1015                         break;
1016                 }
1017                 case T_asm:
1018                         next_token();
1019                         expect_void('(');
1020                         if(token.type != T_STRING_LITERAL) {
1021                                 parse_error_expected("while parsing assembler attribute",
1022                                                      T_STRING_LITERAL);
1023                                 eat_brace();
1024                                 break;
1025                         } else {
1026                                 parse_string_literals();
1027                         }
1028                         expect_void(')');
1029                         break;
1030                 default:
1031                         goto attributes_finished;
1032                 }
1033         }
1034
1035 attributes_finished:
1036         ;
1037 }
1038
1039 #if 0
1040 static designator_t *parse_designation(void)
1041 {
1042         if(token.type != '[' && token.type != '.')
1043                 return NULL;
1044
1045         designator_t *result = NULL;
1046         designator_t *last   = NULL;
1047
1048         while(1) {
1049                 designator_t *designator;
1050                 switch(token.type) {
1051                 case '[':
1052                         designator = allocate_ast_zero(sizeof(designator[0]));
1053                         next_token();
1054                         designator->array_access = parse_constant_expression();
1055                         expect(']');
1056                         break;
1057                 case '.':
1058                         designator = allocate_ast_zero(sizeof(designator[0]));
1059                         next_token();
1060                         if(token.type != T_IDENTIFIER) {
1061                                 parse_error_expected("while parsing designator",
1062                                                      T_IDENTIFIER, 0);
1063                                 return NULL;
1064                         }
1065                         designator->symbol = token.v.symbol;
1066                         next_token();
1067                         break;
1068                 default:
1069                         expect('=');
1070                         return result;
1071                 }
1072
1073                 assert(designator != NULL);
1074                 if(last != NULL) {
1075                         last->next = designator;
1076                 } else {
1077                         result = designator;
1078                 }
1079                 last = designator;
1080         }
1081 }
1082 #endif
1083
1084 static initializer_t *initializer_from_string(array_type_t *type,
1085                                               const char *string)
1086 {
1087         /* TODO: check len vs. size of array type */
1088         (void) type;
1089
1090         initializer_t *initializer = allocate_initializer(INITIALIZER_STRING);
1091         initializer->string.string = string;
1092
1093         return initializer;
1094 }
1095
1096 static initializer_t *initializer_from_expression(type_t *type,
1097                                                   expression_t *expression)
1098 {
1099         /* TODO check that expression is a constant expression */
1100
1101         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
1102         if(is_type_array(type) && expression->type == EXPR_STRING_LITERAL) {
1103                 array_type_t *array_type   = &type->array;
1104                 type_t       *element_type = array_type->element_type;
1105
1106                 if(element_type->type == TYPE_ATOMIC) {
1107                         atomic_type_t      *atomic_type = &element_type->atomic;
1108                         atomic_type_type_t  atype       = atomic_type->atype;
1109
1110                         /* TODO handle wide strings */
1111                         if(atype == ATOMIC_TYPE_CHAR
1112                                         || atype == ATOMIC_TYPE_SCHAR
1113                                         || atype == ATOMIC_TYPE_UCHAR) {
1114
1115                                 string_literal_expression_t *literal = &expression->string;
1116                                 return initializer_from_string(array_type, literal->value);
1117                         }
1118                 }
1119         }
1120
1121         if(is_type_scalar(type)) {
1122                 semantic_assign(type, &expression, "initializer");
1123
1124                 initializer_t *result = allocate_initializer(INITIALIZER_VALUE);
1125                 result->value.value   = expression;
1126
1127                 return result;
1128         }
1129
1130         return NULL;
1131 }
1132
1133 static initializer_t *parse_sub_initializer(type_t *type,
1134                                             expression_t *expression,
1135                                             type_t *expression_type);
1136
1137 static initializer_t *parse_sub_initializer_elem(type_t *type)
1138 {
1139         if(token.type == '{') {
1140                 return parse_sub_initializer(type, NULL, NULL);
1141         }
1142
1143         expression_t *expression      = parse_assignment_expression();
1144         type_t       *expression_type = skip_typeref(expression->base.datatype);
1145
1146         return parse_sub_initializer(type, expression, expression_type);
1147 }
1148
1149 static bool had_initializer_brace_warning;
1150
1151 static initializer_t *parse_sub_initializer(type_t *type,
1152                                             expression_t *expression,
1153                                             type_t *expression_type)
1154 {
1155         if(is_type_scalar(type)) {
1156                 /* there might be extra {} hierarchies */
1157                 if(token.type == '{') {
1158                         next_token();
1159                         if(!had_initializer_brace_warning) {
1160                                 parse_warning("braces around scalar initializer");
1161                                 had_initializer_brace_warning = true;
1162                         }
1163                         initializer_t *result = parse_sub_initializer(type, NULL, NULL);
1164                         if(token.type == ',') {
1165                                 next_token();
1166                                 /* TODO: warn about excessive elements */
1167                         }
1168                         expect_block('}');
1169                         return result;
1170                 }
1171
1172                 if(expression == NULL) {
1173                         expression = parse_assignment_expression();
1174                 }
1175                 return initializer_from_expression(type, expression);
1176         }
1177
1178         /* does the expression match the currently looked at object to initalize */
1179         if(expression != NULL) {
1180                 initializer_t *result = initializer_from_expression(type, expression);
1181                 if(result != NULL)
1182                         return result;
1183         }
1184
1185         bool read_paren = false;
1186         if(token.type == '{') {
1187                 next_token();
1188                 read_paren = true;
1189         }
1190
1191         /* descend into subtype */
1192         initializer_t  *result = NULL;
1193         initializer_t **elems;
1194         if(is_type_array(type)) {
1195                 array_type_t *array_type   = &type->array;
1196                 type_t       *element_type = array_type->element_type;
1197                 element_type               = skip_typeref(element_type);
1198
1199                 initializer_t *sub;
1200                 had_initializer_brace_warning = false;
1201                 if(expression == NULL) {
1202                         sub = parse_sub_initializer_elem(element_type);
1203                 } else {
1204                         sub = parse_sub_initializer(element_type, expression,
1205                                                     expression_type);
1206                 }
1207
1208                 /* didn't match the subtypes -> try the parent type */
1209                 if(sub == NULL) {
1210                         assert(!read_paren);
1211                         return NULL;
1212                 }
1213
1214                 elems = NEW_ARR_F(initializer_t*, 0);
1215                 ARR_APP1(initializer_t*, elems, sub);
1216
1217                 while(true) {
1218                         if(token.type == '}')
1219                                 break;
1220                         expect_block(',');
1221                         if(token.type == '}')
1222                                 break;
1223
1224                         sub = parse_sub_initializer_elem(element_type);
1225                         if(sub == NULL) {
1226                                 /* TODO error, do nicer cleanup */
1227                                 parse_error("member initializer didn't match");
1228                                 DEL_ARR_F(elems);
1229                                 return NULL;
1230                         }
1231                         ARR_APP1(initializer_t*, elems, sub);
1232                 }
1233         } else {
1234                 assert(is_type_compound(type));
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 (is_type_array(type)) {
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 && is_type_array(type) && 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 && is_type_function(type)) {
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(is_type_function(type));
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                 parameter_type = parameter_declaration->type;
2591
2592                 function_parameter_t *function_parameter
2593                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2594                 memset(function_parameter, 0, sizeof(function_parameter[0]));
2595
2596                 function_parameter->type = parameter_type;
2597                 if(last_parameter != NULL) {
2598                         last_parameter->next = function_parameter;
2599                 } else {
2600                         parameters = function_parameter;
2601                 }
2602                 last_parameter = function_parameter;
2603         }
2604         new_type->function.parameters = parameters;
2605
2606         type = typehash_insert(new_type);
2607         if(type != new_type) {
2608                 obstack_free(type_obst, new_type);
2609         }
2610
2611         declaration->type = type;
2612 }
2613
2614 static void parse_external_declaration(void)
2615 {
2616         /* function-definitions and declarations both start with declaration
2617          * specifiers */
2618         declaration_specifiers_t specifiers;
2619         memset(&specifiers, 0, sizeof(specifiers));
2620         parse_declaration_specifiers(&specifiers);
2621
2622         /* must be a declaration */
2623         if(token.type == ';') {
2624                 parse_anonymous_declaration_rest(&specifiers, record_declaration);
2625                 return;
2626         }
2627
2628         /* declarator is common to both function-definitions and declarations */
2629         declaration_t *ndeclaration = parse_declarator(&specifiers, false);
2630
2631         /* must be a declaration */
2632         if(token.type == ',' || token.type == '=' || token.type == ';') {
2633                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
2634                 return;
2635         }
2636
2637         /* must be a function definition */
2638         parse_kr_declaration_list(ndeclaration);
2639
2640         if(token.type != '{') {
2641                 parse_error_expected("while parsing function definition", '{', 0);
2642                 eat_statement();
2643                 return;
2644         }
2645
2646         type_t *type = ndeclaration->type;
2647         if(type == NULL) {
2648                 eat_block();
2649                 return;
2650         }
2651
2652         /* note that we don't skip typerefs: the standard doesn't allow them here
2653          * (so we can't use is_type_function here) */
2654         if(type->type != TYPE_FUNCTION) {
2655                 parser_print_error_prefix();
2656                 fprintf(stderr, "declarator '");
2657                 print_type_ext(type, ndeclaration->symbol, NULL);
2658                 fprintf(stderr, "' has a body but is not a function type.\n");
2659                 eat_block();
2660                 return;
2661         }
2662
2663         /* Â§ 6.7.5.3 (14) a function definition with () means no
2664          * parameters (and not unspecified parameters) */
2665         if(type->function.unspecified_parameters) {
2666                 type_t *duplicate = duplicate_type(type);
2667                 duplicate->function.unspecified_parameters = false;
2668
2669                 type = typehash_insert(duplicate);
2670                 if(type != duplicate) {
2671                         obstack_free(type_obst, duplicate);
2672                 }
2673                 ndeclaration->type = type;
2674         }
2675
2676         declaration_t *declaration = record_declaration(ndeclaration);
2677         if(ndeclaration != declaration) {
2678                 memcpy(&declaration->context, &ndeclaration->context,
2679                                 sizeof(declaration->context));
2680         }
2681         type = skip_typeref(declaration->type);
2682
2683         /* push function parameters and switch context */
2684         int         top          = environment_top();
2685         context_t  *last_context = context;
2686         set_context(&declaration->context);
2687
2688         declaration_t *parameter = declaration->context.declarations;
2689         for( ; parameter != NULL; parameter = parameter->next) {
2690                 environment_push(parameter);
2691         }
2692
2693         if(declaration->init.statement != NULL) {
2694                 parser_error_multiple_definition(declaration, token.source_position);
2695                 eat_block();
2696                 goto end_of_parse_external_declaration;
2697         } else {
2698                 /* parse function body */
2699                 int            label_stack_top      = label_top();
2700                 declaration_t *old_current_function = current_function;
2701                 current_function                    = declaration;
2702
2703                 declaration->init.statement = parse_compound_statement();
2704
2705                 assert(current_function == declaration);
2706                 current_function = old_current_function;
2707                 label_pop_to(label_stack_top);
2708         }
2709
2710 end_of_parse_external_declaration:
2711         assert(context == &declaration->context);
2712         set_context(last_context);
2713         environment_pop_to(top);
2714 }
2715
2716 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2717 {
2718         while(1) {
2719                 if(token.type == ':') {
2720                         next_token();
2721                         parse_constant_expression();
2722                         /* TODO (bitfields) */
2723                 } else {
2724                         declaration_t *declaration = parse_declarator(specifiers, true);
2725
2726                         /* TODO: check constraints for struct declarations */
2727                         /* TODO: check for doubled fields */
2728                         record_declaration(declaration);
2729
2730                         if(token.type == ':') {
2731                                 next_token();
2732                                 parse_constant_expression();
2733                                 /* TODO (bitfields) */
2734                         }
2735                 }
2736
2737                 if(token.type != ',')
2738                         break;
2739                 next_token();
2740         }
2741         expect_void(';');
2742 }
2743
2744 static void parse_compound_type_entries(void)
2745 {
2746         eat('{');
2747
2748         while(token.type != '}' && token.type != T_EOF) {
2749                 declaration_specifiers_t specifiers;
2750                 memset(&specifiers, 0, sizeof(specifiers));
2751                 parse_declaration_specifiers(&specifiers);
2752
2753                 parse_struct_declarators(&specifiers);
2754         }
2755         if(token.type == T_EOF) {
2756                 parse_error("EOF while parsing struct");
2757         }
2758         next_token();
2759 }
2760
2761 static type_t *parse_typename(void)
2762 {
2763         declaration_specifiers_t specifiers;
2764         memset(&specifiers, 0, sizeof(specifiers));
2765         parse_declaration_specifiers(&specifiers);
2766         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2767                 /* TODO: improve error message, user does probably not know what a
2768                  * storage class is...
2769                  */
2770                 parse_error("typename may not have a storage class");
2771         }
2772
2773         type_t *result = parse_abstract_declarator(specifiers.type);
2774
2775         return result;
2776 }
2777
2778
2779
2780
2781 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2782 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2783                                                           expression_t *left);
2784
2785 typedef struct expression_parser_function_t expression_parser_function_t;
2786 struct expression_parser_function_t {
2787         unsigned                         precedence;
2788         parse_expression_function        parser;
2789         unsigned                         infix_precedence;
2790         parse_expression_infix_function  infix_parser;
2791 };
2792
2793 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2794
2795 static expression_t *make_invalid_expression(void)
2796 {
2797         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2798         expression->base.source_position = token.source_position;
2799         return expression;
2800 }
2801
2802 static expression_t *expected_expression_error(void)
2803 {
2804         parser_print_error_prefix();
2805         fprintf(stderr, "expected expression, got token ");
2806         print_token(stderr, &token);
2807         fprintf(stderr, "\n");
2808
2809         next_token();
2810
2811         return make_invalid_expression();
2812 }
2813
2814 static expression_t *parse_string_const(void)
2815 {
2816         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2817         cnst->base.datatype = type_string;
2818         cnst->string.value  = parse_string_literals();
2819
2820         return cnst;
2821 }
2822
2823 static expression_t *parse_wide_string_const(void)
2824 {
2825         expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
2826         cnst->base.datatype      = type_wchar_t_ptr;
2827         cnst->wide_string.value  = token.v.wide_string; /* TODO concatenate */
2828         next_token();
2829         return cnst;
2830 }
2831
2832 static expression_t *parse_int_const(void)
2833 {
2834         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2835         cnst->base.datatype      = token.datatype;
2836         cnst->conste.v.int_value = token.v.intvalue;
2837
2838         next_token();
2839
2840         return cnst;
2841 }
2842
2843 static expression_t *parse_float_const(void)
2844 {
2845         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2846         cnst->base.datatype        = token.datatype;
2847         cnst->conste.v.float_value = token.v.floatvalue;
2848
2849         next_token();
2850
2851         return cnst;
2852 }
2853
2854 static declaration_t *create_implicit_function(symbol_t *symbol,
2855                 const source_position_t source_position)
2856 {
2857         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2858         ntype->function.return_type            = type_int;
2859         ntype->function.unspecified_parameters = true;
2860
2861         type_t *type = typehash_insert(ntype);
2862         if(type != ntype) {
2863                 free_type(ntype);
2864         }
2865
2866         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2867
2868         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2869         declaration->type            = type;
2870         declaration->symbol          = symbol;
2871         declaration->source_position = source_position;
2872
2873         /* prepend the implicit definition to the global context
2874          * this is safe since the symbol wasn't declared as anything else yet
2875          */
2876         assert(symbol->declaration == NULL);
2877
2878         context_t *last_context = context;
2879         context = global_context;
2880
2881         environment_push(declaration);
2882         declaration->next     = context->declarations;
2883         context->declarations = declaration;
2884
2885         context = last_context;
2886
2887         return declaration;
2888 }
2889
2890 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
2891 {
2892         function_parameter_t *parameter
2893                 = obstack_alloc(type_obst, sizeof(parameter[0]));
2894         memset(parameter, 0, sizeof(parameter[0]));
2895         parameter->type = argument_type;
2896
2897         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
2898         type->function.return_type = return_type;
2899         type->function.parameters  = parameter;
2900
2901         type_t *result = typehash_insert(type);
2902         if(result != type) {
2903                 free_type(type);
2904         }
2905
2906         return result;
2907 }
2908
2909 static type_t *get_builtin_symbol_type(symbol_t *symbol)
2910 {
2911         switch(symbol->ID) {
2912         case T___builtin_alloca:
2913                 return make_function_1_type(type_void_ptr, type_size_t);
2914         case T___builtin_nan:
2915                 return make_function_1_type(type_double, type_string);
2916         case T___builtin_nanf:
2917                 return make_function_1_type(type_float, type_string);
2918         case T___builtin_nand:
2919                 return make_function_1_type(type_long_double, type_string);
2920         default:
2921                 panic("not implemented builtin symbol found");
2922         }
2923 }
2924
2925 /**
2926  * performs automatic type cast as described in Â§ 6.3.2.1
2927  */
2928 static type_t *automatic_type_conversion(type_t *orig_type)
2929 {
2930         if(orig_type == NULL)
2931                 return NULL;
2932
2933         type_t *type = skip_typeref(orig_type);
2934         if(is_type_array(type)) {
2935                 array_type_t *array_type   = &type->array;
2936                 type_t       *element_type = array_type->element_type;
2937                 unsigned      qualifiers   = array_type->type.qualifiers;
2938
2939                 return make_pointer_type(element_type, qualifiers);
2940         }
2941
2942         if(is_type_function(type)) {
2943                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
2944         }
2945
2946         return orig_type;
2947 }
2948
2949 /**
2950  * reverts the automatic casts of array to pointer types and function
2951  * to function-pointer types as defined Â§ 6.3.2.1
2952  */
2953 type_t *revert_automatic_type_conversion(const expression_t *expression)
2954 {
2955         if(expression->base.datatype == NULL)
2956                 return NULL;
2957
2958         switch(expression->type) {
2959         case EXPR_REFERENCE: {
2960                 const reference_expression_t *ref = &expression->reference;
2961                 return ref->declaration->type;
2962         }
2963         case EXPR_SELECT: {
2964                 const select_expression_t *select = &expression->select;
2965                 return select->compound_entry->type;
2966         }
2967         case EXPR_UNARY: {
2968                 const unary_expression_t *unary = &expression->unary;
2969                 if(unary->type == UNEXPR_DEREFERENCE) {
2970                         expression_t   *value        = unary->value;
2971                         type_t         *type         = skip_typeref(value->base.datatype);
2972                         pointer_type_t *pointer_type = &type->pointer;
2973
2974                         return pointer_type->points_to;
2975                 }
2976                 break;
2977         }
2978         case EXPR_BUILTIN_SYMBOL: {
2979                 const builtin_symbol_expression_t *builtin
2980                         = &expression->builtin_symbol;
2981                 return get_builtin_symbol_type(builtin->symbol);
2982         }
2983         case EXPR_ARRAY_ACCESS: {
2984                 const array_access_expression_t *array_access
2985                         = &expression->array_access;
2986                 const expression_t *array_ref = array_access->array_ref;
2987                 type_t *type_left  = skip_typeref(array_ref->base.datatype);
2988                 assert(is_type_pointer(type_left));
2989                 pointer_type_t *pointer_type = &type_left->pointer;
2990                 return pointer_type->points_to;
2991         }
2992
2993         default:
2994                 break;
2995         }
2996
2997         return expression->base.datatype;
2998 }
2999
3000 static expression_t *parse_reference(void)
3001 {
3002         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3003
3004         reference_expression_t *ref = &expression->reference;
3005         ref->symbol = token.v.symbol;
3006
3007         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3008
3009         source_position_t source_position = token.source_position;
3010         next_token();
3011
3012         if(declaration == NULL) {
3013 #ifndef STRICT_C99
3014                 /* an implicitly defined function */
3015                 if(token.type == '(') {
3016                         parser_print_prefix_pos(token.source_position);
3017                         fprintf(stderr, "warning: implicit declaration of function '%s'\n",
3018                                 ref->symbol->string);
3019
3020                         declaration = create_implicit_function(ref->symbol,
3021                                                                source_position);
3022                 } else
3023 #endif
3024                 {
3025                         parser_print_error_prefix();
3026                         fprintf(stderr, "unknown symbol '%s' found.\n", ref->symbol->string);
3027                         return expression;
3028                 }
3029         }
3030
3031         type_t *type = declaration->type;
3032         /* we always do the auto-type conversions; the & and sizeof parser contains
3033          * code to revert this! */
3034         type = automatic_type_conversion(type);
3035
3036         ref->declaration         = declaration;
3037         ref->expression.datatype = type;
3038
3039         return expression;
3040 }
3041
3042 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3043 {
3044         (void) expression;
3045         (void) dest_type;
3046         /* TODO check if explicit cast is allowed and issue warnings/errors */
3047 }
3048
3049 static expression_t *parse_cast(void)
3050 {
3051         expression_t *cast = allocate_expression_zero(EXPR_UNARY);
3052
3053         cast->unary.type           = UNEXPR_CAST;
3054         cast->base.source_position = token.source_position;
3055
3056         type_t *type  = parse_typename();
3057
3058         expect(')');
3059         expression_t *value = parse_sub_expression(20);
3060
3061         check_cast_allowed(value, type);
3062
3063         cast->base.datatype = type;
3064         cast->unary.value   = value;
3065
3066         return cast;
3067 }
3068
3069 static expression_t *parse_statement_expression(void)
3070 {
3071         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3072
3073         statement_t *statement          = parse_compound_statement();
3074         expression->statement.statement = statement;
3075         if(statement == NULL) {
3076                 expect(')');
3077                 return NULL;
3078         }
3079
3080         assert(statement->type == STATEMENT_COMPOUND);
3081         compound_statement_t *compound_statement = &statement->compound;
3082
3083         /* find last statement and use it's type */
3084         const statement_t *last_statement = NULL;
3085         const statement_t *iter           = compound_statement->statements;
3086         for( ; iter != NULL; iter = iter->base.next) {
3087                 last_statement = iter;
3088         }
3089
3090         if(last_statement->type == STATEMENT_EXPRESSION) {
3091                 const expression_statement_t *expression_statement
3092                         = &last_statement->expression;
3093                 expression->base.datatype
3094                         = expression_statement->expression->base.datatype;
3095         } else {
3096                 expression->base.datatype = type_void;
3097         }
3098
3099         expect(')');
3100
3101         return expression;
3102 }
3103
3104 static expression_t *parse_brace_expression(void)
3105 {
3106         eat('(');
3107
3108         switch(token.type) {
3109         case '{':
3110                 /* gcc extension: a stement expression */
3111                 return parse_statement_expression();
3112
3113         TYPE_QUALIFIERS
3114         TYPE_SPECIFIERS
3115                 return parse_cast();
3116         case T_IDENTIFIER:
3117                 if(is_typedef_symbol(token.v.symbol)) {
3118                         return parse_cast();
3119                 }
3120         }
3121
3122         expression_t *result = parse_expression();
3123         expect(')');
3124
3125         return result;
3126 }
3127
3128 static expression_t *parse_function_keyword(void)
3129 {
3130         next_token();
3131         /* TODO */
3132
3133         if (current_function == NULL) {
3134                 parse_error("'__func__' used outside of a function");
3135         }
3136
3137         string_literal_expression_t *expression
3138                 = allocate_ast_zero(sizeof(expression[0]));
3139
3140         expression->expression.type     = EXPR_FUNCTION;
3141         expression->expression.datatype = type_string;
3142         expression->value               = "TODO: FUNCTION";
3143
3144         return (expression_t*) expression;
3145 }
3146
3147 static expression_t *parse_pretty_function_keyword(void)
3148 {
3149         eat(T___PRETTY_FUNCTION__);
3150         /* TODO */
3151
3152         string_literal_expression_t *expression
3153                 = allocate_ast_zero(sizeof(expression[0]));
3154
3155         expression->expression.type     = EXPR_PRETTY_FUNCTION;
3156         expression->expression.datatype = type_string;
3157         expression->value               = "TODO: PRETTY FUNCTION";
3158
3159         return (expression_t*) expression;
3160 }
3161
3162 static designator_t *parse_designator(void)
3163 {
3164         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3165
3166         if(token.type != T_IDENTIFIER) {
3167                 parse_error_expected("while parsing member designator",
3168                                      T_IDENTIFIER, 0);
3169                 eat_brace();
3170                 return NULL;
3171         }
3172         result->symbol = token.v.symbol;
3173         next_token();
3174
3175         designator_t *last_designator = result;
3176         while(true) {
3177                 if(token.type == '.') {
3178                         next_token();
3179                         if(token.type != T_IDENTIFIER) {
3180                                 parse_error_expected("while parsing member designator",
3181                                                      T_IDENTIFIER, 0);
3182                                 eat_brace();
3183                                 return NULL;
3184                         }
3185                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3186                         designator->symbol       = token.v.symbol;
3187                         next_token();
3188
3189                         last_designator->next = designator;
3190                         last_designator       = designator;
3191                         continue;
3192                 }
3193                 if(token.type == '[') {
3194                         next_token();
3195                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3196                         designator->array_access = parse_expression();
3197                         if(designator->array_access == NULL) {
3198                                 eat_brace();
3199                                 return NULL;
3200                         }
3201                         expect(']');
3202
3203                         last_designator->next = designator;
3204                         last_designator       = designator;
3205                         continue;
3206                 }
3207                 break;
3208         }
3209
3210         return result;
3211 }
3212
3213 static expression_t *parse_offsetof(void)
3214 {
3215         eat(T___builtin_offsetof);
3216
3217         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3218         expression->base.datatype = type_size_t;
3219
3220         expect('(');
3221         expression->offsetofe.type = parse_typename();
3222         expect(',');
3223         expression->offsetofe.designator = parse_designator();
3224         expect(')');
3225
3226         return expression;
3227 }
3228
3229 static expression_t *parse_va_arg(void)
3230 {
3231         eat(T___builtin_va_arg);
3232
3233         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3234
3235         expect('(');
3236         expression->va_arge.arg = parse_assignment_expression();
3237         expect(',');
3238         expression->base.datatype = parse_typename();
3239         expect(')');
3240
3241         return expression;
3242 }
3243
3244 static expression_t *parse_builtin_symbol(void)
3245 {
3246         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3247
3248         symbol_t *symbol = token.v.symbol;
3249
3250         expression->builtin_symbol.symbol = symbol;
3251         next_token();
3252
3253         type_t *type = get_builtin_symbol_type(symbol);
3254         type = automatic_type_conversion(type);
3255
3256         expression->base.datatype = type;
3257         return expression;
3258 }
3259
3260 static expression_t *parse_primary_expression(void)
3261 {
3262         switch(token.type) {
3263         case T_INTEGER:
3264                 return parse_int_const();
3265         case T_FLOATINGPOINT:
3266                 return parse_float_const();
3267         case T_STRING_LITERAL: /* TODO merge */
3268                 return parse_string_const();
3269         case T_WIDE_STRING_LITERAL:
3270                 return parse_wide_string_const();
3271         case T_IDENTIFIER:
3272                 return parse_reference();
3273         case T___FUNCTION__:
3274         case T___func__:
3275                 return parse_function_keyword();
3276         case T___PRETTY_FUNCTION__:
3277                 return parse_pretty_function_keyword();
3278         case T___builtin_offsetof:
3279                 return parse_offsetof();
3280         case T___builtin_va_arg:
3281                 return parse_va_arg();
3282         case T___builtin_nanf:
3283         case T___builtin_alloca:
3284         case T___builtin_expect:
3285         case T___builtin_va_start:
3286         case T___builtin_va_end:
3287                 return parse_builtin_symbol();
3288
3289         case '(':
3290                 return parse_brace_expression();
3291         }
3292
3293         parser_print_error_prefix();
3294         fprintf(stderr, "unexpected token ");
3295         print_token(stderr, &token);
3296         fprintf(stderr, "\n");
3297         eat_statement();
3298
3299         return make_invalid_expression();
3300 }
3301
3302 static expression_t *parse_array_expression(unsigned precedence,
3303                                             expression_t *left)
3304 {
3305         (void) precedence;
3306
3307         eat('[');
3308
3309         expression_t *inside = parse_expression();
3310
3311         array_access_expression_t *array_access
3312                 = allocate_ast_zero(sizeof(array_access[0]));
3313
3314         array_access->expression.type = EXPR_ARRAY_ACCESS;
3315
3316         type_t *type_left   = left->base.datatype;
3317         type_t *type_inside = inside->base.datatype;
3318         type_t *return_type = NULL;
3319
3320         if(type_left != NULL && type_inside != NULL) {
3321                 type_left   = skip_typeref(type_left);
3322                 type_inside = skip_typeref(type_inside);
3323
3324                 if(is_type_pointer(type_left)) {
3325                         pointer_type_t *pointer = &type_left->pointer;
3326                         return_type             = pointer->points_to;
3327                         array_access->array_ref = left;
3328                         array_access->index     = inside;
3329                 } else if(is_type_pointer(type_inside)) {
3330                         pointer_type_t *pointer = &type_inside->pointer;
3331                         return_type             = pointer->points_to;
3332                         array_access->array_ref = inside;
3333                         array_access->index     = left;
3334                         array_access->flipped   = true;
3335                 } else {
3336                         parser_print_error_prefix();
3337                         fprintf(stderr, "array access on object with non-pointer types ");
3338                         print_type_quoted(type_left);
3339                         fprintf(stderr, ", ");
3340                         print_type_quoted(type_inside);
3341                         fprintf(stderr, "\n");
3342                 }
3343         } else {
3344                 array_access->array_ref = left;
3345                 array_access->index     = inside;
3346         }
3347
3348         if(token.type != ']') {
3349                 parse_error_expected("Problem while parsing array access", ']', 0);
3350                 return (expression_t*) array_access;
3351         }
3352         next_token();
3353
3354         return_type = automatic_type_conversion(return_type);
3355         array_access->expression.datatype = return_type;
3356
3357         return (expression_t*) array_access;
3358 }
3359
3360 static expression_t *parse_sizeof(unsigned precedence)
3361 {
3362         eat(T_sizeof);
3363
3364         sizeof_expression_t *sizeof_expression
3365                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3366         sizeof_expression->expression.type     = EXPR_SIZEOF;
3367         sizeof_expression->expression.datatype = type_size_t;
3368
3369         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3370                 next_token();
3371                 sizeof_expression->type = parse_typename();
3372                 expect(')');
3373         } else {
3374                 expression_t *expression  = parse_sub_expression(precedence);
3375                 expression->base.datatype = revert_automatic_type_conversion(expression);
3376
3377                 sizeof_expression->type            = expression->base.datatype;
3378                 sizeof_expression->size_expression = expression;
3379         }
3380
3381         return (expression_t*) sizeof_expression;
3382 }
3383
3384 static expression_t *parse_select_expression(unsigned precedence,
3385                                              expression_t *compound)
3386 {
3387         (void) precedence;
3388         assert(token.type == '.' || token.type == T_MINUSGREATER);
3389
3390         bool is_pointer = (token.type == T_MINUSGREATER);
3391         next_token();
3392
3393         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3394         select->select.compound = compound;
3395
3396         if(token.type != T_IDENTIFIER) {
3397                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3398                 return select;
3399         }
3400         symbol_t *symbol      = token.v.symbol;
3401         select->select.symbol = symbol;
3402         next_token();
3403
3404         type_t *orig_type = compound->base.datatype;
3405         if(orig_type == NULL)
3406                 return make_invalid_expression();
3407
3408         type_t *type = skip_typeref(orig_type);
3409
3410         type_t *type_left = type;
3411         if(is_pointer) {
3412                 if(type->type != TYPE_POINTER) {
3413                         parser_print_error_prefix();
3414                         fprintf(stderr, "left hand side of '->' is not a pointer, but ");
3415                         print_type_quoted(orig_type);
3416                         fputc('\n', stderr);
3417                         return make_invalid_expression();
3418                 }
3419                 pointer_type_t *pointer_type = &type->pointer;
3420                 type_left                    = pointer_type->points_to;
3421         }
3422         type_left = skip_typeref(type_left);
3423
3424         if(type_left->type != TYPE_COMPOUND_STRUCT
3425                         && type_left->type != TYPE_COMPOUND_UNION) {
3426                 parser_print_error_prefix();
3427                 fprintf(stderr, "request for member '%s' in something not a struct or "
3428                         "union, but ", symbol->string);
3429                 print_type_quoted(type_left);
3430                 fputc('\n', stderr);
3431                 return make_invalid_expression();
3432         }
3433
3434         compound_type_t *compound_type = &type_left->compound;
3435         declaration_t   *declaration   = compound_type->declaration;
3436
3437         if(!declaration->init.is_defined) {
3438                 parser_print_error_prefix();
3439                 fprintf(stderr, "request for member '%s' of incomplete type ",
3440                         symbol->string);
3441                 print_type_quoted(type_left);
3442                 fputc('\n', stderr);
3443                 return make_invalid_expression();
3444         }
3445
3446         declaration_t *iter = declaration->context.declarations;
3447         for( ; iter != NULL; iter = iter->next) {
3448                 if(iter->symbol == symbol) {
3449                         break;
3450                 }
3451         }
3452         if(iter == NULL) {
3453                 parser_print_error_prefix();
3454                 print_type_quoted(type_left);
3455                 fprintf(stderr, " has no member named '%s'\n", symbol->string);
3456                 return make_invalid_expression();
3457         }
3458
3459         /* we always do the auto-type conversions; the & and sizeof parser contains
3460          * code to revert this! */
3461         type_t *expression_type = automatic_type_conversion(iter->type);
3462
3463         select->select.compound_entry = iter;
3464         select->base.datatype         = expression_type;
3465         return select;
3466 }
3467
3468 static expression_t *parse_call_expression(unsigned precedence,
3469                                            expression_t *expression)
3470 {
3471         (void) precedence;
3472         expression_t *result = allocate_expression_zero(EXPR_CALL);
3473
3474         call_expression_t *call  = &result->call;
3475         call->function           = expression;
3476
3477         function_type_t *function_type = NULL;
3478         type_t          *orig_type     = expression->base.datatype;
3479         if(orig_type != NULL) {
3480                 type_t *type  = skip_typeref(orig_type);
3481
3482                 if(is_type_pointer(type)) {
3483                         pointer_type_t *pointer_type = &type->pointer;
3484
3485                         type = skip_typeref(pointer_type->points_to);
3486
3487                         if (is_type_function(type)) {
3488                                 function_type             = &type->function;
3489                                 call->expression.datatype = function_type->return_type;
3490                         }
3491                 }
3492                 if(function_type == NULL) {
3493                         parser_print_error_prefix();
3494                         fputs("called object '", stderr);
3495                         print_expression(expression);
3496                         fputs("' (type ", stderr);
3497                         print_type_quoted(orig_type);
3498                         fputs(") is not a pointer to a function\n", stderr);
3499
3500                         function_type             = NULL;
3501                         call->expression.datatype = NULL;
3502                 }
3503         }
3504
3505         /* parse arguments */
3506         eat('(');
3507
3508         if(token.type != ')') {
3509                 call_argument_t *last_argument = NULL;
3510
3511                 while(true) {
3512                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3513
3514                         argument->expression = parse_assignment_expression();
3515                         if(last_argument == NULL) {
3516                                 call->arguments = argument;
3517                         } else {
3518                                 last_argument->next = argument;
3519                         }
3520                         last_argument = argument;
3521
3522                         if(token.type != ',')
3523                                 break;
3524                         next_token();
3525                 }
3526         }
3527         expect(')');
3528
3529         if(function_type != NULL) {
3530                 function_parameter_t *parameter = function_type->parameters;
3531                 call_argument_t      *argument  = call->arguments;
3532                 for( ; parameter != NULL && argument != NULL;
3533                                 parameter = parameter->next, argument = argument->next) {
3534                         type_t *expected_type = parameter->type;
3535                         /* TODO report context in error messages */
3536                         argument->expression = create_implicit_cast(argument->expression,
3537                                                                     expected_type);
3538                 }
3539                 /* too few parameters */
3540                 if(parameter != NULL) {
3541                         parser_print_error_prefix();
3542                         fprintf(stderr, "too few arguments to function '");
3543                         print_expression(expression);
3544                         fprintf(stderr, "'\n");
3545                 } else if(argument != NULL) {
3546                         /* too many parameters */
3547                         if(!function_type->variadic
3548                                         && !function_type->unspecified_parameters) {
3549                                 parser_print_error_prefix();
3550                                 fprintf(stderr, "too many arguments to function '");
3551                                 print_expression(expression);
3552                                 fprintf(stderr, "'\n");
3553                         } else {
3554                                 /* do default promotion */
3555                                 for( ; argument != NULL; argument = argument->next) {
3556                                         type_t *type = argument->expression->base.datatype;
3557
3558                                         if(type == NULL)
3559                                                 continue;
3560
3561                                         type = skip_typeref(type);
3562                                         if(is_type_integer(type)) {
3563                                                 type = promote_integer(type);
3564                                         } else if(type == type_float) {
3565                                                 type = type_double;
3566                                         }
3567
3568                                         argument->expression
3569                                                 = create_implicit_cast(argument->expression, type);
3570                                 }
3571                         }
3572                 }
3573         }
3574
3575         return result;
3576 }
3577
3578 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3579
3580 static bool same_compound_type(const type_t *type1, const type_t *type2)
3581 {
3582         if(!is_type_compound(type1))
3583                 return false;
3584         if(type1->type != type2->type)
3585                 return false;
3586
3587         const compound_type_t *compound1 = &type1->compound;
3588         const compound_type_t *compound2 = &type2->compound;
3589
3590         return compound1->declaration == compound2->declaration;
3591 }
3592
3593 static expression_t *parse_conditional_expression(unsigned precedence,
3594                                                   expression_t *expression)
3595 {
3596         eat('?');
3597
3598         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3599
3600         conditional_expression_t *conditional = &result->conditional;
3601         conditional->condition = expression;
3602
3603         /* 6.5.15.2 */
3604         type_t *condition_type_orig = expression->base.datatype;
3605         if(condition_type_orig != NULL) {
3606                 type_t *condition_type = skip_typeref(condition_type_orig);
3607                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3608                         type_error("expected a scalar type in conditional condition",
3609                                    expression->base.source_position, condition_type_orig);
3610                 }
3611         }
3612
3613         expression_t *true_expression = parse_expression();
3614         expect(':');
3615         expression_t *false_expression = parse_sub_expression(precedence);
3616
3617         conditional->true_expression  = true_expression;
3618         conditional->false_expression = false_expression;
3619
3620         type_t *orig_true_type  = true_expression->base.datatype;
3621         type_t *orig_false_type = false_expression->base.datatype;
3622         if(orig_true_type == NULL || orig_false_type == NULL)
3623                 return result;
3624
3625         type_t *true_type  = skip_typeref(orig_true_type);
3626         type_t *false_type = skip_typeref(orig_false_type);
3627
3628         /* 6.5.15.3 */
3629         type_t *result_type = NULL;
3630         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3631                 result_type = semantic_arithmetic(true_type, false_type);
3632
3633                 true_expression  = create_implicit_cast(true_expression, result_type);
3634                 false_expression = create_implicit_cast(false_expression, result_type);
3635
3636                 conditional->true_expression     = true_expression;
3637                 conditional->false_expression    = false_expression;
3638                 conditional->expression.datatype = result_type;
3639         } else if (same_compound_type(true_type, false_type)
3640                         || (is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3641                                 is_type_atomic(false_type, ATOMIC_TYPE_VOID))) {
3642                 /* just take 1 of the 2 types */
3643                 result_type = true_type;
3644         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3645                         && pointers_compatible(true_type, false_type)) {
3646                 /* ok */
3647                 result_type = true_type;
3648         } else {
3649                 /* TODO */
3650                 type_error_incompatible("while parsing conditional",
3651                                         expression->base.source_position, true_type,
3652                                         false_type);
3653         }
3654
3655         conditional->expression.datatype = result_type;
3656         return result;
3657 }
3658
3659 static expression_t *parse_extension(unsigned precedence)
3660 {
3661         eat(T___extension__);
3662
3663         /* TODO enable extensions */
3664
3665         return parse_sub_expression(precedence);
3666 }
3667
3668 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3669 {
3670         eat(T___builtin_classify_type);
3671
3672         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
3673         result->base.datatype = type_int;
3674
3675         expect('(');
3676         expression_t *expression = parse_sub_expression(precedence);
3677         expect(')');
3678         result->classify_type.type_expression = expression;
3679
3680         return result;
3681 }
3682
3683 static void semantic_incdec(unary_expression_t *expression)
3684 {
3685         type_t *orig_type = expression->value->base.datatype;
3686         if(orig_type == NULL)
3687                 return;
3688
3689         type_t *type = skip_typeref(orig_type);
3690         if(!is_type_arithmetic(type) && type->type != TYPE_POINTER) {
3691                 /* TODO: improve error message */
3692                 parser_print_error_prefix();
3693                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
3694                 return;
3695         }
3696
3697         expression->expression.datatype = orig_type;
3698 }
3699
3700 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3701 {
3702         type_t *orig_type = expression->value->base.datatype;
3703         if(orig_type == NULL)
3704                 return;
3705
3706         type_t *type = skip_typeref(orig_type);
3707         if(!is_type_arithmetic(type)) {
3708                 /* TODO: improve error message */
3709                 parser_print_error_prefix();
3710                 fprintf(stderr, "operation needs an arithmetic type\n");
3711                 return;
3712         }
3713
3714         expression->expression.datatype = orig_type;
3715 }
3716
3717 static void semantic_unexpr_scalar(unary_expression_t *expression)
3718 {
3719         type_t *orig_type = expression->value->base.datatype;
3720         if(orig_type == NULL)
3721                 return;
3722
3723         type_t *type = skip_typeref(orig_type);
3724         if (!is_type_scalar(type)) {
3725                 parse_error("operand of ! must be of scalar type\n");
3726                 return;
3727         }
3728
3729         expression->expression.datatype = orig_type;
3730 }
3731
3732 static void semantic_unexpr_integer(unary_expression_t *expression)
3733 {
3734         type_t *orig_type = expression->value->base.datatype;
3735         if(orig_type == NULL)
3736                 return;
3737
3738         type_t *type = skip_typeref(orig_type);
3739         if (!is_type_integer(type)) {
3740                 parse_error("operand of ~ must be of integer type\n");
3741                 return;
3742         }
3743
3744         expression->expression.datatype = orig_type;
3745 }
3746
3747 static void semantic_dereference(unary_expression_t *expression)
3748 {
3749         type_t *orig_type = expression->value->base.datatype;
3750         if(orig_type == NULL)
3751                 return;
3752
3753         type_t *type = skip_typeref(orig_type);
3754         if(!is_type_pointer(type)) {
3755                 parser_print_error_prefix();
3756                 fputs("Unary '*' needs pointer or arrray type, but type ", stderr);
3757                 print_type_quoted(orig_type);
3758                 fputs(" given.\n", stderr);
3759                 return;
3760         }
3761
3762         pointer_type_t *pointer_type = &type->pointer;
3763         type_t         *result_type  = pointer_type->points_to;
3764
3765         result_type = automatic_type_conversion(result_type);
3766         expression->expression.datatype = result_type;
3767 }
3768
3769 static void semantic_take_addr(unary_expression_t *expression)
3770 {
3771         expression_t *value  = expression->value;
3772         value->base.datatype = revert_automatic_type_conversion(value);
3773
3774         type_t *orig_type = value->base.datatype;
3775         if(orig_type == NULL)
3776                 return;
3777
3778         if(value->type == EXPR_REFERENCE) {
3779                 reference_expression_t *reference   = (reference_expression_t*) value;
3780                 declaration_t          *declaration = reference->declaration;
3781                 if(declaration != NULL) {
3782                         declaration->address_taken = 1;
3783                 }
3784         }
3785
3786         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3787 }
3788
3789 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3790 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3791 {                                                                              \
3792         eat(token_type);                                                           \
3793                                                                                \
3794         unary_expression_t *unary_expression                                       \
3795                 = allocate_ast_zero(sizeof(unary_expression[0]));                      \
3796         unary_expression->expression.type     = EXPR_UNARY;                        \
3797         unary_expression->type                = unexpression_type;                 \
3798         unary_expression->value               = parse_sub_expression(precedence);  \
3799                                                                                    \
3800         sfunc(unary_expression);                                                   \
3801                                                                                \
3802         return (expression_t*) unary_expression;                                   \
3803 }
3804
3805 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE, semantic_unexpr_arithmetic)
3806 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS,   semantic_unexpr_arithmetic)
3807 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT,    semantic_unexpr_scalar)
3808 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE, semantic_dereference)
3809 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS, semantic_take_addr)
3810 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE,
3811                                semantic_unexpr_integer)
3812 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT,
3813                                semantic_incdec)
3814 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT,
3815                                semantic_incdec)
3816
3817 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
3818                                                sfunc)                         \
3819 static expression_t *parse_##unexpression_type(unsigned precedence,           \
3820                                                expression_t *left)            \
3821 {                                                                             \
3822         (void) precedence;                                                        \
3823         eat(token_type);                                                          \
3824                                                                               \
3825         unary_expression_t *unary_expression                                      \
3826                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
3827         unary_expression->expression.type     = EXPR_UNARY;                       \
3828         unary_expression->type                = unexpression_type;                \
3829         unary_expression->value               = left;                             \
3830                                                                                   \
3831         sfunc(unary_expression);                                                  \
3832                                                                               \
3833         return (expression_t*) unary_expression;                                  \
3834 }
3835
3836 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT,
3837                                        semantic_incdec)
3838 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT,
3839                                        semantic_incdec)
3840
3841 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
3842 {
3843         /* TODO: handle complex + imaginary types */
3844
3845         /* Â§ 6.3.1.8 Usual arithmetic conversions */
3846         if(type_left == type_long_double || type_right == type_long_double) {
3847                 return type_long_double;
3848         } else if(type_left == type_double || type_right == type_double) {
3849                 return type_double;
3850         } else if(type_left == type_float || type_right == type_float) {
3851                 return type_float;
3852         }
3853
3854         type_right = promote_integer(type_right);
3855         type_left  = promote_integer(type_left);
3856
3857         if(type_left == type_right)
3858                 return type_left;
3859
3860         bool signed_left  = is_type_signed(type_left);
3861         bool signed_right = is_type_signed(type_right);
3862         int  rank_left    = get_rank(type_left);
3863         int  rank_right   = get_rank(type_right);
3864         if(rank_left < rank_right) {
3865                 if(signed_left == signed_right || !signed_right) {
3866                         return type_right;
3867                 } else {
3868                         return type_left;
3869                 }
3870         } else {
3871                 if(signed_left == signed_right || !signed_left) {
3872                         return type_left;
3873                 } else {
3874                         return type_right;
3875                 }
3876         }
3877 }
3878
3879 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
3880 {
3881         expression_t *left       = expression->left;
3882         expression_t *right      = expression->right;
3883         type_t       *orig_type_left  = left->base.datatype;
3884         type_t       *orig_type_right = right->base.datatype;
3885
3886         if(orig_type_left == NULL || orig_type_right == NULL)
3887                 return;
3888
3889         type_t *type_left  = skip_typeref(orig_type_left);
3890         type_t *type_right = skip_typeref(orig_type_right);
3891
3892         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3893                 /* TODO: improve error message */
3894                 parser_print_error_prefix();
3895                 fprintf(stderr, "operation needs arithmetic types\n");
3896                 return;
3897         }
3898
3899         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3900         expression->left  = create_implicit_cast(left, arithmetic_type);
3901         expression->right = create_implicit_cast(right, arithmetic_type);
3902         expression->expression.datatype = arithmetic_type;
3903 }
3904
3905 static void semantic_shift_op(binary_expression_t *expression)
3906 {
3907         expression_t *left       = expression->left;
3908         expression_t *right      = expression->right;
3909         type_t       *orig_type_left  = left->base.datatype;
3910         type_t       *orig_type_right = right->base.datatype;
3911
3912         if(orig_type_left == NULL || orig_type_right == NULL)
3913                 return;
3914
3915         type_t *type_left  = skip_typeref(orig_type_left);
3916         type_t *type_right = skip_typeref(orig_type_right);
3917
3918         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
3919                 /* TODO: improve error message */
3920                 parser_print_error_prefix();
3921                 fprintf(stderr, "operation needs integer types\n");
3922                 return;
3923         }
3924
3925         type_left  = promote_integer(type_left);
3926         type_right = promote_integer(type_right);
3927
3928         expression->left  = create_implicit_cast(left, type_left);
3929         expression->right = create_implicit_cast(right, type_right);
3930         expression->expression.datatype = type_left;
3931 }
3932
3933 static void semantic_add(binary_expression_t *expression)
3934 {
3935         expression_t *left            = expression->left;
3936         expression_t *right           = expression->right;
3937         type_t       *orig_type_left  = left->base.datatype;
3938         type_t       *orig_type_right = right->base.datatype;
3939
3940         if(orig_type_left == NULL || orig_type_right == NULL)
3941                 return;
3942
3943         type_t *type_left  = skip_typeref(orig_type_left);
3944         type_t *type_right = skip_typeref(orig_type_right);
3945
3946         /* Â§ 5.6.5 */
3947         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3948                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3949                 expression->left  = create_implicit_cast(left, arithmetic_type);
3950                 expression->right = create_implicit_cast(right, arithmetic_type);
3951                 expression->expression.datatype = arithmetic_type;
3952                 return;
3953         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
3954                 expression->expression.datatype = type_left;
3955         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
3956                 expression->expression.datatype = type_right;
3957         } else {
3958                 parser_print_error_prefix();
3959                 fprintf(stderr, "invalid operands to binary + (");
3960                 print_type_quoted(orig_type_left);
3961                 fprintf(stderr, ", ");
3962                 print_type_quoted(orig_type_right);
3963                 fprintf(stderr, ")\n");
3964         }
3965 }
3966
3967 static void semantic_sub(binary_expression_t *expression)
3968 {
3969         expression_t *left            = expression->left;
3970         expression_t *right           = expression->right;
3971         type_t       *orig_type_left  = left->base.datatype;
3972         type_t       *orig_type_right = right->base.datatype;
3973
3974         if(orig_type_left == NULL || orig_type_right == NULL)
3975                 return;
3976
3977         type_t       *type_left       = skip_typeref(orig_type_left);
3978         type_t       *type_right      = skip_typeref(orig_type_right);
3979
3980         /* Â§ 5.6.5 */
3981         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3982                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3983                 expression->left  = create_implicit_cast(left, arithmetic_type);
3984                 expression->right = create_implicit_cast(right, arithmetic_type);
3985                 expression->expression.datatype = arithmetic_type;
3986                 return;
3987         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
3988                 expression->expression.datatype = type_left;
3989         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
3990                 if(!pointers_compatible(type_left, type_right)) {
3991                         parser_print_error_prefix();
3992                         fprintf(stderr, "pointers to incompatible objects to binary - (");
3993                         print_type_quoted(orig_type_left);
3994                         fprintf(stderr, ", ");
3995                         print_type_quoted(orig_type_right);
3996                         fprintf(stderr, ")\n");
3997                 } else {
3998                         expression->expression.datatype = type_ptrdiff_t;
3999                 }
4000         } else {
4001                 parser_print_error_prefix();
4002                 fprintf(stderr, "invalid operands to binary - (");
4003                 print_type_quoted(orig_type_left);
4004                 fprintf(stderr, ", ");
4005                 print_type_quoted(orig_type_right);
4006                 fprintf(stderr, ")\n");
4007         }
4008 }
4009
4010 static void semantic_comparison(binary_expression_t *expression)
4011 {
4012         expression_t *left            = expression->left;
4013         expression_t *right           = expression->right;
4014         type_t       *orig_type_left  = left->base.datatype;
4015         type_t       *orig_type_right = right->base.datatype;
4016
4017         if(orig_type_left == NULL || orig_type_right == NULL)
4018                 return;
4019
4020         type_t *type_left  = skip_typeref(orig_type_left);
4021         type_t *type_right = skip_typeref(orig_type_right);
4022
4023         /* TODO non-arithmetic types */
4024         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4025                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4026                 expression->left  = create_implicit_cast(left, arithmetic_type);
4027                 expression->right = create_implicit_cast(right, arithmetic_type);
4028                 expression->expression.datatype = arithmetic_type;
4029         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4030                 /* TODO check compatibility */
4031         } else if (is_type_pointer(type_left)) {
4032                 expression->right = create_implicit_cast(right, type_left);
4033         } else if (is_type_pointer(type_right)) {
4034                 expression->left = create_implicit_cast(left, type_right);
4035         } else {
4036                 type_error_incompatible("invalid operands in comparison",
4037                                         token.source_position, type_left, type_right);
4038         }
4039         expression->expression.datatype = type_int;
4040 }
4041
4042 static void semantic_arithmetic_assign(binary_expression_t *expression)
4043 {
4044         expression_t *left            = expression->left;
4045         expression_t *right           = expression->right;
4046         type_t       *orig_type_left  = left->base.datatype;
4047         type_t       *orig_type_right = right->base.datatype;
4048
4049         if(orig_type_left == NULL || orig_type_right == NULL)
4050                 return;
4051
4052         type_t *type_left  = skip_typeref(orig_type_left);
4053         type_t *type_right = skip_typeref(orig_type_right);
4054
4055         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4056                 /* TODO: improve error message */
4057                 parser_print_error_prefix();
4058                 fprintf(stderr, "operation needs arithmetic types\n");
4059                 return;
4060         }
4061
4062         /* combined instructions are tricky. We can't create an implicit cast on
4063          * the left side, because we need the uncasted form for the store.
4064          * The ast2firm pass has to know that left_type must be right_type
4065          * for the arithmeitc operation and create a cast by itself */
4066         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4067         expression->right       = create_implicit_cast(right, arithmetic_type);
4068         expression->expression.datatype = type_left;
4069 }
4070
4071 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4072 {
4073         expression_t *left            = expression->left;
4074         expression_t *right           = expression->right;
4075         type_t       *orig_type_left  = left->base.datatype;
4076         type_t       *orig_type_right = right->base.datatype;
4077
4078         if(orig_type_left == NULL || orig_type_right == NULL)
4079                 return;
4080
4081         type_t *type_left  = skip_typeref(orig_type_left);
4082         type_t *type_right = skip_typeref(orig_type_right);
4083
4084         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4085                 /* combined instructions are tricky. We can't create an implicit cast on
4086                  * the left side, because we need the uncasted form for the store.
4087                  * The ast2firm pass has to know that left_type must be right_type
4088                  * for the arithmeitc operation and create a cast by itself */
4089                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4090                 expression->right = create_implicit_cast(right, arithmetic_type);
4091                 expression->expression.datatype = type_left;
4092         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4093                 expression->expression.datatype = type_left;
4094         } else {
4095                 parser_print_error_prefix();
4096                 fputs("Incompatible types ", stderr);
4097                 print_type_quoted(orig_type_left);
4098                 fputs(" and ", stderr);
4099                 print_type_quoted(orig_type_right);
4100                 fputs(" in assignment\n", stderr);
4101                 return;
4102         }
4103 }
4104
4105 static void semantic_logical_op(binary_expression_t *expression)
4106 {
4107         expression_t *left            = expression->left;
4108         expression_t *right           = expression->right;
4109         type_t       *orig_type_left  = left->base.datatype;
4110         type_t       *orig_type_right = right->base.datatype;
4111
4112         if(orig_type_left == NULL || orig_type_right == NULL)
4113                 return;
4114
4115         type_t *type_left  = skip_typeref(orig_type_left);
4116         type_t *type_right = skip_typeref(orig_type_right);
4117
4118         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4119                 /* TODO: improve error message */
4120                 parser_print_error_prefix();
4121                 fprintf(stderr, "operation needs scalar types\n");
4122                 return;
4123         }
4124
4125         expression->expression.datatype = type_int;
4126 }
4127
4128 static bool has_const_fields(type_t *type)
4129 {
4130         (void) type;
4131         /* TODO */
4132         return false;
4133 }
4134
4135 static void semantic_binexpr_assign(binary_expression_t *expression)
4136 {
4137         expression_t *left           = expression->left;
4138         type_t       *orig_type_left = left->base.datatype;
4139
4140         if(orig_type_left == NULL)
4141                 return;
4142
4143         type_t *type_left = revert_automatic_type_conversion(left);
4144         type_left         = skip_typeref(orig_type_left);
4145
4146         /* must be a modifiable lvalue */
4147         if (is_type_array(type_left)) {
4148                 parser_print_error_prefix();
4149                 fprintf(stderr, "Cannot assign to arrays ('");
4150                 print_expression(left);
4151                 fprintf(stderr, "')\n");
4152                 return;
4153         }
4154         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4155                 parser_print_error_prefix();
4156                 fprintf(stderr, "assignment to readonly location '");
4157                 print_expression(left);
4158                 fprintf(stderr, "' (type ");
4159                 print_type_quoted(orig_type_left);
4160                 fprintf(stderr, ")\n");
4161                 return;
4162         }
4163         if(is_type_incomplete(type_left)) {
4164                 parser_print_error_prefix();
4165                 fprintf(stderr, "left-hand side of assignment '");
4166                 print_expression(left);
4167                 fprintf(stderr, "' has incomplete type ");
4168                 print_type_quoted(orig_type_left);
4169                 fprintf(stderr, "\n");
4170                 return;
4171         }
4172         if(is_type_compound(type_left) && has_const_fields(type_left)) {
4173                 parser_print_error_prefix();
4174                 fprintf(stderr, "can't assign to '");
4175                 print_expression(left);
4176                 fprintf(stderr, "' because compound type ");
4177                 print_type_quoted(orig_type_left);
4178                 fprintf(stderr, " has readonly fields\n");
4179                 return;
4180         }
4181
4182         semantic_assign(orig_type_left, &expression->right, "assignment");
4183
4184         expression->expression.datatype = orig_type_left;
4185 }
4186
4187 static void semantic_comma(binary_expression_t *expression)
4188 {
4189         expression->expression.datatype = expression->right->base.datatype;
4190 }
4191
4192 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
4193 static expression_t *parse_##binexpression_type(unsigned precedence,     \
4194                                                 expression_t *left)      \
4195 {                                                                        \
4196         eat(token_type);                                                     \
4197                                                                          \
4198         expression_t *right = parse_sub_expression(precedence + lr);         \
4199                                                                          \
4200         binary_expression_t *binexpr                                         \
4201                 = allocate_ast_zero(sizeof(binexpr[0]));                         \
4202         binexpr->expression.type     = EXPR_BINARY;                          \
4203         binexpr->type                = binexpression_type;                   \
4204         binexpr->left                = left;                                 \
4205         binexpr->right               = right;                                \
4206         sfunc(binexpr);                                                      \
4207                                                                          \
4208         return (expression_t*) binexpr;                                      \
4209 }
4210
4211 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA,          semantic_comma, 1)
4212 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL,            semantic_binexpr_arithmetic, 1)
4213 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV,            semantic_binexpr_arithmetic, 1)
4214 CREATE_BINEXPR_PARSER('%', BINEXPR_MOD,            semantic_binexpr_arithmetic, 1)
4215 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD,            semantic_add, 1)
4216 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB,            semantic_sub, 1)
4217 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS,           semantic_comparison, 1)
4218 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER,        semantic_comparison, 1)
4219 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN,         semantic_binexpr_assign, 0)
4220 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL, semantic_comparison, 1)
4221 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL,
4222                       semantic_comparison, 1)
4223 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL, semantic_comparison, 1)
4224 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL,
4225                       semantic_comparison, 1)
4226 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND,    semantic_binexpr_arithmetic, 1)
4227 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR,     semantic_binexpr_arithmetic, 1)
4228 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR,    semantic_binexpr_arithmetic, 1)
4229 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND,  semantic_logical_op, 1)
4230 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR, semantic_logical_op, 1)
4231 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT,
4232                       semantic_shift_op, 1)
4233 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT,
4234                       semantic_shift_op, 1)
4235 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN,
4236                       semantic_arithmetic_addsubb_assign, 0)
4237 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN,
4238                       semantic_arithmetic_addsubb_assign, 0)
4239 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN,
4240                       semantic_arithmetic_assign, 0)
4241 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN,
4242                       semantic_arithmetic_assign, 0)
4243 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN,
4244                       semantic_arithmetic_assign, 0)
4245 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN,
4246                       semantic_arithmetic_assign, 0)
4247 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN,
4248                       semantic_arithmetic_assign, 0)
4249 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN,
4250                       semantic_arithmetic_assign, 0)
4251 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN,
4252                       semantic_arithmetic_assign, 0)
4253 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN,
4254                       semantic_arithmetic_assign, 0)
4255
4256 static expression_t *parse_sub_expression(unsigned precedence)
4257 {
4258         if(token.type < 0) {
4259                 return expected_expression_error();
4260         }
4261
4262         expression_parser_function_t *parser
4263                 = &expression_parsers[token.type];
4264         source_position_t             source_position = token.source_position;
4265         expression_t                 *left;
4266
4267         if(parser->parser != NULL) {
4268                 left = parser->parser(parser->precedence);
4269         } else {
4270                 left = parse_primary_expression();
4271         }
4272         assert(left != NULL);
4273         left->base.source_position = source_position;
4274
4275         while(true) {
4276                 if(token.type < 0) {
4277                         return expected_expression_error();
4278                 }
4279
4280                 parser = &expression_parsers[token.type];
4281                 if(parser->infix_parser == NULL)
4282                         break;
4283                 if(parser->infix_precedence < precedence)
4284                         break;
4285
4286                 left = parser->infix_parser(parser->infix_precedence, left);
4287
4288                 assert(left != NULL);
4289                 assert(left->type != EXPR_UNKNOWN);
4290                 left->base.source_position = source_position;
4291         }
4292
4293         return left;
4294 }
4295
4296 static expression_t *parse_expression(void)
4297 {
4298         return parse_sub_expression(1);
4299 }
4300
4301
4302
4303 static void register_expression_parser(parse_expression_function parser,
4304                                        int token_type, unsigned precedence)
4305 {
4306         expression_parser_function_t *entry = &expression_parsers[token_type];
4307
4308         if(entry->parser != NULL) {
4309                 fprintf(stderr, "for token ");
4310                 print_token_type(stderr, (token_type_t) token_type);
4311                 fprintf(stderr, "\n");
4312                 panic("trying to register multiple expression parsers for a token");
4313         }
4314         entry->parser     = parser;
4315         entry->precedence = precedence;
4316 }
4317
4318 static void register_expression_infix_parser(
4319                 parse_expression_infix_function parser, int token_type,
4320                 unsigned precedence)
4321 {
4322         expression_parser_function_t *entry = &expression_parsers[token_type];
4323
4324         if(entry->infix_parser != NULL) {
4325                 fprintf(stderr, "for token ");
4326                 print_token_type(stderr, (token_type_t) token_type);
4327                 fprintf(stderr, "\n");
4328                 panic("trying to register multiple infix expression parsers for a "
4329                       "token");
4330         }
4331         entry->infix_parser     = parser;
4332         entry->infix_precedence = precedence;
4333 }
4334
4335 static void init_expression_parsers(void)
4336 {
4337         memset(&expression_parsers, 0, sizeof(expression_parsers));
4338
4339         register_expression_infix_parser(parse_BINEXPR_MUL,         '*',        16);
4340         register_expression_infix_parser(parse_BINEXPR_DIV,         '/',        16);
4341         register_expression_infix_parser(parse_BINEXPR_MOD,         '%',        16);
4342         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,   T_LESSLESS, 16);
4343         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
4344                                                               T_GREATERGREATER, 16);
4345         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
4346         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
4347         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
4348         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
4349         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
4350         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
4351                                                                 T_GREATEREQUAL, 14);
4352         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
4353         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
4354                                                         T_EXCLAMATIONMARKEQUAL, 13);
4355         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
4356         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
4357         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
4358         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
4359         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
4360         register_expression_infix_parser(parse_conditional_expression, '?',      7);
4361         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
4362         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
4363         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
4364         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
4365                                                                 T_ASTERISKEQUAL, 2);
4366         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
4367         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
4368                                                                  T_PERCENTEQUAL, 2);
4369         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
4370                                                                 T_LESSLESSEQUAL, 2);
4371         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
4372                                                           T_GREATERGREATEREQUAL, 2);
4373         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
4374                                                                      T_ANDEQUAL, 2);
4375         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
4376                                                                     T_PIPEEQUAL, 2);
4377         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
4378                                                                    T_CARETEQUAL, 2);
4379
4380         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
4381
4382         register_expression_infix_parser(parse_array_expression,        '[',    30);
4383         register_expression_infix_parser(parse_call_expression,         '(',    30);
4384         register_expression_infix_parser(parse_select_expression,       '.',    30);
4385         register_expression_infix_parser(parse_select_expression,
4386                                                                 T_MINUSGREATER, 30);
4387         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
4388                                          T_PLUSPLUS, 30);
4389         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
4390                                          T_MINUSMINUS, 30);
4391
4392         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
4393         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
4394         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
4395         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
4396         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
4397         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
4398         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
4399         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
4400         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4401         register_expression_parser(parse_extension,            T___extension__, 25);
4402         register_expression_parser(parse_builtin_classify_type,
4403                                                      T___builtin_classify_type, 25);
4404 }
4405
4406 static asm_constraint_t *parse_asm_constraints(void)
4407 {
4408         asm_constraint_t *result = NULL;
4409         asm_constraint_t *last   = NULL;
4410
4411         while(token.type == T_STRING_LITERAL || token.type == '[') {
4412                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4413                 memset(constraint, 0, sizeof(constraint[0]));
4414
4415                 if(token.type == '[') {
4416                         eat('[');
4417                         if(token.type != T_IDENTIFIER) {
4418                                 parse_error_expected("while parsing asm constraint",
4419                                                      T_IDENTIFIER, 0);
4420                                 return NULL;
4421                         }
4422                         constraint->symbol = token.v.symbol;
4423
4424                         expect(']');
4425                 }
4426
4427                 constraint->constraints = parse_string_literals();
4428                 expect('(');
4429                 constraint->expression = parse_expression();
4430                 expect(')');
4431
4432                 if(last != NULL) {
4433                         last->next = constraint;
4434                 } else {
4435                         result = constraint;
4436                 }
4437                 last = constraint;
4438
4439                 if(token.type != ',')
4440                         break;
4441                 eat(',');
4442         }
4443
4444         return result;
4445 }
4446
4447 static asm_clobber_t *parse_asm_clobbers(void)
4448 {
4449         asm_clobber_t *result = NULL;
4450         asm_clobber_t *last   = NULL;
4451
4452         while(token.type == T_STRING_LITERAL) {
4453                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4454                 clobber->clobber       = parse_string_literals();
4455
4456                 if(last != NULL) {
4457                         last->next = clobber;
4458                 } else {
4459                         result = clobber;
4460                 }
4461                 last = clobber;
4462
4463                 if(token.type != ',')
4464                         break;
4465                 eat(',');
4466         }
4467
4468         return result;
4469 }
4470
4471 static statement_t *parse_asm_statement(void)
4472 {
4473         eat(T_asm);
4474
4475         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4476         statement->base.source_position = token.source_position;
4477
4478         asm_statement_t *asm_statement = &statement->asms;
4479
4480         if(token.type == T_volatile) {
4481                 next_token();
4482                 asm_statement->is_volatile = true;
4483         }
4484
4485         expect('(');
4486         asm_statement->asm_text = parse_string_literals();
4487
4488         if(token.type != ':')
4489                 goto end_of_asm;
4490         eat(':');
4491
4492         asm_statement->inputs = parse_asm_constraints();
4493         if(token.type != ':')
4494                 goto end_of_asm;
4495         eat(':');
4496
4497         asm_statement->outputs = parse_asm_constraints();
4498         if(token.type != ':')
4499                 goto end_of_asm;
4500         eat(':');
4501
4502         asm_statement->clobbers = parse_asm_clobbers();
4503
4504 end_of_asm:
4505         expect(')');
4506         expect(';');
4507         return statement;
4508 }
4509
4510 static statement_t *parse_case_statement(void)
4511 {
4512         eat(T_case);
4513
4514         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4515
4516         statement->base.source_position  = token.source_position;
4517         statement->case_label.expression = parse_expression();
4518
4519         expect(':');
4520         statement->case_label.label_statement = parse_statement();
4521
4522         return statement;
4523 }
4524
4525 static statement_t *parse_default_statement(void)
4526 {
4527         eat(T_default);
4528
4529         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4530
4531         statement->base.source_position = token.source_position;
4532
4533         expect(':');
4534         statement->label.label_statement = parse_statement();
4535
4536         return statement;
4537 }
4538
4539 static declaration_t *get_label(symbol_t *symbol)
4540 {
4541         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4542         assert(current_function != NULL);
4543         /* if we found a label in the same function, then we already created the
4544          * declaration */
4545         if(candidate != NULL
4546                         && candidate->parent_context == &current_function->context) {
4547                 return candidate;
4548         }
4549
4550         /* otherwise we need to create a new one */
4551         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4552         declaration->namespc       = NAMESPACE_LABEL;
4553         declaration->symbol        = symbol;
4554
4555         label_push(declaration);
4556
4557         return declaration;
4558 }
4559
4560 static statement_t *parse_label_statement(void)
4561 {
4562         assert(token.type == T_IDENTIFIER);
4563         symbol_t *symbol = token.v.symbol;
4564         next_token();
4565
4566         declaration_t *label = get_label(symbol);
4567
4568         /* if source position is already set then the label is defined twice,
4569          * otherwise it was just mentioned in a goto so far */
4570         if(label->source_position.input_name != NULL) {
4571                 parser_print_error_prefix();
4572                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
4573                 parser_print_error_prefix_pos(label->source_position);
4574                 fprintf(stderr, "previous definition of '%s' was here\n",
4575                         symbol->string);
4576         } else {
4577                 label->source_position = token.source_position;
4578         }
4579
4580         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4581
4582         label_statement->statement.type            = STATEMENT_LABEL;
4583         label_statement->statement.source_position = token.source_position;
4584         label_statement->label                     = label;
4585
4586         expect(':');
4587
4588         if(token.type == '}') {
4589                 parse_error("label at end of compound statement");
4590                 return (statement_t*) label_statement;
4591         } else {
4592                 label_statement->label_statement = parse_statement();
4593         }
4594
4595         return (statement_t*) label_statement;
4596 }
4597
4598 static statement_t *parse_if(void)
4599 {
4600         eat(T_if);
4601
4602         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4603         statement->statement.type            = STATEMENT_IF;
4604         statement->statement.source_position = token.source_position;
4605
4606         expect('(');
4607         statement->condition = parse_expression();
4608         expect(')');
4609
4610         statement->true_statement = parse_statement();
4611         if(token.type == T_else) {
4612                 next_token();
4613                 statement->false_statement = parse_statement();
4614         }
4615
4616         return (statement_t*) statement;
4617 }
4618
4619 static statement_t *parse_switch(void)
4620 {
4621         eat(T_switch);
4622
4623         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4624         statement->statement.type            = STATEMENT_SWITCH;
4625         statement->statement.source_position = token.source_position;
4626
4627         expect('(');
4628         statement->expression = parse_expression();
4629         expect(')');
4630         statement->body = parse_statement();
4631
4632         return (statement_t*) statement;
4633 }
4634
4635 static statement_t *parse_while(void)
4636 {
4637         eat(T_while);
4638
4639         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4640         statement->statement.type            = STATEMENT_WHILE;
4641         statement->statement.source_position = token.source_position;
4642
4643         expect('(');
4644         statement->condition = parse_expression();
4645         expect(')');
4646         statement->body = parse_statement();
4647
4648         return (statement_t*) statement;
4649 }
4650
4651 static statement_t *parse_do(void)
4652 {
4653         eat(T_do);
4654
4655         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4656         statement->statement.type            = STATEMENT_DO_WHILE;
4657         statement->statement.source_position = token.source_position;
4658
4659         statement->body = parse_statement();
4660         expect(T_while);
4661         expect('(');
4662         statement->condition = parse_expression();
4663         expect(')');
4664         expect(';');
4665
4666         return (statement_t*) statement;
4667 }
4668
4669 static statement_t *parse_for(void)
4670 {
4671         eat(T_for);
4672
4673         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4674         statement->statement.type            = STATEMENT_FOR;
4675         statement->statement.source_position = token.source_position;
4676
4677         expect('(');
4678
4679         int         top          = environment_top();
4680         context_t  *last_context = context;
4681         set_context(&statement->context);
4682
4683         if(token.type != ';') {
4684                 if(is_declaration_specifier(&token, false)) {
4685                         parse_declaration(record_declaration);
4686                 } else {
4687                         statement->initialisation = parse_expression();
4688                         expect(';');
4689                 }
4690         } else {
4691                 expect(';');
4692         }
4693
4694         if(token.type != ';') {
4695                 statement->condition = parse_expression();
4696         }
4697         expect(';');
4698         if(token.type != ')') {
4699                 statement->step = parse_expression();
4700         }
4701         expect(')');
4702         statement->body = parse_statement();
4703
4704         assert(context == &statement->context);
4705         set_context(last_context);
4706         environment_pop_to(top);
4707
4708         return (statement_t*) statement;
4709 }
4710
4711 static statement_t *parse_goto(void)
4712 {
4713         eat(T_goto);
4714
4715         if(token.type != T_IDENTIFIER) {
4716                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4717                 eat_statement();
4718                 return NULL;
4719         }
4720         symbol_t *symbol = token.v.symbol;
4721         next_token();
4722
4723         declaration_t *label = get_label(symbol);
4724
4725         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4726
4727         statement->statement.type            = STATEMENT_GOTO;
4728         statement->statement.source_position = token.source_position;
4729
4730         statement->label = label;
4731
4732         expect(';');
4733
4734         return (statement_t*) statement;
4735 }
4736
4737 static statement_t *parse_continue(void)
4738 {
4739         eat(T_continue);
4740         expect(';');
4741
4742         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4743         statement->type                 = STATEMENT_CONTINUE;
4744         statement->base.source_position = token.source_position;
4745
4746         return statement;
4747 }
4748
4749 static statement_t *parse_break(void)
4750 {
4751         eat(T_break);
4752         expect(';');
4753
4754         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4755         statement->type                 = STATEMENT_BREAK;
4756         statement->base.source_position = token.source_position;
4757
4758         return statement;
4759 }
4760
4761 static statement_t *parse_return(void)
4762 {
4763         eat(T_return);
4764
4765         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4766
4767         statement->statement.type            = STATEMENT_RETURN;
4768         statement->statement.source_position = token.source_position;
4769
4770         assert(is_type_function(current_function->type));
4771         function_type_t *function_type = &current_function->type->function;
4772         type_t          *return_type   = function_type->return_type;
4773
4774         expression_t *return_value = NULL;
4775         if(token.type != ';') {
4776                 return_value = parse_expression();
4777         }
4778         expect(';');
4779
4780         if(return_type == NULL)
4781                 return (statement_t*) statement;
4782
4783         return_type = skip_typeref(return_type);
4784
4785         if(return_value != NULL) {
4786                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
4787
4788                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
4789                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
4790                         parse_warning("'return' with a value, in function returning void");
4791                         return_value = NULL;
4792                 } else {
4793                         if(return_type != NULL) {
4794                                 semantic_assign(return_type, &return_value, "'return'");
4795                         }
4796                 }
4797         } else {
4798                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
4799                         parse_warning("'return' without value, in function returning "
4800                                       "non-void");
4801                 }
4802         }
4803         statement->return_value = return_value;
4804
4805         return (statement_t*) statement;
4806 }
4807
4808 static statement_t *parse_declaration_statement(void)
4809 {
4810         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
4811
4812         statement->base.source_position = token.source_position;
4813
4814         declaration_t *before = last_declaration;
4815         parse_declaration(record_declaration);
4816
4817         if(before == NULL) {
4818                 statement->declaration.declarations_begin = context->declarations;
4819         } else {
4820                 statement->declaration.declarations_begin = before->next;
4821         }
4822         statement->declaration.declarations_end = last_declaration;
4823
4824         return statement;
4825 }
4826
4827 static statement_t *parse_expression_statement(void)
4828 {
4829         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
4830
4831         statement->base.source_position  = token.source_position;
4832         statement->expression.expression = parse_expression();
4833
4834         expect(';');
4835
4836         return statement;
4837 }
4838
4839 static statement_t *parse_statement(void)
4840 {
4841         statement_t   *statement = NULL;
4842
4843         /* declaration or statement */
4844         switch(token.type) {
4845         case T_asm:
4846                 statement = parse_asm_statement();
4847                 break;
4848
4849         case T_case:
4850                 statement = parse_case_statement();
4851                 break;
4852
4853         case T_default:
4854                 statement = parse_default_statement();
4855                 break;
4856
4857         case '{':
4858                 statement = parse_compound_statement();
4859                 break;
4860
4861         case T_if:
4862                 statement = parse_if();
4863                 break;
4864
4865         case T_switch:
4866                 statement = parse_switch();
4867                 break;
4868
4869         case T_while:
4870                 statement = parse_while();
4871                 break;
4872
4873         case T_do:
4874                 statement = parse_do();
4875                 break;
4876
4877         case T_for:
4878                 statement = parse_for();
4879                 break;
4880
4881         case T_goto:
4882                 statement = parse_goto();
4883                 break;
4884
4885         case T_continue:
4886                 statement = parse_continue();
4887                 break;
4888
4889         case T_break:
4890                 statement = parse_break();
4891                 break;
4892
4893         case T_return:
4894                 statement = parse_return();
4895                 break;
4896
4897         case ';':
4898                 next_token();
4899                 statement = NULL;
4900                 break;
4901
4902         case T_IDENTIFIER:
4903                 if(look_ahead(1)->type == ':') {
4904                         statement = parse_label_statement();
4905                         break;
4906                 }
4907
4908                 if(is_typedef_symbol(token.v.symbol)) {
4909                         statement = parse_declaration_statement();
4910                         break;
4911                 }
4912
4913                 statement = parse_expression_statement();
4914                 break;
4915
4916         case T___extension__:
4917                 /* this can be a prefix to a declaration or an expression statement */
4918                 /* we simply eat it now and parse the rest with tail recursion */
4919                 do {
4920                         next_token();
4921                 } while(token.type == T___extension__);
4922                 statement = parse_statement();
4923                 break;
4924
4925         DECLARATION_START
4926                 statement = parse_declaration_statement();
4927                 break;
4928
4929         default:
4930                 statement = parse_expression_statement();
4931                 break;
4932         }
4933
4934         assert(statement == NULL
4935                         || statement->base.source_position.input_name != NULL);
4936
4937         return statement;
4938 }
4939
4940 static statement_t *parse_compound_statement(void)
4941 {
4942         compound_statement_t *compound_statement
4943                 = allocate_ast_zero(sizeof(compound_statement[0]));
4944         compound_statement->statement.type            = STATEMENT_COMPOUND;
4945         compound_statement->statement.source_position = token.source_position;
4946
4947         eat('{');
4948
4949         int        top          = environment_top();
4950         context_t *last_context = context;
4951         set_context(&compound_statement->context);
4952
4953         statement_t *last_statement = NULL;
4954
4955         while(token.type != '}' && token.type != T_EOF) {
4956                 statement_t *statement = parse_statement();
4957                 if(statement == NULL)
4958                         continue;
4959
4960                 if(last_statement != NULL) {
4961                         last_statement->base.next = statement;
4962                 } else {
4963                         compound_statement->statements = statement;
4964                 }
4965
4966                 while(statement->base.next != NULL)
4967                         statement = statement->base.next;
4968
4969                 last_statement = statement;
4970         }
4971
4972         if(token.type != '}') {
4973                 parser_print_error_prefix_pos(
4974                                 compound_statement->statement.source_position);
4975                 fprintf(stderr, "end of file while looking for closing '}'\n");
4976         }
4977         next_token();
4978
4979         assert(context == &compound_statement->context);
4980         set_context(last_context);
4981         environment_pop_to(top);
4982
4983         return (statement_t*) compound_statement;
4984 }
4985
4986 static void initialize_builtins(void)
4987 {
4988         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__", type_int);
4989         type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
4990         type_size_t      = make_global_typedef("__SIZE_TYPE__",
4991                         make_atomic_type(ATOMIC_TYPE_ULONG, TYPE_QUALIFIER_NONE));
4992         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",
4993                         make_atomic_type(ATOMIC_TYPE_LONG, TYPE_QUALIFIER_NONE));
4994 }
4995
4996 static translation_unit_t *parse_translation_unit(void)
4997 {
4998         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
4999
5000         assert(global_context == NULL);
5001         global_context = &unit->context;
5002
5003         assert(context == NULL);
5004         set_context(&unit->context);
5005
5006         initialize_builtins();
5007
5008         while(token.type != T_EOF) {
5009                 parse_external_declaration();
5010         }
5011
5012         assert(context == &unit->context);
5013         context          = NULL;
5014         last_declaration = NULL;
5015
5016         assert(global_context == &unit->context);
5017         global_context = NULL;
5018
5019         return unit;
5020 }
5021
5022 translation_unit_t *parse(void)
5023 {
5024         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5025         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5026         found_error       = false;
5027
5028         type_set_output(stderr);
5029         ast_set_output(stderr);
5030
5031         lookahead_bufpos = 0;
5032         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5033                 next_token();
5034         }
5035         translation_unit_t *unit = parse_translation_unit();
5036
5037         DEL_ARR_F(environment_stack);
5038         DEL_ARR_F(label_stack);
5039
5040         if(found_error)
5041                 return NULL;
5042
5043         return unit;
5044 }
5045
5046 void init_parser(void)
5047 {
5048         init_expression_parsers();
5049         obstack_init(&temp_obst);
5050
5051         type_int         = make_atomic_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
5052         type_long_double = make_atomic_type(ATOMIC_TYPE_LONG_DOUBLE,
5053                                             TYPE_QUALIFIER_NONE);
5054         type_double      = make_atomic_type(ATOMIC_TYPE_DOUBLE,
5055                                             TYPE_QUALIFIER_NONE);
5056         type_float       = make_atomic_type(ATOMIC_TYPE_FLOAT, TYPE_QUALIFIER_NONE);
5057         type_char        = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_NONE);
5058         type_void        = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
5059         type_void_ptr    = make_pointer_type(type_void, TYPE_QUALIFIER_NONE);
5060         type_string      = make_pointer_type(type_char, TYPE_QUALIFIER_NONE);
5061 }
5062
5063 void exit_parser(void)
5064 {
5065         obstack_free(&temp_obst, NULL);
5066 }