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