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