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