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