removed set_opt_overflow_unsafe_transform(), not needed anymore
[cparser] / parser.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdbool.h>
25
26 #include "parser.h"
27 #include "diagnostic.h"
28 #include "format_check.h"
29 #include "lexer.h"
30 #include "symbol_t.h"
31 #include "token_t.h"
32 #include "types.h"
33 #include "type_t.h"
34 #include "type_hash.h"
35 #include "ast_t.h"
36 #include "lang_features.h"
37 #include "warning.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
41
42 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
44
45 typedef struct {
46         declaration_t *old_declaration;
47         symbol_t      *symbol;
48         unsigned short namespc;
49 } stack_entry_t;
50
51 typedef struct declaration_specifiers_t  declaration_specifiers_t;
52 struct declaration_specifiers_t {
53         source_position_t  source_position;
54         unsigned char      declared_storage_class;
55         bool               is_inline;
56         decl_modifiers_t   decl_modifiers;
57         type_t            *type;
58 };
59
60 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
61
62 static token_t             token;
63 static token_t             lookahead_buffer[MAX_LOOKAHEAD];
64 static int                 lookahead_bufpos;
65 static stack_entry_t      *environment_stack = NULL;
66 static stack_entry_t      *label_stack       = NULL;
67 static scope_t            *global_scope      = NULL;
68 static scope_t            *scope             = NULL;
69 static declaration_t      *last_declaration  = NULL;
70 static declaration_t      *current_function  = NULL;
71 static switch_statement_t *current_switch    = NULL;
72 static statement_t        *current_loop      = NULL;
73 static goto_statement_t   *goto_first        = NULL;
74 static goto_statement_t   *goto_last         = NULL;
75 static label_statement_t  *label_first       = NULL;
76 static label_statement_t  *label_last        = NULL;
77 static struct obstack      temp_obst;
78
79 /** The current source position. */
80 #define HERE token.source_position
81
82 static type_t *type_valist;
83
84 static statement_t *parse_compound_statement(void);
85 static statement_t *parse_statement(void);
86
87 static expression_t *parse_sub_expression(unsigned precedence);
88 static expression_t *parse_expression(void);
89 static type_t       *parse_typename(void);
90
91 static void parse_compound_type_entries(declaration_t *compound_declaration);
92 static declaration_t *parse_declarator(
93                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
94 static declaration_t *record_declaration(declaration_t *declaration);
95
96 static void semantic_comparison(binary_expression_t *expression);
97
98 #define STORAGE_CLASSES     \
99         case T_typedef:         \
100         case T_extern:          \
101         case T_static:          \
102         case T_auto:            \
103         case T_register:
104
105 #define TYPE_QUALIFIERS     \
106         case T_const:           \
107         case T_restrict:        \
108         case T_volatile:        \
109         case T_inline:          \
110         case T_forceinline:
111
112 #ifdef PROVIDE_COMPLEX
113 #define COMPLEX_SPECIFIERS  \
114         case T__Complex:
115 #define IMAGINARY_SPECIFIERS \
116         case T__Imaginary:
117 #else
118 #define COMPLEX_SPECIFIERS
119 #define IMAGINARY_SPECIFIERS
120 #endif
121
122 #define TYPE_SPECIFIERS       \
123         case T_void:              \
124         case T_char:              \
125         case T_short:             \
126         case T_int:               \
127         case T_long:              \
128         case T_float:             \
129         case T_double:            \
130         case T_signed:            \
131         case T_unsigned:          \
132         case T__Bool:             \
133         case T_struct:            \
134         case T_union:             \
135         case T_enum:              \
136         case T___typeof__:        \
137         case T___builtin_va_list: \
138         COMPLEX_SPECIFIERS        \
139         IMAGINARY_SPECIFIERS
140
141 #define DECLARATION_START   \
142         STORAGE_CLASSES         \
143         TYPE_QUALIFIERS         \
144         TYPE_SPECIFIERS
145
146 #define TYPENAME_START      \
147         TYPE_QUALIFIERS         \
148         TYPE_SPECIFIERS
149
150 /**
151  * Allocate an AST node with given size and
152  * initialize all fields with zero.
153  */
154 static void *allocate_ast_zero(size_t size)
155 {
156         void *res = allocate_ast(size);
157         memset(res, 0, size);
158         return res;
159 }
160
161 static declaration_t *allocate_declaration_zero(void)
162 {
163         declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
164         declaration->type = type_error_type;
165         return declaration;
166 }
167
168 /**
169  * Returns the size of a statement node.
170  *
171  * @param kind  the statement kind
172  */
173 static size_t get_statement_struct_size(statement_kind_t kind)
174 {
175         static const size_t sizes[] = {
176                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
177                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
178                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
179                 [STATEMENT_IF]          = sizeof(if_statement_t),
180                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
181                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
182                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
183                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
184                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
185                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
186                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
187                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
188                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
189                 [STATEMENT_FOR]         = sizeof(for_statement_t),
190                 [STATEMENT_ASM]         = sizeof(asm_statement_t)
191         };
192         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
193         assert(sizes[kind] != 0);
194         return sizes[kind];
195 }
196
197 /**
198  * Allocate a statement node of given kind and initialize all
199  * fields with zero.
200  */
201 static statement_t *allocate_statement_zero(statement_kind_t kind)
202 {
203         size_t       size = get_statement_struct_size(kind);
204         statement_t *res  = allocate_ast_zero(size);
205
206         res->base.kind = kind;
207         return res;
208 }
209
210 /**
211  * Returns the size of an expression node.
212  *
213  * @param kind  the expression kind
214  */
215 static size_t get_expression_struct_size(expression_kind_t kind)
216 {
217         static const size_t sizes[] = {
218                 [EXPR_INVALID]                 = sizeof(expression_base_t),
219                 [EXPR_REFERENCE]               = sizeof(reference_expression_t),
220                 [EXPR_CONST]                   = sizeof(const_expression_t),
221                 [EXPR_CHARACTER_CONSTANT]      = sizeof(const_expression_t),
222                 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
223                 [EXPR_STRING_LITERAL]          = sizeof(string_literal_expression_t),
224                 [EXPR_WIDE_STRING_LITERAL]   = sizeof(wide_string_literal_expression_t),
225                 [EXPR_COMPOUND_LITERAL]        = sizeof(compound_literal_expression_t),
226                 [EXPR_CALL]                    = sizeof(call_expression_t),
227                 [EXPR_UNARY_FIRST]             = sizeof(unary_expression_t),
228                 [EXPR_BINARY_FIRST]            = sizeof(binary_expression_t),
229                 [EXPR_CONDITIONAL]             = sizeof(conditional_expression_t),
230                 [EXPR_SELECT]                  = sizeof(select_expression_t),
231                 [EXPR_ARRAY_ACCESS]            = sizeof(array_access_expression_t),
232                 [EXPR_SIZEOF]                  = sizeof(typeprop_expression_t),
233                 [EXPR_ALIGNOF]                 = sizeof(typeprop_expression_t),
234                 [EXPR_CLASSIFY_TYPE]           = sizeof(classify_type_expression_t),
235                 [EXPR_FUNCTION]                = sizeof(string_literal_expression_t),
236                 [EXPR_PRETTY_FUNCTION]         = sizeof(string_literal_expression_t),
237                 [EXPR_BUILTIN_SYMBOL]          = sizeof(builtin_symbol_expression_t),
238                 [EXPR_BUILTIN_CONSTANT_P]      = sizeof(builtin_constant_expression_t),
239                 [EXPR_BUILTIN_PREFETCH]        = sizeof(builtin_prefetch_expression_t),
240                 [EXPR_OFFSETOF]                = sizeof(offsetof_expression_t),
241                 [EXPR_VA_START]                = sizeof(va_start_expression_t),
242                 [EXPR_VA_ARG]                  = sizeof(va_arg_expression_t),
243                 [EXPR_STATEMENT]               = sizeof(statement_expression_t),
244         };
245         if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
246                 return sizes[EXPR_UNARY_FIRST];
247         }
248         if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
249                 return sizes[EXPR_BINARY_FIRST];
250         }
251         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
252         assert(sizes[kind] != 0);
253         return sizes[kind];
254 }
255
256 /**
257  * Allocate an expression node of given kind and initialize all
258  * fields with zero.
259  */
260 static expression_t *allocate_expression_zero(expression_kind_t kind)
261 {
262         size_t        size = get_expression_struct_size(kind);
263         expression_t *res  = allocate_ast_zero(size);
264
265         res->base.kind = kind;
266         res->base.type = type_error_type;
267         return res;
268 }
269
270 /**
271  * Returns the size of a type node.
272  *
273  * @param kind  the type kind
274  */
275 static size_t get_type_struct_size(type_kind_t kind)
276 {
277         static const size_t sizes[] = {
278                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
279                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
280                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
281                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
282                 [TYPE_ENUM]            = sizeof(enum_type_t),
283                 [TYPE_FUNCTION]        = sizeof(function_type_t),
284                 [TYPE_POINTER]         = sizeof(pointer_type_t),
285                 [TYPE_ARRAY]           = sizeof(array_type_t),
286                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
287                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
288                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
289         };
290         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
291         assert(kind <= TYPE_TYPEOF);
292         assert(sizes[kind] != 0);
293         return sizes[kind];
294 }
295
296 /**
297  * Allocate a type node of given kind and initialize all
298  * fields with zero.
299  */
300 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
301 {
302         size_t  size = get_type_struct_size(kind);
303         type_t *res  = obstack_alloc(type_obst, size);
304         memset(res, 0, size);
305
306         res->base.kind            = kind;
307         res->base.source_position = source_position;
308         return res;
309 }
310
311 /**
312  * Returns the size of an initializer node.
313  *
314  * @param kind  the initializer kind
315  */
316 static size_t get_initializer_size(initializer_kind_t kind)
317 {
318         static const size_t sizes[] = {
319                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
320                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
321                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
322                 [INITIALIZER_LIST]        = sizeof(initializer_list_t),
323                 [INITIALIZER_DESIGNATOR]  = sizeof(initializer_designator_t)
324         };
325         assert(kind < sizeof(sizes) / sizeof(*sizes));
326         assert(sizes[kind] != 0);
327         return sizes[kind];
328 }
329
330 /**
331  * Allocate an initializer node of given kind and initialize all
332  * fields with zero.
333  */
334 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
335 {
336         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
337         result->kind          = kind;
338
339         return result;
340 }
341
342 /**
343  * Free a type from the type obstack.
344  */
345 static void free_type(void *type)
346 {
347         obstack_free(type_obst, type);
348 }
349
350 /**
351  * Returns the index of the top element of the environment stack.
352  */
353 static size_t environment_top(void)
354 {
355         return ARR_LEN(environment_stack);
356 }
357
358 /**
359  * Returns the index of the top element of the label stack.
360  */
361 static size_t label_top(void)
362 {
363         return ARR_LEN(label_stack);
364 }
365
366
367 /**
368  * Return the next token.
369  */
370 static inline void next_token(void)
371 {
372         token                              = lookahead_buffer[lookahead_bufpos];
373         lookahead_buffer[lookahead_bufpos] = lexer_token;
374         lexer_next_token();
375
376         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
377
378 #ifdef PRINT_TOKENS
379         print_token(stderr, &token);
380         fprintf(stderr, "\n");
381 #endif
382 }
383
384 /**
385  * Return the next token with a given lookahead.
386  */
387 static inline const token_t *look_ahead(int num)
388 {
389         assert(num > 0 && num <= MAX_LOOKAHEAD);
390         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
391         return &lookahead_buffer[pos];
392 }
393
394 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
395
396 /**
397  * Report a parse error because an expected token was not found.
398  */
399 static void parse_error_expected(const char *message, ...)
400 {
401         if(message != NULL) {
402                 errorf(HERE, "%s", message);
403         }
404         va_list ap;
405         va_start(ap, message);
406         errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
407         va_end(ap);
408 }
409
410 /**
411  * Report a type error.
412  */
413 static void type_error(const char *msg, const source_position_t source_position,
414                        type_t *type)
415 {
416         errorf(source_position, "%s, but found type '%T'", msg, type);
417 }
418
419 /**
420  * Report an incompatible type.
421  */
422 static void type_error_incompatible(const char *msg,
423                 const source_position_t source_position, type_t *type1, type_t *type2)
424 {
425         errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
426 }
427
428 /**
429  * Eat an complete block, ie. '{ ... }'.
430  */
431 static void eat_block(void)
432 {
433         if(token.type == '{')
434                 next_token();
435
436         while(token.type != '}') {
437                 if(token.type == T_EOF)
438                         return;
439                 if(token.type == '{') {
440                         eat_block();
441                         continue;
442                 }
443                 next_token();
444         }
445         eat('}');
446 }
447
448 /**
449  * Eat a statement until an ';' token.
450  */
451 static void eat_statement(void)
452 {
453         while(token.type != ';') {
454                 if(token.type == T_EOF)
455                         return;
456                 if(token.type == '}')
457                         return;
458                 if(token.type == '{') {
459                         eat_block();
460                         continue;
461                 }
462                 next_token();
463         }
464         eat(';');
465 }
466
467 /**
468  * Eat a parenthesed term, ie. '( ... )'.
469  */
470 static void eat_paren(void)
471 {
472         if(token.type == '(')
473                 next_token();
474
475         while(token.type != ')') {
476                 if(token.type == T_EOF)
477                         return;
478                 if(token.type == ')' || token.type == ';' || token.type == '}') {
479                         return;
480                 }
481                 if(token.type == ')') {
482                         next_token();
483                         return;
484                 }
485                 if(token.type == '(') {
486                         eat_paren();
487                         continue;
488                 }
489                 if(token.type == '{') {
490                         eat_block();
491                         continue;
492                 }
493                 next_token();
494         }
495 }
496
497 #define expect(expected)                           \
498         do {                                           \
499     if(UNLIKELY(token.type != (expected))) {       \
500         parse_error_expected(NULL, (expected), 0); \
501         eat_statement();                           \
502         return NULL;                               \
503     }                                              \
504     next_token();                                  \
505         } while(0)
506
507 #define expect_block(expected)                     \
508         do {                                           \
509     if(UNLIKELY(token.type != (expected))) {       \
510         parse_error_expected(NULL, (expected), 0); \
511         eat_block();                               \
512         return NULL;                               \
513     }                                              \
514     next_token();                                  \
515         } while(0)
516
517 #define expect_void(expected)                      \
518         do {                                           \
519     if(UNLIKELY(token.type != (expected))) {       \
520         parse_error_expected(NULL, (expected), 0); \
521         eat_statement();                           \
522         return;                                    \
523     }                                              \
524     next_token();                                  \
525     } while(0)
526
527 static void set_scope(scope_t *new_scope)
528 {
529         if(scope != NULL) {
530                 scope->last_declaration = last_declaration;
531         }
532         scope = new_scope;
533
534         last_declaration = new_scope->last_declaration;
535 }
536
537 /**
538  * Search a symbol in a given namespace and returns its declaration or
539  * NULL if this symbol was not found.
540  */
541 static declaration_t *get_declaration(const symbol_t *const symbol,
542                                       const namespace_t namespc)
543 {
544         declaration_t *declaration = symbol->declaration;
545         for( ; declaration != NULL; declaration = declaration->symbol_next) {
546                 if(declaration->namespc == namespc)
547                         return declaration;
548         }
549
550         return NULL;
551 }
552
553 /**
554  * pushs an environment_entry on the environment stack and links the
555  * corresponding symbol to the new entry
556  */
557 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
558 {
559         symbol_t    *symbol  = declaration->symbol;
560         namespace_t  namespc = (namespace_t) declaration->namespc;
561
562         /* replace/add declaration into declaration list of the symbol */
563         declaration_t *iter = symbol->declaration;
564         if (iter == NULL) {
565                 symbol->declaration = declaration;
566         } else {
567                 declaration_t *iter_last = NULL;
568                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
569                         /* replace an entry? */
570                         if(iter->namespc == namespc) {
571                                 if(iter_last == NULL) {
572                                         symbol->declaration = declaration;
573                                 } else {
574                                         iter_last->symbol_next = declaration;
575                                 }
576                                 declaration->symbol_next = iter->symbol_next;
577                                 break;
578                         }
579                 }
580                 if(iter == NULL) {
581                         assert(iter_last->symbol_next == NULL);
582                         iter_last->symbol_next = declaration;
583                 }
584         }
585
586         /* remember old declaration */
587         stack_entry_t entry;
588         entry.symbol          = symbol;
589         entry.old_declaration = iter;
590         entry.namespc         = (unsigned short) namespc;
591         ARR_APP1(stack_entry_t, *stack_ptr, entry);
592 }
593
594 static void environment_push(declaration_t *declaration)
595 {
596         assert(declaration->source_position.input_name != NULL);
597         assert(declaration->parent_scope != NULL);
598         stack_push(&environment_stack, declaration);
599 }
600
601 static void label_push(declaration_t *declaration)
602 {
603         declaration->parent_scope = &current_function->scope;
604         stack_push(&label_stack, declaration);
605 }
606
607 /**
608  * pops symbols from the environment stack until @p new_top is the top element
609  */
610 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
611 {
612         stack_entry_t *stack = *stack_ptr;
613         size_t         top   = ARR_LEN(stack);
614         size_t         i;
615
616         assert(new_top <= top);
617         if(new_top == top)
618                 return;
619
620         for(i = top; i > new_top; --i) {
621                 stack_entry_t *entry = &stack[i - 1];
622
623                 declaration_t *old_declaration = entry->old_declaration;
624                 symbol_t      *symbol          = entry->symbol;
625                 namespace_t    namespc         = (namespace_t)entry->namespc;
626
627                 /* replace/remove declaration */
628                 declaration_t *declaration = symbol->declaration;
629                 assert(declaration != NULL);
630                 if(declaration->namespc == namespc) {
631                         if(old_declaration == NULL) {
632                                 symbol->declaration = declaration->symbol_next;
633                         } else {
634                                 symbol->declaration = old_declaration;
635                         }
636                 } else {
637                         declaration_t *iter_last = declaration;
638                         declaration_t *iter      = declaration->symbol_next;
639                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
640                                 /* replace an entry? */
641                                 if(iter->namespc == namespc) {
642                                         assert(iter_last != NULL);
643                                         iter_last->symbol_next = old_declaration;
644                                         if(old_declaration != NULL) {
645                                                 old_declaration->symbol_next = iter->symbol_next;
646                                         }
647                                         break;
648                                 }
649                         }
650                         assert(iter != NULL);
651                 }
652         }
653
654         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
655 }
656
657 static void environment_pop_to(size_t new_top)
658 {
659         stack_pop_to(&environment_stack, new_top);
660 }
661
662 static void label_pop_to(size_t new_top)
663 {
664         stack_pop_to(&label_stack, new_top);
665 }
666
667
668 static int get_rank(const type_t *type)
669 {
670         assert(!is_typeref(type));
671         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
672          * and esp. footnote 108). However we can't fold constants (yet), so we
673          * can't decide whether unsigned int is possible, while int always works.
674          * (unsigned int would be preferable when possible... for stuff like
675          *  struct { enum { ... } bla : 4; } ) */
676         if(type->kind == TYPE_ENUM)
677                 return ATOMIC_TYPE_INT;
678
679         assert(type->kind == TYPE_ATOMIC);
680         return type->atomic.akind;
681 }
682
683 static type_t *promote_integer(type_t *type)
684 {
685         if(type->kind == TYPE_BITFIELD)
686                 type = type->bitfield.base;
687
688         if(get_rank(type) < ATOMIC_TYPE_INT)
689                 type = type_int;
690
691         return type;
692 }
693
694 /**
695  * Create a cast expression.
696  *
697  * @param expression  the expression to cast
698  * @param dest_type   the destination type
699  */
700 static expression_t *create_cast_expression(expression_t *expression,
701                                             type_t *dest_type)
702 {
703         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
704
705         cast->unary.value = expression;
706         cast->base.type   = dest_type;
707
708         return cast;
709 }
710
711 /**
712  * Check if a given expression represents the 0 pointer constant.
713  */
714 static bool is_null_pointer_constant(const expression_t *expression)
715 {
716         /* skip void* cast */
717         if(expression->kind == EXPR_UNARY_CAST
718                         || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
719                 expression = expression->unary.value;
720         }
721
722         /* TODO: not correct yet, should be any constant integer expression
723          * which evaluates to 0 */
724         if (expression->kind != EXPR_CONST)
725                 return false;
726
727         type_t *const type = skip_typeref(expression->base.type);
728         if (!is_type_integer(type))
729                 return false;
730
731         return expression->conste.v.int_value == 0;
732 }
733
734 /**
735  * Create an implicit cast expression.
736  *
737  * @param expression  the expression to cast
738  * @param dest_type   the destination type
739  */
740 static expression_t *create_implicit_cast(expression_t *expression,
741                                           type_t *dest_type)
742 {
743         type_t *const source_type = expression->base.type;
744
745         if (source_type == dest_type)
746                 return expression;
747
748         return create_cast_expression(expression, dest_type);
749 }
750
751 /** Implements the rules from Â§ 6.5.16.1 */
752 static type_t *semantic_assign(type_t *orig_type_left,
753                             const expression_t *const right,
754                             const char *context)
755 {
756         type_t *const orig_type_right = right->base.type;
757         type_t *const type_left       = skip_typeref(orig_type_left);
758         type_t *const type_right      = skip_typeref(orig_type_right);
759
760         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
761             (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
762             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
763                 && is_type_pointer(type_right))) {
764                 return orig_type_left;
765         }
766
767         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
768                 type_t *points_to_left  = skip_typeref(type_left->pointer.points_to);
769                 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
770
771                 /* the left type has all qualifiers from the right type */
772                 unsigned missing_qualifiers
773                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
774                 if(missing_qualifiers != 0) {
775                         errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
776                         return orig_type_left;
777                 }
778
779                 points_to_left  = get_unqualified_type(points_to_left);
780                 points_to_right = get_unqualified_type(points_to_right);
781
782                 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
783                                 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
784                         return orig_type_left;
785                 }
786
787                 if (!types_compatible(points_to_left, points_to_right)) {
788                         warningf(right->base.source_position,
789                                 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
790                                 orig_type_left, context, right, orig_type_right);
791                 }
792
793                 return orig_type_left;
794         }
795
796         if ((is_type_compound(type_left)  && is_type_compound(type_right))
797                         || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
798                 type_t *const unqual_type_left  = get_unqualified_type(type_left);
799                 type_t *const unqual_type_right = get_unqualified_type(type_right);
800                 if (types_compatible(unqual_type_left, unqual_type_right)) {
801                         return orig_type_left;
802                 }
803         }
804
805         if (!is_type_valid(type_left))
806                 return type_left;
807
808         if (!is_type_valid(type_right))
809                 return orig_type_right;
810
811         return NULL;
812 }
813
814 static expression_t *parse_constant_expression(void)
815 {
816         /* start parsing at precedence 7 (conditional expression) */
817         expression_t *result = parse_sub_expression(7);
818
819         if(!is_constant_expression(result)) {
820                 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
821         }
822
823         return result;
824 }
825
826 static expression_t *parse_assignment_expression(void)
827 {
828         /* start parsing at precedence 2 (assignment expression) */
829         return parse_sub_expression(2);
830 }
831
832 static type_t *make_global_typedef(const char *name, type_t *type)
833 {
834         symbol_t *const symbol       = symbol_table_insert(name);
835
836         declaration_t *const declaration = allocate_declaration_zero();
837         declaration->namespc                = NAMESPACE_NORMAL;
838         declaration->storage_class          = STORAGE_CLASS_TYPEDEF;
839         declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
840         declaration->type                   = type;
841         declaration->symbol                 = symbol;
842         declaration->source_position        = builtin_source_position;
843
844         record_declaration(declaration);
845
846         type_t *typedef_type               = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
847         typedef_type->typedeft.declaration = declaration;
848
849         return typedef_type;
850 }
851
852 static string_t parse_string_literals(void)
853 {
854         assert(token.type == T_STRING_LITERAL);
855         string_t result = token.v.string;
856
857         next_token();
858
859         while (token.type == T_STRING_LITERAL) {
860                 result = concat_strings(&result, &token.v.string);
861                 next_token();
862         }
863
864         return result;
865 }
866
867 static void parse_attributes(void)
868 {
869         while(true) {
870                 switch(token.type) {
871                 case T___attribute__: {
872                         next_token();
873
874                         expect_void('(');
875                         int depth = 1;
876                         while(depth > 0) {
877                                 switch(token.type) {
878                                 case T_EOF:
879                                         errorf(HERE, "EOF while parsing attribute");
880                                         break;
881                                 case '(':
882                                         next_token();
883                                         depth++;
884                                         break;
885                                 case ')':
886                                         next_token();
887                                         depth--;
888                                         break;
889                                 default:
890                                         next_token();
891                                 }
892                         }
893                         break;
894                 }
895                 case T_asm:
896                         next_token();
897                         expect_void('(');
898                         if(token.type != T_STRING_LITERAL) {
899                                 parse_error_expected("while parsing assembler attribute",
900                                                      T_STRING_LITERAL);
901                                 eat_paren();
902                                 break;
903                         } else {
904                                 parse_string_literals();
905                         }
906                         expect_void(')');
907                         break;
908                 default:
909                         goto attributes_finished;
910                 }
911         }
912
913 attributes_finished:
914         ;
915 }
916
917 static designator_t *parse_designation(void)
918 {
919         designator_t *result = NULL;
920         designator_t *last   = NULL;
921
922         while(true) {
923                 designator_t *designator;
924                 switch(token.type) {
925                 case '[':
926                         designator = allocate_ast_zero(sizeof(designator[0]));
927                         designator->source_position = token.source_position;
928                         next_token();
929                         designator->array_index = parse_constant_expression();
930                         expect(']');
931                         break;
932                 case '.':
933                         designator = allocate_ast_zero(sizeof(designator[0]));
934                         designator->source_position = token.source_position;
935                         next_token();
936                         if(token.type != T_IDENTIFIER) {
937                                 parse_error_expected("while parsing designator",
938                                                      T_IDENTIFIER, 0);
939                                 return NULL;
940                         }
941                         designator->symbol = token.v.symbol;
942                         next_token();
943                         break;
944                 default:
945                         expect('=');
946                         return result;
947                 }
948
949                 assert(designator != NULL);
950                 if(last != NULL) {
951                         last->next = designator;
952                 } else {
953                         result = designator;
954                 }
955                 last = designator;
956         }
957 }
958
959 static initializer_t *initializer_from_string(array_type_t *type,
960                                               const string_t *const string)
961 {
962         /* TODO: check len vs. size of array type */
963         (void) type;
964
965         initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
966         initializer->string.string = *string;
967
968         return initializer;
969 }
970
971 static initializer_t *initializer_from_wide_string(array_type_t *const type,
972                                                    wide_string_t *const string)
973 {
974         /* TODO: check len vs. size of array type */
975         (void) type;
976
977         initializer_t *const initializer =
978                 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
979         initializer->wide_string.string = *string;
980
981         return initializer;
982 }
983
984 static initializer_t *initializer_from_expression(type_t *orig_type,
985                                                   expression_t *expression)
986 {
987         /* TODO check that expression is a constant expression */
988
989         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
990         type_t *type           = skip_typeref(orig_type);
991         type_t *expr_type_orig = expression->base.type;
992         type_t *expr_type      = skip_typeref(expr_type_orig);
993         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
994                 array_type_t *const array_type   = &type->array;
995                 type_t       *const element_type = skip_typeref(array_type->element_type);
996
997                 if (element_type->kind == TYPE_ATOMIC) {
998                         atomic_type_kind_t akind = element_type->atomic.akind;
999                         switch (expression->kind) {
1000                                 case EXPR_STRING_LITERAL:
1001                                         if (akind == ATOMIC_TYPE_CHAR
1002                                                         || akind == ATOMIC_TYPE_SCHAR
1003                                                         || akind == ATOMIC_TYPE_UCHAR) {
1004                                                 return initializer_from_string(array_type,
1005                                                         &expression->string.value);
1006                                         }
1007
1008                                 case EXPR_WIDE_STRING_LITERAL: {
1009                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1010                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
1011                                                 return initializer_from_wide_string(array_type,
1012                                                         &expression->wide_string.value);
1013                                         }
1014                                 }
1015
1016                                 default:
1017                                         break;
1018                         }
1019                 }
1020         }
1021
1022         type_t *const res_type = semantic_assign(type, expression, "initializer");
1023         if (res_type == NULL)
1024                 return NULL;
1025
1026         initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1027         result->value.value = create_implicit_cast(expression, res_type);
1028
1029         return result;
1030 }
1031
1032 static bool is_initializer_constant(const expression_t *expression)
1033 {
1034         return is_constant_expression(expression)
1035                 || is_address_constant(expression);
1036 }
1037
1038 static initializer_t *parse_scalar_initializer(type_t *type,
1039                                                bool must_be_constant)
1040 {
1041         /* there might be extra {} hierarchies */
1042         int braces = 0;
1043         while(token.type == '{') {
1044                 next_token();
1045                 if(braces == 0) {
1046                         warningf(HERE, "extra curly braces around scalar initializer");
1047                 }
1048                 braces++;
1049         }
1050
1051         expression_t *expression = parse_assignment_expression();
1052         if(must_be_constant && !is_initializer_constant(expression)) {
1053                 errorf(expression->base.source_position,
1054                        "Initialisation expression '%E' is not constant\n",
1055                        expression);
1056         }
1057
1058         initializer_t *initializer = initializer_from_expression(type, expression);
1059
1060         if(initializer == NULL) {
1061                 errorf(expression->base.source_position,
1062                        "expression '%E' doesn't match expected type '%T'",
1063                        expression, type);
1064                 /* TODO */
1065                 return NULL;
1066         }
1067
1068         bool additional_warning_displayed = false;
1069         while(braces > 0) {
1070                 if(token.type == ',') {
1071                         next_token();
1072                 }
1073                 if(token.type != '}') {
1074                         if(!additional_warning_displayed) {
1075                                 warningf(HERE, "additional elements in scalar initializer");
1076                                 additional_warning_displayed = true;
1077                         }
1078                 }
1079                 eat_block();
1080                 braces--;
1081         }
1082
1083         return initializer;
1084 }
1085
1086 typedef struct type_path_entry_t type_path_entry_t;
1087 struct type_path_entry_t {
1088         type_t *type;
1089         union {
1090                 size_t         index;
1091                 declaration_t *compound_entry;
1092         } v;
1093 };
1094
1095 typedef struct type_path_t type_path_t;
1096 struct type_path_t {
1097         type_path_entry_t *path;
1098         type_t            *top_type;     /**< type of the element the path points */
1099         size_t             max_index;    /**< largest index in outermost array */
1100         bool               invalid;
1101 };
1102
1103 static __attribute__((unused)) void debug_print_type_path(
1104                 const type_path_t *path)
1105 {
1106         size_t len = ARR_LEN(path->path);
1107
1108         if(path->invalid) {
1109                 fprintf(stderr, "invalid path");
1110                 return;
1111         }
1112
1113         for(size_t i = 0; i < len; ++i) {
1114                 const type_path_entry_t *entry = & path->path[i];
1115
1116                 type_t *type = skip_typeref(entry->type);
1117                 if(is_type_compound(type)) {
1118                         fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1119                 } else if(is_type_array(type)) {
1120                         fprintf(stderr, "[%u]", entry->v.index);
1121                 } else {
1122                         fprintf(stderr, "-INVALID-");
1123                 }
1124         }
1125         fprintf(stderr, "  (");
1126         print_type(path->top_type);
1127         fprintf(stderr, ")");
1128 }
1129
1130 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1131 {
1132         size_t len = ARR_LEN(path->path);
1133         assert(len > 0);
1134         return & path->path[len-1];
1135 }
1136
1137 static type_path_entry_t *append_to_type_path(type_path_t *path)
1138 {
1139         size_t len = ARR_LEN(path->path);
1140         ARR_RESIZE(type_path_entry_t, path->path, len+1);
1141
1142         type_path_entry_t *result = & path->path[len];
1143         memset(result, 0, sizeof(result[0]));
1144         return result;
1145 }
1146
1147 static void descend_into_subtype(type_path_t *path)
1148 {
1149         type_t *orig_top_type = path->top_type;
1150         type_t *top_type      = skip_typeref(orig_top_type);
1151
1152         assert(is_type_compound(top_type) || is_type_array(top_type));
1153
1154         type_path_entry_t *top = append_to_type_path(path);
1155         top->type              = top_type;
1156
1157         if(is_type_compound(top_type)) {
1158                 declaration_t *declaration = top_type->compound.declaration;
1159                 declaration_t *entry       = declaration->scope.declarations;
1160
1161                 top->v.compound_entry = entry;
1162                 path->top_type        = entry->type;
1163         } else {
1164                 assert(is_type_array(top_type));
1165
1166                 top->v.index   = 0;
1167                 path->top_type = top_type->array.element_type;
1168         }
1169 }
1170
1171 static void ascend_from_subtype(type_path_t *path)
1172 {
1173         type_path_entry_t *top = get_type_path_top(path);
1174
1175         path->top_type = top->type;
1176
1177         size_t len = ARR_LEN(path->path);
1178         ARR_RESIZE(type_path_entry_t, path->path, len-1);
1179 }
1180
1181 static void ascend_to(type_path_t *path, size_t top_path_level)
1182 {
1183         size_t len = ARR_LEN(path->path);
1184         assert(len >= top_path_level);
1185
1186         while(len > top_path_level) {
1187                 ascend_from_subtype(path);
1188                 len = ARR_LEN(path->path);
1189         }
1190 }
1191
1192 static bool walk_designator(type_path_t *path, const designator_t *designator,
1193                             bool used_in_offsetof)
1194 {
1195         for( ; designator != NULL; designator = designator->next) {
1196                 type_path_entry_t *top       = get_type_path_top(path);
1197                 type_t            *orig_type = top->type;
1198
1199                 type_t *type = skip_typeref(orig_type);
1200
1201                 if(designator->symbol != NULL) {
1202                         symbol_t *symbol = designator->symbol;
1203                         if(!is_type_compound(type)) {
1204                                 if(is_type_valid(type)) {
1205                                         errorf(designator->source_position,
1206                                                "'.%Y' designator used for non-compound type '%T'",
1207                                                symbol, orig_type);
1208                                 }
1209                                 goto failed;
1210                         }
1211
1212                         declaration_t *declaration = type->compound.declaration;
1213                         declaration_t *iter        = declaration->scope.declarations;
1214                         for( ; iter != NULL; iter = iter->next) {
1215                                 if(iter->symbol == symbol) {
1216                                         break;
1217                                 }
1218                         }
1219                         if(iter == NULL) {
1220                                 errorf(designator->source_position,
1221                                        "'%T' has no member named '%Y'", orig_type, symbol);
1222                                 goto failed;
1223                         }
1224                         if(used_in_offsetof) {
1225                                 type_t *real_type = skip_typeref(iter->type);
1226                                 if(real_type->kind == TYPE_BITFIELD) {
1227                                         errorf(designator->source_position,
1228                                                "offsetof designator '%Y' may not specify bitfield",
1229                                                symbol);
1230                                         goto failed;
1231                                 }
1232                         }
1233
1234                         top->type             = orig_type;
1235                         top->v.compound_entry = iter;
1236                         orig_type             = iter->type;
1237                 } else {
1238                         expression_t *array_index = designator->array_index;
1239                         assert(designator->array_index != NULL);
1240
1241                         if(!is_type_array(type)) {
1242                                 if(is_type_valid(type)) {
1243                                         errorf(designator->source_position,
1244                                                "[%E] designator used for non-array type '%T'",
1245                                                array_index, orig_type);
1246                                 }
1247                                 goto failed;
1248                         }
1249                         if(!is_type_valid(array_index->base.type)) {
1250                                 goto failed;
1251                         }
1252
1253                         long index = fold_constant(array_index);
1254                         if(!used_in_offsetof) {
1255                                 if(index < 0) {
1256                                         errorf(designator->source_position,
1257                                                "array index [%E] must be positive", array_index);
1258                                         goto failed;
1259                                 }
1260                                 if(type->array.size_constant == true) {
1261                                         long array_size = type->array.size;
1262                                         if(index >= array_size) {
1263                                                 errorf(designator->source_position,
1264                                                                 "designator [%E] (%d) exceeds array size %d",
1265                                                                 array_index, index, array_size);
1266                                                 goto failed;
1267                                         }
1268                                 }
1269                         }
1270
1271                         top->type    = orig_type;
1272                         top->v.index = (size_t) index;
1273                         orig_type    = type->array.element_type;
1274                 }
1275                 path->top_type = orig_type;
1276
1277                 if(designator->next != NULL) {
1278                         descend_into_subtype(path);
1279                 }
1280         }
1281
1282         path->invalid  = false;
1283         return true;
1284
1285 failed:
1286         return false;
1287 }
1288
1289 static void advance_current_object(type_path_t *path, size_t top_path_level)
1290 {
1291         if(path->invalid)
1292                 return;
1293
1294         type_path_entry_t *top = get_type_path_top(path);
1295
1296         type_t *type = skip_typeref(top->type);
1297         if(is_type_union(type)) {
1298                 /* in unions only the first element is initialized */
1299                 top->v.compound_entry = NULL;
1300         } else if(is_type_struct(type)) {
1301                 declaration_t *entry = top->v.compound_entry;
1302
1303                 entry                 = entry->next;
1304                 top->v.compound_entry = entry;
1305                 if(entry != NULL) {
1306                         path->top_type = entry->type;
1307                         return;
1308                 }
1309         } else {
1310                 assert(is_type_array(type));
1311
1312                 top->v.index++;
1313
1314                 if(!type->array.size_constant || top->v.index < type->array.size) {
1315                         return;
1316                 }
1317         }
1318
1319         /* we're past the last member of the current sub-aggregate, try if we
1320          * can ascend in the type hierarchy and continue with another subobject */
1321         size_t len = ARR_LEN(path->path);
1322
1323         if(len > top_path_level) {
1324                 ascend_from_subtype(path);
1325                 advance_current_object(path, top_path_level);
1326         } else {
1327                 path->invalid = true;
1328         }
1329 }
1330
1331 static void skip_initializers(void)
1332 {
1333         if(token.type == '{')
1334                 next_token();
1335
1336         while(token.type != '}') {
1337                 if(token.type == T_EOF)
1338                         return;
1339                 if(token.type == '{') {
1340                         eat_block();
1341                         continue;
1342                 }
1343                 next_token();
1344         }
1345 }
1346
1347 static initializer_t *parse_sub_initializer(type_path_t *path,
1348                 type_t *outer_type, size_t top_path_level, bool must_be_constant)
1349 {
1350         type_t *orig_type = path->top_type;
1351         type_t *type      = skip_typeref(orig_type);
1352
1353         /* we can't do usefull stuff if we didn't even parse the type. Skip the
1354          * initializers in this case. */
1355         if(!is_type_valid(type)) {
1356                 skip_initializers();
1357                 return NULL;
1358         }
1359
1360         initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1361
1362         while(true) {
1363                 designator_t *designator = NULL;
1364                 if(token.type == '.' || token.type == '[') {
1365                         designator = parse_designation();
1366
1367                         /* reset path to toplevel, evaluate designator from there */
1368                         ascend_to(path, top_path_level);
1369                         if(!walk_designator(path, designator, false)) {
1370                                 /* can't continue after designation error */
1371                                 goto end_error;
1372                         }
1373
1374                         initializer_t *designator_initializer
1375                                 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1376                         designator_initializer->designator.designator = designator;
1377                         ARR_APP1(initializer_t*, initializers, designator_initializer);
1378                 }
1379
1380                 initializer_t *sub;
1381
1382                 if(token.type == '{') {
1383                         if(is_type_scalar(type)) {
1384                                 sub = parse_scalar_initializer(type, must_be_constant);
1385                         } else {
1386                                 eat('{');
1387                                 descend_into_subtype(path);
1388
1389                                 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1390                                                             must_be_constant);
1391
1392                                 ascend_from_subtype(path);
1393
1394                                 expect_block('}');
1395                         }
1396                 } else {
1397                         /* must be an expression */
1398                         expression_t *expression = parse_assignment_expression();
1399
1400                         if(must_be_constant && !is_initializer_constant(expression)) {
1401                                 errorf(expression->base.source_position,
1402                                        "Initialisation expression '%E' is not constant\n",
1403                                        expression);
1404                         }
1405
1406                         /* handle { "string" } special case */
1407                         if((expression->kind == EXPR_STRING_LITERAL
1408                                         || expression->kind == EXPR_WIDE_STRING_LITERAL)
1409                                         && outer_type != NULL) {
1410                                 sub = initializer_from_expression(outer_type, expression);
1411                                 if(sub != NULL) {
1412                                         if(token.type == ',') {
1413                                                 next_token();
1414                                         }
1415                                         if(token.type != '}') {
1416                                                 warningf(HERE, "excessive elements in initializer for type '%T'",
1417                                                                  orig_type);
1418                                         }
1419                                         /* TODO: eat , ... */
1420                                         return sub;
1421                                 }
1422                         }
1423
1424                         /* descend into subtypes until expression matches type */
1425                         while(true) {
1426                                 orig_type = path->top_type;
1427                                 type      = skip_typeref(orig_type);
1428
1429                                 sub = initializer_from_expression(orig_type, expression);
1430                                 if(sub != NULL) {
1431                                         break;
1432                                 }
1433                                 if(!is_type_valid(type)) {
1434                                         goto end_error;
1435                                 }
1436                                 if(is_type_scalar(type)) {
1437                                         errorf(expression->base.source_position,
1438                                                         "expression '%E' doesn't match expected type '%T'",
1439                                                         expression, orig_type);
1440                                         goto end_error;
1441                                 }
1442
1443                                 descend_into_subtype(path);
1444                         }
1445                 }
1446
1447                 /* update largest index of top array */
1448                 const type_path_entry_t *first      = &path->path[0];
1449                 type_t                  *first_type = first->type;
1450                 first_type                          = skip_typeref(first_type);
1451                 if(is_type_array(first_type)) {
1452                         size_t index = first->v.index;
1453                         if(index > path->max_index)
1454                                 path->max_index = index;
1455                 }
1456
1457                 /* append to initializers list */
1458                 ARR_APP1(initializer_t*, initializers, sub);
1459
1460                 if(token.type == '}') {
1461                         break;
1462                 }
1463                 expect(',');
1464                 if(token.type == '}') {
1465                         break;
1466                 }
1467
1468                 advance_current_object(path, top_path_level);
1469                 orig_type = path->top_type;
1470                 type      = skip_typeref(orig_type);
1471         }
1472
1473         size_t len  = ARR_LEN(initializers);
1474         size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1475         initializer_t *result = allocate_ast_zero(size);
1476         result->kind          = INITIALIZER_LIST;
1477         result->list.len      = len;
1478         memcpy(&result->list.initializers, initializers,
1479                len * sizeof(initializers[0]));
1480
1481         ascend_to(path, top_path_level);
1482
1483         return result;
1484
1485 end_error:
1486         skip_initializers();
1487         DEL_ARR_F(initializers);
1488         ascend_to(path, top_path_level);
1489         return NULL;
1490 }
1491
1492 typedef struct parse_initializer_env_t {
1493         type_t        *type;        /* the type of the initializer. In case of an
1494                                        array type with unspecified size this gets
1495                                        adjusted to the actual size. */
1496         initializer_t *initializer; /* initializer will be filled in here */
1497         bool           must_be_constant;
1498 } parse_initializer_env_t;
1499
1500 static void parse_initializer(parse_initializer_env_t *env)
1501 {
1502         type_t        *type   = skip_typeref(env->type);
1503         initializer_t *result = NULL;
1504         size_t         max_index;
1505
1506         if(is_type_scalar(type)) {
1507                 /* TODO: Â§ 6.7.8.11; eat {} without warning */
1508                 result = parse_scalar_initializer(type, env->must_be_constant);
1509         } else if(token.type == '{') {
1510                 eat('{');
1511
1512                 type_path_t path;
1513                 memset(&path, 0, sizeof(path));
1514                 path.top_type = env->type;
1515                 path.path     = NEW_ARR_F(type_path_entry_t, 0);
1516
1517                 descend_into_subtype(&path);
1518
1519                 result = parse_sub_initializer(&path, env->type, 1,
1520                                                env->must_be_constant);
1521
1522                 max_index = path.max_index;
1523                 DEL_ARR_F(path.path);
1524
1525                 expect_void('}');
1526         } else {
1527                 /* parse_scalar_initializer also works in this case: we simply
1528                  * have an expression without {} around it */
1529                 result = parse_scalar_initializer(type, env->must_be_constant);
1530         }
1531
1532         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
1533          * the array type size */
1534         if(is_type_array(type) && type->array.size_expression == NULL
1535                         && result != NULL) {
1536                 size_t size;
1537                 switch (result->kind) {
1538                 case INITIALIZER_LIST:
1539                         size = max_index + 1;
1540                         break;
1541
1542                 case INITIALIZER_STRING:
1543                         size = result->string.string.size;
1544                         break;
1545
1546                 case INITIALIZER_WIDE_STRING:
1547                         size = result->wide_string.string.size;
1548                         break;
1549
1550                 default:
1551                         panic("invalid initializer type");
1552                 }
1553
1554                 expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
1555                 cnst->base.type          = type_size_t;
1556                 cnst->conste.v.int_value = size;
1557
1558                 type_t *new_type = duplicate_type(type);
1559
1560                 new_type->array.size_expression = cnst;
1561                 new_type->array.size_constant   = true;
1562                 new_type->array.size            = size;
1563                 env->type = new_type;
1564         }
1565
1566         env->initializer = result;
1567 }
1568
1569 static declaration_t *append_declaration(declaration_t *declaration);
1570
1571 static declaration_t *parse_compound_type_specifier(bool is_struct)
1572 {
1573         if(is_struct) {
1574                 eat(T_struct);
1575         } else {
1576                 eat(T_union);
1577         }
1578
1579         symbol_t      *symbol      = NULL;
1580         declaration_t *declaration = NULL;
1581
1582         if (token.type == T___attribute__) {
1583                 /* TODO */
1584                 parse_attributes();
1585         }
1586
1587         if(token.type == T_IDENTIFIER) {
1588                 symbol = token.v.symbol;
1589                 next_token();
1590
1591                 if(is_struct) {
1592                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1593                 } else {
1594                         declaration = get_declaration(symbol, NAMESPACE_UNION);
1595                 }
1596         } else if(token.type != '{') {
1597                 if(is_struct) {
1598                         parse_error_expected("while parsing struct type specifier",
1599                                              T_IDENTIFIER, '{', 0);
1600                 } else {
1601                         parse_error_expected("while parsing union type specifier",
1602                                              T_IDENTIFIER, '{', 0);
1603                 }
1604
1605                 return NULL;
1606         }
1607
1608         if(declaration == NULL) {
1609                 declaration = allocate_declaration_zero();
1610                 declaration->namespc         =
1611                         (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1612                 declaration->source_position = token.source_position;
1613                 declaration->symbol          = symbol;
1614                 declaration->parent_scope  = scope;
1615                 if (symbol != NULL) {
1616                         environment_push(declaration);
1617                 }
1618                 append_declaration(declaration);
1619         }
1620
1621         if(token.type == '{') {
1622                 if(declaration->init.is_defined) {
1623                         assert(symbol != NULL);
1624                         errorf(HERE, "multiple definitions of '%s %Y'",
1625                                is_struct ? "struct" : "union", symbol);
1626                         declaration->scope.declarations = NULL;
1627                 }
1628                 declaration->init.is_defined = true;
1629
1630                 parse_compound_type_entries(declaration);
1631                 parse_attributes();
1632         }
1633
1634         return declaration;
1635 }
1636
1637 static void parse_enum_entries(type_t *const enum_type)
1638 {
1639         eat('{');
1640
1641         if(token.type == '}') {
1642                 next_token();
1643                 errorf(HERE, "empty enum not allowed");
1644                 return;
1645         }
1646
1647         do {
1648                 if(token.type != T_IDENTIFIER) {
1649                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1650                         eat_block();
1651                         return;
1652                 }
1653
1654                 declaration_t *const entry = allocate_declaration_zero();
1655                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
1656                 entry->type            = enum_type;
1657                 entry->symbol          = token.v.symbol;
1658                 entry->source_position = token.source_position;
1659                 next_token();
1660
1661                 if(token.type == '=') {
1662                         next_token();
1663                         expression_t *value = parse_constant_expression();
1664
1665                         value = create_implicit_cast(value, enum_type);
1666                         entry->init.enum_value = value;
1667
1668                         /* TODO semantic */
1669                 }
1670
1671                 record_declaration(entry);
1672
1673                 if(token.type != ',')
1674                         break;
1675                 next_token();
1676         } while(token.type != '}');
1677
1678         expect_void('}');
1679 }
1680
1681 static type_t *parse_enum_specifier(void)
1682 {
1683         eat(T_enum);
1684
1685         declaration_t *declaration;
1686         symbol_t      *symbol;
1687
1688         if(token.type == T_IDENTIFIER) {
1689                 symbol = token.v.symbol;
1690                 next_token();
1691
1692                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1693         } else if(token.type != '{') {
1694                 parse_error_expected("while parsing enum type specifier",
1695                                      T_IDENTIFIER, '{', 0);
1696                 return NULL;
1697         } else {
1698                 declaration = NULL;
1699                 symbol      = NULL;
1700         }
1701
1702         if(declaration == NULL) {
1703                 declaration = allocate_declaration_zero();
1704                 declaration->namespc         = NAMESPACE_ENUM;
1705                 declaration->source_position = token.source_position;
1706                 declaration->symbol          = symbol;
1707                 declaration->parent_scope  = scope;
1708         }
1709
1710         type_t *const type      = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1711         type->enumt.declaration = declaration;
1712
1713         if(token.type == '{') {
1714                 if(declaration->init.is_defined) {
1715                         errorf(HERE, "multiple definitions of enum %Y", symbol);
1716                 }
1717                 if (symbol != NULL) {
1718                         environment_push(declaration);
1719                 }
1720                 append_declaration(declaration);
1721                 declaration->init.is_defined = 1;
1722
1723                 parse_enum_entries(type);
1724                 parse_attributes();
1725         }
1726
1727         return type;
1728 }
1729
1730 /**
1731  * if a symbol is a typedef to another type, return true
1732  */
1733 static bool is_typedef_symbol(symbol_t *symbol)
1734 {
1735         const declaration_t *const declaration =
1736                 get_declaration(symbol, NAMESPACE_NORMAL);
1737         return
1738                 declaration != NULL &&
1739                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1740 }
1741
1742 static type_t *parse_typeof(void)
1743 {
1744         eat(T___typeof__);
1745
1746         type_t *type;
1747
1748         expect('(');
1749
1750         expression_t *expression  = NULL;
1751
1752 restart:
1753         switch(token.type) {
1754         case T___extension__:
1755                 /* this can be a prefix to a typename or an expression */
1756                 /* we simply eat it now. */
1757                 do {
1758                         next_token();
1759                 } while(token.type == T___extension__);
1760                 goto restart;
1761
1762         case T_IDENTIFIER:
1763                 if(is_typedef_symbol(token.v.symbol)) {
1764                         type = parse_typename();
1765                 } else {
1766                         expression = parse_expression();
1767                         type       = expression->base.type;
1768                 }
1769                 break;
1770
1771         TYPENAME_START
1772                 type = parse_typename();
1773                 break;
1774
1775         default:
1776                 expression = parse_expression();
1777                 type       = expression->base.type;
1778                 break;
1779         }
1780
1781         expect(')');
1782
1783         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1784         typeof_type->typeoft.expression  = expression;
1785         typeof_type->typeoft.typeof_type = type;
1786
1787         return typeof_type;
1788 }
1789
1790 typedef enum {
1791         SPECIFIER_SIGNED    = 1 << 0,
1792         SPECIFIER_UNSIGNED  = 1 << 1,
1793         SPECIFIER_LONG      = 1 << 2,
1794         SPECIFIER_INT       = 1 << 3,
1795         SPECIFIER_DOUBLE    = 1 << 4,
1796         SPECIFIER_CHAR      = 1 << 5,
1797         SPECIFIER_SHORT     = 1 << 6,
1798         SPECIFIER_LONG_LONG = 1 << 7,
1799         SPECIFIER_FLOAT     = 1 << 8,
1800         SPECIFIER_BOOL      = 1 << 9,
1801         SPECIFIER_VOID      = 1 << 10,
1802 #ifdef PROVIDE_COMPLEX
1803         SPECIFIER_COMPLEX   = 1 << 11,
1804         SPECIFIER_IMAGINARY = 1 << 12,
1805 #endif
1806 } specifiers_t;
1807
1808 static type_t *create_builtin_type(symbol_t *const symbol,
1809                                    type_t *const real_type)
1810 {
1811         type_t *type            = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1812         type->builtin.symbol    = symbol;
1813         type->builtin.real_type = real_type;
1814
1815         type_t *result = typehash_insert(type);
1816         if (type != result) {
1817                 free_type(type);
1818         }
1819
1820         return result;
1821 }
1822
1823 static type_t *get_typedef_type(symbol_t *symbol)
1824 {
1825         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1826         if(declaration == NULL
1827                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1828                 return NULL;
1829
1830         type_t *type               = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1831         type->typedeft.declaration = declaration;
1832
1833         return type;
1834 }
1835
1836 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1837 {
1838         type_t   *type            = NULL;
1839         unsigned  type_qualifiers = 0;
1840         unsigned  type_specifiers = 0;
1841         int       newtype         = 0;
1842
1843         specifiers->source_position = token.source_position;
1844
1845         while(true) {
1846                 switch(token.type) {
1847
1848                 /* storage class */
1849 #define MATCH_STORAGE_CLASS(token, class)                                  \
1850                 case token:                                                        \
1851                         if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
1852                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
1853                         }                                                              \
1854                         specifiers->declared_storage_class = class;                    \
1855                         next_token();                                                  \
1856                         break;
1857
1858                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1859                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1860                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1861                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1862                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1863
1864                 case T___thread:
1865                         switch (specifiers->declared_storage_class) {
1866                         case STORAGE_CLASS_NONE:
1867                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
1868                                 break;
1869
1870                         case STORAGE_CLASS_EXTERN:
1871                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
1872                                 break;
1873
1874                         case STORAGE_CLASS_STATIC:
1875                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
1876                                 break;
1877
1878                         default:
1879                                 errorf(HERE, "multiple storage classes in declaration specifiers");
1880                                 break;
1881                         }
1882                         next_token();
1883                         break;
1884
1885                 /* type qualifiers */
1886 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1887                 case token:                                                     \
1888                         type_qualifiers |= qualifier;                               \
1889                         next_token();                                               \
1890                         break;
1891
1892                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1893                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1894                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1895
1896                 case T___extension__:
1897                         /* TODO */
1898                         next_token();
1899                         break;
1900
1901                 /* type specifiers */
1902 #define MATCH_SPECIFIER(token, specifier, name)                         \
1903                 case token:                                                     \
1904                         next_token();                                               \
1905                         if(type_specifiers & specifier) {                           \
1906                                 errorf(HERE, "multiple " name " type specifiers given"); \
1907                         } else {                                                    \
1908                                 type_specifiers |= specifier;                           \
1909                         }                                                           \
1910                         break;
1911
1912                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1913                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1914                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1915                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1916                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1917                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1918                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1919                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1920                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1921 #ifdef PROVIDE_COMPLEX
1922                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1923                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1924 #endif
1925                 case T_forceinline:
1926                         /* only in microsoft mode */
1927                         specifiers->decl_modifiers |= DM_FORCEINLINE;
1928
1929                 case T_inline:
1930                         next_token();
1931                         specifiers->is_inline = true;
1932                         break;
1933
1934                 case T_long:
1935                         next_token();
1936                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1937                                 errorf(HERE, "multiple type specifiers given");
1938                         } else if(type_specifiers & SPECIFIER_LONG) {
1939                                 type_specifiers |= SPECIFIER_LONG_LONG;
1940                         } else {
1941                                 type_specifiers |= SPECIFIER_LONG;
1942                         }
1943                         break;
1944
1945                 case T_struct: {
1946                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
1947
1948                         type->compound.declaration = parse_compound_type_specifier(true);
1949                         break;
1950                 }
1951                 case T_union: {
1952                         type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
1953
1954                         type->compound.declaration = parse_compound_type_specifier(false);
1955                         break;
1956                 }
1957                 case T_enum:
1958                         type = parse_enum_specifier();
1959                         break;
1960                 case T___typeof__:
1961                         type = parse_typeof();
1962                         break;
1963                 case T___builtin_va_list:
1964                         type = duplicate_type(type_valist);
1965                         next_token();
1966                         break;
1967
1968                 case T___attribute__:
1969                         parse_attributes();
1970                         break;
1971
1972                 case T_IDENTIFIER: {
1973                         /* only parse identifier if we haven't found a type yet */
1974                         if(type != NULL || type_specifiers != 0)
1975                                 goto finish_specifiers;
1976
1977                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1978
1979                         if(typedef_type == NULL)
1980                                 goto finish_specifiers;
1981
1982                         next_token();
1983                         type = typedef_type;
1984                         break;
1985                 }
1986
1987                 /* function specifier */
1988                 default:
1989                         goto finish_specifiers;
1990                 }
1991         }
1992
1993 finish_specifiers:
1994
1995         if(type == NULL) {
1996                 atomic_type_kind_t atomic_type;
1997
1998                 /* match valid basic types */
1999                 switch(type_specifiers) {
2000                 case SPECIFIER_VOID:
2001                         atomic_type = ATOMIC_TYPE_VOID;
2002                         break;
2003                 case SPECIFIER_CHAR:
2004                         atomic_type = ATOMIC_TYPE_CHAR;
2005                         break;
2006                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2007                         atomic_type = ATOMIC_TYPE_SCHAR;
2008                         break;
2009                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2010                         atomic_type = ATOMIC_TYPE_UCHAR;
2011                         break;
2012                 case SPECIFIER_SHORT:
2013                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2014                 case SPECIFIER_SHORT | SPECIFIER_INT:
2015                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2016                         atomic_type = ATOMIC_TYPE_SHORT;
2017                         break;
2018                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2019                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2020                         atomic_type = ATOMIC_TYPE_USHORT;
2021                         break;
2022                 case SPECIFIER_INT:
2023                 case SPECIFIER_SIGNED:
2024                 case SPECIFIER_SIGNED | SPECIFIER_INT:
2025                         atomic_type = ATOMIC_TYPE_INT;
2026                         break;
2027                 case SPECIFIER_UNSIGNED:
2028                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2029                         atomic_type = ATOMIC_TYPE_UINT;
2030                         break;
2031                 case SPECIFIER_LONG:
2032                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2033                 case SPECIFIER_LONG | SPECIFIER_INT:
2034                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2035                         atomic_type = ATOMIC_TYPE_LONG;
2036                         break;
2037                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2038                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2039                         atomic_type = ATOMIC_TYPE_ULONG;
2040                         break;
2041                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2042                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2043                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2044                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2045                         | SPECIFIER_INT:
2046                         atomic_type = ATOMIC_TYPE_LONGLONG;
2047                         break;
2048                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2049                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2050                         | SPECIFIER_INT:
2051                         atomic_type = ATOMIC_TYPE_ULONGLONG;
2052                         break;
2053                 case SPECIFIER_FLOAT:
2054                         atomic_type = ATOMIC_TYPE_FLOAT;
2055                         break;
2056                 case SPECIFIER_DOUBLE:
2057                         atomic_type = ATOMIC_TYPE_DOUBLE;
2058                         break;
2059                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2060                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2061                         break;
2062                 case SPECIFIER_BOOL:
2063                         atomic_type = ATOMIC_TYPE_BOOL;
2064                         break;
2065 #ifdef PROVIDE_COMPLEX
2066                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2067                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2068                         break;
2069                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2070                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2071                         break;
2072                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2073                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2074                         break;
2075                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2076                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2077                         break;
2078                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2079                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2080                         break;
2081                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2082                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2083                         break;
2084 #endif
2085                 default:
2086                         /* invalid specifier combination, give an error message */
2087                         if(type_specifiers == 0) {
2088                                 if (! strict_mode) {
2089                                         if (warning.implicit_int) {
2090                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
2091                                         }
2092                                         atomic_type = ATOMIC_TYPE_INT;
2093                                         break;
2094                                 } else {
2095                                         errorf(HERE, "no type specifiers given in declaration");
2096                                 }
2097                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
2098                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
2099                                 errorf(HERE, "signed and unsigned specifiers gives");
2100                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2101                                 errorf(HERE, "only integer types can be signed or unsigned");
2102                         } else {
2103                                 errorf(HERE, "multiple datatypes in declaration");
2104                         }
2105                         atomic_type = ATOMIC_TYPE_INVALID;
2106                 }
2107
2108                 type               = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2109                 type->atomic.akind = atomic_type;
2110                 newtype            = 1;
2111         } else {
2112                 if(type_specifiers != 0) {
2113                         errorf(HERE, "multiple datatypes in declaration");
2114                 }
2115         }
2116
2117         type->base.qualifiers = type_qualifiers;
2118
2119         type_t *result = typehash_insert(type);
2120         if(newtype && result != type) {
2121                 free_type(type);
2122         }
2123
2124         specifiers->type = result;
2125 }
2126
2127 static type_qualifiers_t parse_type_qualifiers(void)
2128 {
2129         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2130
2131         while(true) {
2132                 switch(token.type) {
2133                 /* type qualifiers */
2134                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2135                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2136                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2137
2138                 default:
2139                         return type_qualifiers;
2140                 }
2141         }
2142 }
2143
2144 static declaration_t *parse_identifier_list(void)
2145 {
2146         declaration_t *declarations     = NULL;
2147         declaration_t *last_declaration = NULL;
2148         do {
2149                 declaration_t *const declaration = allocate_declaration_zero();
2150                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
2151                 declaration->source_position = token.source_position;
2152                 declaration->symbol          = token.v.symbol;
2153                 next_token();
2154
2155                 if(last_declaration != NULL) {
2156                         last_declaration->next = declaration;
2157                 } else {
2158                         declarations = declaration;
2159                 }
2160                 last_declaration = declaration;
2161
2162                 if(token.type != ',')
2163                         break;
2164                 next_token();
2165         } while(token.type == T_IDENTIFIER);
2166
2167         return declarations;
2168 }
2169
2170 static void semantic_parameter(declaration_t *declaration)
2171 {
2172         /* TODO: improve error messages */
2173
2174         if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2175                 errorf(HERE, "typedef not allowed in parameter list");
2176         } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2177                         && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2178                 errorf(HERE, "parameter may only have none or register storage class");
2179         }
2180
2181         type_t *const orig_type = declaration->type;
2182         type_t *      type      = skip_typeref(orig_type);
2183
2184         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
2185          * into a pointer. Â§ 6.7.5.3 (7) */
2186         if (is_type_array(type)) {
2187                 type_t *const element_type = type->array.element_type;
2188
2189                 type = make_pointer_type(element_type, type->base.qualifiers);
2190
2191                 declaration->type = type;
2192         }
2193
2194         if(is_type_incomplete(type)) {
2195                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2196                        orig_type, declaration->symbol);
2197         }
2198 }
2199
2200 static declaration_t *parse_parameter(void)
2201 {
2202         declaration_specifiers_t specifiers;
2203         memset(&specifiers, 0, sizeof(specifiers));
2204
2205         parse_declaration_specifiers(&specifiers);
2206
2207         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2208
2209         semantic_parameter(declaration);
2210
2211         return declaration;
2212 }
2213
2214 static declaration_t *parse_parameters(function_type_t *type)
2215 {
2216         if(token.type == T_IDENTIFIER) {
2217                 symbol_t *symbol = token.v.symbol;
2218                 if(!is_typedef_symbol(symbol)) {
2219                         type->kr_style_parameters = true;
2220                         return parse_identifier_list();
2221                 }
2222         }
2223
2224         if(token.type == ')') {
2225                 type->unspecified_parameters = 1;
2226                 return NULL;
2227         }
2228         if(token.type == T_void && look_ahead(1)->type == ')') {
2229                 next_token();
2230                 return NULL;
2231         }
2232
2233         declaration_t        *declarations = NULL;
2234         declaration_t        *declaration;
2235         declaration_t        *last_declaration = NULL;
2236         function_parameter_t *parameter;
2237         function_parameter_t *last_parameter = NULL;
2238
2239         while(true) {
2240                 switch(token.type) {
2241                 case T_DOTDOTDOT:
2242                         next_token();
2243                         type->variadic = 1;
2244                         return declarations;
2245
2246                 case T_IDENTIFIER:
2247                 case T___extension__:
2248                 DECLARATION_START
2249                         declaration = parse_parameter();
2250
2251                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
2252                         memset(parameter, 0, sizeof(parameter[0]));
2253                         parameter->type = declaration->type;
2254
2255                         if(last_parameter != NULL) {
2256                                 last_declaration->next = declaration;
2257                                 last_parameter->next   = parameter;
2258                         } else {
2259                                 type->parameters = parameter;
2260                                 declarations     = declaration;
2261                         }
2262                         last_parameter   = parameter;
2263                         last_declaration = declaration;
2264                         break;
2265
2266                 default:
2267                         return declarations;
2268                 }
2269                 if(token.type != ',')
2270                         return declarations;
2271                 next_token();
2272         }
2273 }
2274
2275 typedef enum {
2276         CONSTRUCT_INVALID,
2277         CONSTRUCT_POINTER,
2278         CONSTRUCT_FUNCTION,
2279         CONSTRUCT_ARRAY
2280 } construct_type_kind_t;
2281
2282 typedef struct construct_type_t construct_type_t;
2283 struct construct_type_t {
2284         construct_type_kind_t  kind;
2285         construct_type_t      *next;
2286 };
2287
2288 typedef struct parsed_pointer_t parsed_pointer_t;
2289 struct parsed_pointer_t {
2290         construct_type_t  construct_type;
2291         type_qualifiers_t type_qualifiers;
2292 };
2293
2294 typedef struct construct_function_type_t construct_function_type_t;
2295 struct construct_function_type_t {
2296         construct_type_t  construct_type;
2297         type_t           *function_type;
2298 };
2299
2300 typedef struct parsed_array_t parsed_array_t;
2301 struct parsed_array_t {
2302         construct_type_t  construct_type;
2303         type_qualifiers_t type_qualifiers;
2304         bool              is_static;
2305         bool              is_variable;
2306         expression_t     *size;
2307 };
2308
2309 typedef struct construct_base_type_t construct_base_type_t;
2310 struct construct_base_type_t {
2311         construct_type_t  construct_type;
2312         type_t           *type;
2313 };
2314
2315 static construct_type_t *parse_pointer_declarator(void)
2316 {
2317         eat('*');
2318
2319         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2320         memset(pointer, 0, sizeof(pointer[0]));
2321         pointer->construct_type.kind = CONSTRUCT_POINTER;
2322         pointer->type_qualifiers     = parse_type_qualifiers();
2323
2324         return (construct_type_t*) pointer;
2325 }
2326
2327 static construct_type_t *parse_array_declarator(void)
2328 {
2329         eat('[');
2330
2331         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2332         memset(array, 0, sizeof(array[0]));
2333         array->construct_type.kind = CONSTRUCT_ARRAY;
2334
2335         if(token.type == T_static) {
2336                 array->is_static = true;
2337                 next_token();
2338         }
2339
2340         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2341         if(type_qualifiers != 0) {
2342                 if(token.type == T_static) {
2343                         array->is_static = true;
2344                         next_token();
2345                 }
2346         }
2347         array->type_qualifiers = type_qualifiers;
2348
2349         if(token.type == '*' && look_ahead(1)->type == ']') {
2350                 array->is_variable = true;
2351                 next_token();
2352         } else if(token.type != ']') {
2353                 array->size = parse_assignment_expression();
2354         }
2355
2356         expect(']');
2357
2358         return (construct_type_t*) array;
2359 }
2360
2361 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2362 {
2363         eat('(');
2364
2365         type_t *type;
2366         if(declaration != NULL) {
2367                 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2368         } else {
2369                 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2370         }
2371
2372         declaration_t *parameters = parse_parameters(&type->function);
2373         if(declaration != NULL) {
2374                 declaration->scope.declarations = parameters;
2375         }
2376
2377         construct_function_type_t *construct_function_type =
2378                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2379         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2380         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2381         construct_function_type->function_type       = type;
2382
2383         expect(')');
2384
2385         return (construct_type_t*) construct_function_type;
2386 }
2387
2388 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2389                 bool may_be_abstract)
2390 {
2391         /* construct a single linked list of construct_type_t's which describe
2392          * how to construct the final declarator type */
2393         construct_type_t *first = NULL;
2394         construct_type_t *last  = NULL;
2395
2396         /* pointers */
2397         while(token.type == '*') {
2398                 construct_type_t *type = parse_pointer_declarator();
2399
2400                 if(last == NULL) {
2401                         first = type;
2402                         last  = type;
2403                 } else {
2404                         last->next = type;
2405                         last       = type;
2406                 }
2407         }
2408
2409         /* TODO: find out if this is correct */
2410         parse_attributes();
2411
2412         construct_type_t *inner_types = NULL;
2413
2414         switch(token.type) {
2415         case T_IDENTIFIER:
2416                 if(declaration == NULL) {
2417                         errorf(HERE, "no identifier expected in typename");
2418                 } else {
2419                         declaration->symbol          = token.v.symbol;
2420                         declaration->source_position = token.source_position;
2421                 }
2422                 next_token();
2423                 break;
2424         case '(':
2425                 next_token();
2426                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2427                 expect(')');
2428                 break;
2429         default:
2430                 if(may_be_abstract)
2431                         break;
2432                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2433                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2434                  * eat '}' */
2435                 if(token.type == '}' && current_function == NULL) {
2436                         next_token();
2437                 } else {
2438                         eat_statement();
2439                 }
2440                 return NULL;
2441         }
2442
2443         construct_type_t *p = last;
2444
2445         while(true) {
2446                 construct_type_t *type;
2447                 switch(token.type) {
2448                 case '(':
2449                         type = parse_function_declarator(declaration);
2450                         break;
2451                 case '[':
2452                         type = parse_array_declarator();
2453                         break;
2454                 default:
2455                         goto declarator_finished;
2456                 }
2457
2458                 /* insert in the middle of the list (behind p) */
2459                 if(p != NULL) {
2460                         type->next = p->next;
2461                         p->next    = type;
2462                 } else {
2463                         type->next = first;
2464                         first      = type;
2465                 }
2466                 if(last == p) {
2467                         last = type;
2468                 }
2469         }
2470
2471 declarator_finished:
2472         parse_attributes();
2473
2474         /* append inner_types at the end of the list, we don't to set last anymore
2475          * as it's not needed anymore */
2476         if(last == NULL) {
2477                 assert(first == NULL);
2478                 first = inner_types;
2479         } else {
2480                 last->next = inner_types;
2481         }
2482
2483         return first;
2484 }
2485
2486 static type_t *construct_declarator_type(construct_type_t *construct_list,
2487                                          type_t *type)
2488 {
2489         construct_type_t *iter = construct_list;
2490         for( ; iter != NULL; iter = iter->next) {
2491                 switch(iter->kind) {
2492                 case CONSTRUCT_INVALID:
2493                         panic("invalid type construction found");
2494                 case CONSTRUCT_FUNCTION: {
2495                         construct_function_type_t *construct_function_type
2496                                 = (construct_function_type_t*) iter;
2497
2498                         type_t *function_type = construct_function_type->function_type;
2499
2500                         function_type->function.return_type = type;
2501
2502                         type_t *skipped_return_type = skip_typeref(type);
2503                         if (is_type_function(skipped_return_type)) {
2504                                 errorf(HERE, "function returning function is not allowed");
2505                                 type = type_error_type;
2506                         } else if (is_type_array(skipped_return_type)) {
2507                                 errorf(HERE, "function returning array is not allowed");
2508                                 type = type_error_type;
2509                         } else {
2510                                 type = function_type;
2511                         }
2512                         break;
2513                 }
2514
2515                 case CONSTRUCT_POINTER: {
2516                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2517                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2518                         pointer_type->pointer.points_to  = type;
2519                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2520
2521                         type = pointer_type;
2522                         break;
2523                 }
2524
2525                 case CONSTRUCT_ARRAY: {
2526                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2527                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2528
2529                         expression_t *size_expression = parsed_array->size;
2530                         if(size_expression != NULL) {
2531                                 size_expression
2532                                         = create_implicit_cast(size_expression, type_size_t);
2533                         }
2534
2535                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
2536                         array_type->array.element_type    = type;
2537                         array_type->array.is_static       = parsed_array->is_static;
2538                         array_type->array.is_variable     = parsed_array->is_variable;
2539                         array_type->array.size_expression = size_expression;
2540
2541                         if(size_expression != NULL) {
2542                                 if(is_constant_expression(size_expression)) {
2543                                         array_type->array.size_constant = true;
2544                                         array_type->array.size
2545                                                 = fold_constant(size_expression);
2546                                 } else {
2547                                         array_type->array.is_vla = true;
2548                                 }
2549                         }
2550
2551                         type_t *skipped_type = skip_typeref(type);
2552                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2553                                 errorf(HERE, "array of void is not allowed");
2554                                 type = type_error_type;
2555                         } else {
2556                                 type = array_type;
2557                         }
2558                         break;
2559                 }
2560                 }
2561
2562                 type_t *hashed_type = typehash_insert(type);
2563                 if(hashed_type != type) {
2564                         /* the function type was constructed earlier freeing it here will
2565                          * destroy other types... */
2566                         if(iter->kind != CONSTRUCT_FUNCTION) {
2567                                 free_type(type);
2568                         }
2569                         type = hashed_type;
2570                 }
2571         }
2572
2573         return type;
2574 }
2575
2576 static declaration_t *parse_declarator(
2577                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2578 {
2579         declaration_t *const declaration    = allocate_declaration_zero();
2580         declaration->declared_storage_class = specifiers->declared_storage_class;
2581         declaration->modifiers              = specifiers->decl_modifiers;
2582         declaration->is_inline              = specifiers->is_inline;
2583
2584         declaration->storage_class          = specifiers->declared_storage_class;
2585         if(declaration->storage_class == STORAGE_CLASS_NONE
2586                         && scope != global_scope) {
2587                 declaration->storage_class = STORAGE_CLASS_AUTO;
2588         }
2589
2590         construct_type_t *construct_type
2591                 = parse_inner_declarator(declaration, may_be_abstract);
2592         type_t *const type = specifiers->type;
2593         declaration->type = construct_declarator_type(construct_type, type);
2594
2595         if(construct_type != NULL) {
2596                 obstack_free(&temp_obst, construct_type);
2597         }
2598
2599         return declaration;
2600 }
2601
2602 static type_t *parse_abstract_declarator(type_t *base_type)
2603 {
2604         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2605
2606         type_t *result = construct_declarator_type(construct_type, base_type);
2607         if(construct_type != NULL) {
2608                 obstack_free(&temp_obst, construct_type);
2609         }
2610
2611         return result;
2612 }
2613
2614 static declaration_t *append_declaration(declaration_t* const declaration)
2615 {
2616         if (last_declaration != NULL) {
2617                 last_declaration->next = declaration;
2618         } else {
2619                 scope->declarations = declaration;
2620         }
2621         last_declaration = declaration;
2622         return declaration;
2623 }
2624
2625 /**
2626  * Check if the declaration of main is suspicious.  main should be a
2627  * function with external linkage, returning int, taking either zero
2628  * arguments, two, or three arguments of appropriate types, ie.
2629  *
2630  * int main([ int argc, char **argv [, char **env ] ]).
2631  *
2632  * @param decl    the declaration to check
2633  * @param type    the function type of the declaration
2634  */
2635 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2636 {
2637         if (decl->storage_class == STORAGE_CLASS_STATIC) {
2638                 warningf(decl->source_position, "'main' is normally a non-static function");
2639         }
2640         if (skip_typeref(func_type->return_type) != type_int) {
2641                 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2642         }
2643         const function_parameter_t *parm = func_type->parameters;
2644         if (parm != NULL) {
2645                 type_t *const first_type = parm->type;
2646                 if (!types_compatible(skip_typeref(first_type), type_int)) {
2647                         warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2648                 }
2649                 parm = parm->next;
2650                 if (parm != NULL) {
2651                         type_t *const second_type = parm->type;
2652                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2653                                 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2654                         }
2655                         parm = parm->next;
2656                         if (parm != NULL) {
2657                                 type_t *const third_type = parm->type;
2658                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2659                                         warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2660                                 }
2661                                 parm = parm->next;
2662                                 if (parm != NULL) {
2663                                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2664                                 }
2665                         }
2666                 } else {
2667                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2668                 }
2669         }
2670 }
2671
2672 /**
2673  * Check if a symbol is the equal to "main".
2674  */
2675 static bool is_sym_main(const symbol_t *const sym)
2676 {
2677         return strcmp(sym->string, "main") == 0;
2678 }
2679
2680 static declaration_t *internal_record_declaration(
2681         declaration_t *const declaration,
2682         const bool is_function_definition)
2683 {
2684         const symbol_t *const symbol  = declaration->symbol;
2685         const namespace_t     namespc = (namespace_t)declaration->namespc;
2686
2687         type_t *const orig_type = declaration->type;
2688         type_t *const type      = skip_typeref(orig_type);
2689         if (is_type_function(type) &&
2690                         type->function.unspecified_parameters &&
2691                         warning.strict_prototypes) {
2692                 warningf(declaration->source_position,
2693                          "function declaration '%#T' is not a prototype",
2694                          orig_type, declaration->symbol);
2695         }
2696
2697         if (is_function_definition && warning.main && is_sym_main(symbol)) {
2698                 check_type_of_main(declaration, &type->function);
2699         }
2700
2701         assert(declaration->symbol != NULL);
2702         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2703
2704         assert(declaration != previous_declaration);
2705         if (previous_declaration != NULL) {
2706                 if (previous_declaration->parent_scope == scope) {
2707                         /* can happen for K&R style declarations */
2708                         if(previous_declaration->type == NULL) {
2709                                 previous_declaration->type = declaration->type;
2710                         }
2711
2712                         const type_t *prev_type = skip_typeref(previous_declaration->type);
2713                         if (!types_compatible(type, prev_type)) {
2714                                 errorf(declaration->source_position,
2715                                        "declaration '%#T' is incompatible with "
2716                                        "previous declaration '%#T'",
2717                                        orig_type, symbol, previous_declaration->type, symbol);
2718                                 errorf(previous_declaration->source_position,
2719                                        "previous declaration of '%Y' was here", symbol);
2720                         } else {
2721                                 unsigned old_storage_class
2722                                         = previous_declaration->storage_class;
2723                                 unsigned new_storage_class = declaration->storage_class;
2724
2725                                 if(is_type_incomplete(prev_type)) {
2726                                         previous_declaration->type = type;
2727                                         prev_type                  = type;
2728                                 }
2729
2730                                 /* pretend no storage class means extern for function
2731                                  * declarations (except if the previous declaration is neither
2732                                  * none nor extern) */
2733                                 if (is_type_function(type)) {
2734                                         switch (old_storage_class) {
2735                                                 case STORAGE_CLASS_NONE:
2736                                                         old_storage_class = STORAGE_CLASS_EXTERN;
2737
2738                                                 case STORAGE_CLASS_EXTERN:
2739                                                         if (is_function_definition) {
2740                                                                 if (warning.missing_prototypes &&
2741                                                                     prev_type->function.unspecified_parameters &&
2742                                                                     !is_sym_main(symbol)) {
2743                                                                         warningf(declaration->source_position,
2744                                                                                  "no previous prototype for '%#T'",
2745                                                                                  orig_type, symbol);
2746                                                                 }
2747                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
2748                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
2749                                                         }
2750                                                         break;
2751
2752                                                 default: break;
2753                                         }
2754                                 }
2755
2756                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
2757                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
2758 warn_redundant_declaration:
2759                                         if (warning.redundant_decls) {
2760                                                 warningf(declaration->source_position,
2761                                                          "redundant declaration for '%Y'", symbol);
2762                                                 warningf(previous_declaration->source_position,
2763                                                          "previous declaration of '%Y' was here",
2764                                                          symbol);
2765                                         }
2766                                 } else if (current_function == NULL) {
2767                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
2768                                                         new_storage_class == STORAGE_CLASS_STATIC) {
2769                                                 errorf(declaration->source_position,
2770                                                        "static declaration of '%Y' follows non-static declaration",
2771                                                        symbol);
2772                                                 errorf(previous_declaration->source_position,
2773                                                        "previous declaration of '%Y' was here", symbol);
2774                                         } else {
2775                                                 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
2776                                                         goto warn_redundant_declaration;
2777                                                 }
2778                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
2779                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
2780                                                         previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
2781                                                 }
2782                                         }
2783                                 } else {
2784                                         if (old_storage_class == new_storage_class) {
2785                                                 errorf(declaration->source_position,
2786                                                        "redeclaration of '%Y'", symbol);
2787                                         } else {
2788                                                 errorf(declaration->source_position,
2789                                                        "redeclaration of '%Y' with different linkage",
2790                                                        symbol);
2791                                         }
2792                                         errorf(previous_declaration->source_position,
2793                                                "previous declaration of '%Y' was here", symbol);
2794                                 }
2795                         }
2796                         return previous_declaration;
2797                 }
2798         } else if (is_function_definition) {
2799                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
2800                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
2801                                 warningf(declaration->source_position,
2802                                          "no previous prototype for '%#T'", orig_type, symbol);
2803                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
2804                                 warningf(declaration->source_position,
2805                                          "no previous declaration for '%#T'", orig_type,
2806                                          symbol);
2807                         }
2808                 }
2809         } else if (warning.missing_declarations &&
2810             scope == global_scope &&
2811             !is_type_function(type) && (
2812               declaration->storage_class == STORAGE_CLASS_NONE ||
2813               declaration->storage_class == STORAGE_CLASS_THREAD
2814             )) {
2815                 warningf(declaration->source_position,
2816                          "no previous declaration for '%#T'", orig_type, symbol);
2817         }
2818
2819         assert(declaration->parent_scope == NULL);
2820         assert(scope != NULL);
2821
2822         declaration->parent_scope = scope;
2823
2824         environment_push(declaration);
2825         return append_declaration(declaration);
2826 }
2827
2828 static declaration_t *record_declaration(declaration_t *declaration)
2829 {
2830         return internal_record_declaration(declaration, false);
2831 }
2832
2833 static declaration_t *record_function_definition(declaration_t *declaration)
2834 {
2835         return internal_record_declaration(declaration, true);
2836 }
2837
2838 static void parser_error_multiple_definition(declaration_t *declaration,
2839                 const source_position_t source_position)
2840 {
2841         errorf(source_position, "multiple definition of symbol '%Y'",
2842                declaration->symbol);
2843         errorf(declaration->source_position,
2844                "this is the location of the previous definition.");
2845 }
2846
2847 static bool is_declaration_specifier(const token_t *token,
2848                                      bool only_type_specifiers)
2849 {
2850         switch(token->type) {
2851                 TYPE_SPECIFIERS
2852                         return true;
2853                 case T_IDENTIFIER:
2854                         return is_typedef_symbol(token->v.symbol);
2855
2856                 case T___extension__:
2857                 STORAGE_CLASSES
2858                 TYPE_QUALIFIERS
2859                         return !only_type_specifiers;
2860
2861                 default:
2862                         return false;
2863         }
2864 }
2865
2866 static void parse_init_declarator_rest(declaration_t *declaration)
2867 {
2868         eat('=');
2869
2870         type_t *orig_type = declaration->type;
2871         type_t *type      = skip_typeref(orig_type);
2872
2873         if(declaration->init.initializer != NULL) {
2874                 parser_error_multiple_definition(declaration, token.source_position);
2875         }
2876
2877         bool must_be_constant = false;
2878         if(declaration->storage_class == STORAGE_CLASS_STATIC
2879                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
2880                         || declaration->parent_scope == global_scope) {
2881                 must_be_constant = true;
2882         }
2883
2884         parse_initializer_env_t env;
2885         env.type             = orig_type;
2886         env.must_be_constant = must_be_constant;
2887         parse_initializer(&env);
2888
2889         if(env.type != orig_type) {
2890                 orig_type         = env.type;
2891                 type              = skip_typeref(orig_type);
2892                 declaration->type = env.type;
2893         }
2894
2895         if(is_type_function(type)) {
2896                 errorf(declaration->source_position,
2897                        "initializers not allowed for function types at declator '%Y' (type '%T')",
2898                        declaration->symbol, orig_type);
2899         } else {
2900                 declaration->init.initializer = env.initializer;
2901         }
2902 }
2903
2904 /* parse rest of a declaration without any declarator */
2905 static void parse_anonymous_declaration_rest(
2906                 const declaration_specifiers_t *specifiers,
2907                 parsed_declaration_func finished_declaration)
2908 {
2909         eat(';');
2910
2911         declaration_t *const declaration    = allocate_declaration_zero();
2912         declaration->type                   = specifiers->type;
2913         declaration->declared_storage_class = specifiers->declared_storage_class;
2914         declaration->source_position        = specifiers->source_position;
2915
2916         if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
2917                 warningf(declaration->source_position, "useless storage class in empty declaration");
2918         }
2919         declaration->storage_class = STORAGE_CLASS_NONE;
2920
2921         type_t *type = declaration->type;
2922         switch (type->kind) {
2923                 case TYPE_COMPOUND_STRUCT:
2924                 case TYPE_COMPOUND_UNION: {
2925                         if (type->compound.declaration->symbol == NULL) {
2926                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
2927                         }
2928                         break;
2929                 }
2930
2931                 case TYPE_ENUM:
2932                         break;
2933
2934                 default:
2935                         warningf(declaration->source_position, "empty declaration");
2936                         break;
2937         }
2938
2939         finished_declaration(declaration);
2940 }
2941
2942 static void parse_declaration_rest(declaration_t *ndeclaration,
2943                 const declaration_specifiers_t *specifiers,
2944                 parsed_declaration_func finished_declaration)
2945 {
2946         while(true) {
2947                 declaration_t *declaration = finished_declaration(ndeclaration);
2948
2949                 type_t *orig_type = declaration->type;
2950                 type_t *type      = skip_typeref(orig_type);
2951
2952                 if (type->kind != TYPE_FUNCTION &&
2953                     declaration->is_inline &&
2954                     is_type_valid(type)) {
2955                         warningf(declaration->source_position,
2956                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2957                 }
2958
2959                 if(token.type == '=') {
2960                         parse_init_declarator_rest(declaration);
2961                 }
2962
2963                 if(token.type != ',')
2964                         break;
2965                 eat(',');
2966
2967                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2968         }
2969         expect_void(';');
2970 }
2971
2972 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2973 {
2974         symbol_t *symbol  = declaration->symbol;
2975         if(symbol == NULL) {
2976                 errorf(HERE, "anonymous declaration not valid as function parameter");
2977                 return declaration;
2978         }
2979         namespace_t namespc = (namespace_t) declaration->namespc;
2980         if(namespc != NAMESPACE_NORMAL) {
2981                 return record_declaration(declaration);
2982         }
2983
2984         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2985         if(previous_declaration == NULL ||
2986                         previous_declaration->parent_scope != scope) {
2987                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2988                        symbol);
2989                 return declaration;
2990         }
2991
2992         if(previous_declaration->type == NULL) {
2993                 previous_declaration->type          = declaration->type;
2994                 previous_declaration->declared_storage_class = declaration->declared_storage_class;
2995                 previous_declaration->storage_class = declaration->storage_class;
2996                 previous_declaration->parent_scope  = scope;
2997                 return previous_declaration;
2998         } else {
2999                 return record_declaration(declaration);
3000         }
3001 }
3002
3003 static void parse_declaration(parsed_declaration_func finished_declaration)
3004 {
3005         declaration_specifiers_t specifiers;
3006         memset(&specifiers, 0, sizeof(specifiers));
3007         parse_declaration_specifiers(&specifiers);
3008
3009         if(token.type == ';') {
3010                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3011         } else {
3012                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3013                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3014         }
3015 }
3016
3017 static void parse_kr_declaration_list(declaration_t *declaration)
3018 {
3019         type_t *type = skip_typeref(declaration->type);
3020         if(!is_type_function(type))
3021                 return;
3022
3023         if(!type->function.kr_style_parameters)
3024                 return;
3025
3026         /* push function parameters */
3027         int       top        = environment_top();
3028         scope_t  *last_scope = scope;
3029         set_scope(&declaration->scope);
3030
3031         declaration_t *parameter = declaration->scope.declarations;
3032         for( ; parameter != NULL; parameter = parameter->next) {
3033                 assert(parameter->parent_scope == NULL);
3034                 parameter->parent_scope = scope;
3035                 environment_push(parameter);
3036         }
3037
3038         /* parse declaration list */
3039         while(is_declaration_specifier(&token, false)) {
3040                 parse_declaration(finished_kr_declaration);
3041         }
3042
3043         /* pop function parameters */
3044         assert(scope == &declaration->scope);
3045         set_scope(last_scope);
3046         environment_pop_to(top);
3047
3048         /* update function type */
3049         type_t *new_type = duplicate_type(type);
3050         new_type->function.kr_style_parameters = false;
3051
3052         function_parameter_t *parameters     = NULL;
3053         function_parameter_t *last_parameter = NULL;
3054
3055         declaration_t *parameter_declaration = declaration->scope.declarations;
3056         for( ; parameter_declaration != NULL;
3057                         parameter_declaration = parameter_declaration->next) {
3058                 type_t *parameter_type = parameter_declaration->type;
3059                 if(parameter_type == NULL) {
3060                         if (strict_mode) {
3061                                 errorf(HERE, "no type specified for function parameter '%Y'",
3062                                        parameter_declaration->symbol);
3063                         } else {
3064                                 if (warning.implicit_int) {
3065                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3066                                                 parameter_declaration->symbol);
3067                                 }
3068                                 parameter_type              = type_int;
3069                                 parameter_declaration->type = parameter_type;
3070                         }
3071                 }
3072
3073                 semantic_parameter(parameter_declaration);
3074                 parameter_type = parameter_declaration->type;
3075
3076                 function_parameter_t *function_parameter
3077                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3078                 memset(function_parameter, 0, sizeof(function_parameter[0]));
3079
3080                 function_parameter->type = parameter_type;
3081                 if(last_parameter != NULL) {
3082                         last_parameter->next = function_parameter;
3083                 } else {
3084                         parameters = function_parameter;
3085                 }
3086                 last_parameter = function_parameter;
3087         }
3088         new_type->function.parameters = parameters;
3089
3090         type = typehash_insert(new_type);
3091         if(type != new_type) {
3092                 obstack_free(type_obst, new_type);
3093         }
3094
3095         declaration->type = type;
3096 }
3097
3098 static bool first_err = true;
3099
3100 /**
3101  * When called with first_err set, prints the name of the current function,
3102  * else does noting.
3103  */
3104 static void print_in_function(void) {
3105         if (first_err) {
3106                 first_err = false;
3107                 diagnosticf("%s: In function '%Y':\n",
3108                         current_function->source_position.input_name,
3109                         current_function->symbol);
3110         }
3111 }
3112
3113 /**
3114  * Check if all labels are defined in the current function.
3115  * Check if all labels are used in the current function.
3116  */
3117 static void check_labels(void)
3118 {
3119         for (const goto_statement_t *goto_statement = goto_first;
3120             goto_statement != NULL;
3121             goto_statement = goto_statement->next) {
3122                 declaration_t *label = goto_statement->label;
3123
3124                 label->used = true;
3125                 if (label->source_position.input_name == NULL) {
3126                         print_in_function();
3127                         errorf(goto_statement->base.source_position,
3128                                "label '%Y' used but not defined", label->symbol);
3129                  }
3130         }
3131         goto_first = goto_last = NULL;
3132
3133         if (warning.unused_label) {
3134                 for (const label_statement_t *label_statement = label_first;
3135                          label_statement != NULL;
3136                          label_statement = label_statement->next) {
3137                         const declaration_t *label = label_statement->label;
3138
3139                         if (! label->used) {
3140                                 print_in_function();
3141                                 warningf(label_statement->base.source_position,
3142                                         "label '%Y' defined but not used", label->symbol);
3143                         }
3144                 }
3145         }
3146         label_first = label_last = NULL;
3147 }
3148
3149 /**
3150  * Check declarations of current_function for unused entities.
3151  */
3152 static void check_declarations(void)
3153 {
3154         if (warning.unused_parameter) {
3155                 const scope_t *scope = &current_function->scope;
3156
3157                 const declaration_t *parameter = scope->declarations;
3158                 for (; parameter != NULL; parameter = parameter->next) {
3159                         if (! parameter->used) {
3160                                 print_in_function();
3161                                 warningf(parameter->source_position,
3162                                         "unused parameter '%Y'", parameter->symbol);
3163                         }
3164                 }
3165         }
3166         if (warning.unused_variable) {
3167         }
3168 }
3169
3170 static void parse_external_declaration(void)
3171 {
3172         /* function-definitions and declarations both start with declaration
3173          * specifiers */
3174         declaration_specifiers_t specifiers;
3175         memset(&specifiers, 0, sizeof(specifiers));
3176         parse_declaration_specifiers(&specifiers);
3177
3178         /* must be a declaration */
3179         if(token.type == ';') {
3180                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3181                 return;
3182         }
3183
3184         /* declarator is common to both function-definitions and declarations */
3185         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3186
3187         /* must be a declaration */
3188         if(token.type == ',' || token.type == '=' || token.type == ';') {
3189                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3190                 return;
3191         }
3192
3193         /* must be a function definition */
3194         parse_kr_declaration_list(ndeclaration);
3195
3196         if(token.type != '{') {
3197                 parse_error_expected("while parsing function definition", '{', 0);
3198                 eat_statement();
3199                 return;
3200         }
3201
3202         type_t *type = ndeclaration->type;
3203
3204         /* note that we don't skip typerefs: the standard doesn't allow them here
3205          * (so we can't use is_type_function here) */
3206         if(type->kind != TYPE_FUNCTION) {
3207                 if (is_type_valid(type)) {
3208                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
3209                                type, ndeclaration->symbol);
3210                 }
3211                 eat_block();
3212                 return;
3213         }
3214
3215         /* Â§ 6.7.5.3 (14) a function definition with () means no
3216          * parameters (and not unspecified parameters) */
3217         if(type->function.unspecified_parameters) {
3218                 type_t *duplicate = duplicate_type(type);
3219                 duplicate->function.unspecified_parameters = false;
3220
3221                 type = typehash_insert(duplicate);
3222                 if(type != duplicate) {
3223                         obstack_free(type_obst, duplicate);
3224                 }
3225                 ndeclaration->type = type;
3226         }
3227
3228         declaration_t *const declaration = record_function_definition(ndeclaration);
3229         if(ndeclaration != declaration) {
3230                 declaration->scope = ndeclaration->scope;
3231         }
3232         type = skip_typeref(declaration->type);
3233
3234         /* push function parameters and switch scope */
3235         int       top        = environment_top();
3236         scope_t  *last_scope = scope;
3237         set_scope(&declaration->scope);
3238
3239         declaration_t *parameter = declaration->scope.declarations;
3240         for( ; parameter != NULL; parameter = parameter->next) {
3241                 if(parameter->parent_scope == &ndeclaration->scope) {
3242                         parameter->parent_scope = scope;
3243                 }
3244                 assert(parameter->parent_scope == NULL
3245                                 || parameter->parent_scope == scope);
3246                 parameter->parent_scope = scope;
3247                 environment_push(parameter);
3248         }
3249
3250         if(declaration->init.statement != NULL) {
3251                 parser_error_multiple_definition(declaration, token.source_position);
3252                 eat_block();
3253                 goto end_of_parse_external_declaration;
3254         } else {
3255                 /* parse function body */
3256                 int            label_stack_top      = label_top();
3257                 declaration_t *old_current_function = current_function;
3258                 current_function                    = declaration;
3259
3260                 declaration->init.statement = parse_compound_statement();
3261                 first_err = true;
3262                 check_labels();
3263                 check_declarations();
3264
3265                 assert(current_function == declaration);
3266                 current_function = old_current_function;
3267                 label_pop_to(label_stack_top);
3268         }
3269
3270 end_of_parse_external_declaration:
3271         assert(scope == &declaration->scope);
3272         set_scope(last_scope);
3273         environment_pop_to(top);
3274 }
3275
3276 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3277                                   source_position_t source_position)
3278 {
3279         type_t *type        = allocate_type_zero(TYPE_BITFIELD, source_position);
3280         type->bitfield.base = base;
3281         type->bitfield.size = size;
3282
3283         return type;
3284 }
3285
3286 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3287                                           symbol_t *symbol)
3288 {
3289         declaration_t *iter = compound_declaration->scope.declarations;
3290         for( ; iter != NULL; iter = iter->next) {
3291                 if(iter->namespc != NAMESPACE_NORMAL)
3292                         continue;
3293
3294                 if(iter->symbol == NULL) {
3295                         type_t *type = skip_typeref(iter->type);
3296                         if(is_type_compound(type)) {
3297                                 declaration_t *result
3298                                         = find_compound_entry(type->compound.declaration, symbol);
3299                                 if(result != NULL)
3300                                         return result;
3301                         }
3302                         continue;
3303                 }
3304
3305                 if(iter->symbol == symbol) {
3306                         return iter;
3307                 }
3308         }
3309
3310         return NULL;
3311 }
3312
3313 static void parse_compound_declarators(declaration_t *struct_declaration,
3314                 const declaration_specifiers_t *specifiers)
3315 {
3316         declaration_t *last_declaration = struct_declaration->scope.declarations;
3317         if(last_declaration != NULL) {
3318                 while(last_declaration->next != NULL) {
3319                         last_declaration = last_declaration->next;
3320                 }
3321         }
3322
3323         while(1) {
3324                 declaration_t *declaration;
3325
3326                 if(token.type == ':') {
3327                         source_position_t source_position = HERE;
3328                         next_token();
3329
3330                         type_t *base_type = specifiers->type;
3331                         expression_t *size = parse_constant_expression();
3332
3333                         if(!is_type_integer(skip_typeref(base_type))) {
3334                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
3335                                        base_type);
3336                         }
3337
3338                         type_t *type = make_bitfield_type(base_type, size, source_position);
3339
3340                         declaration                         = allocate_declaration_zero();
3341                         declaration->namespc                = NAMESPACE_NORMAL;
3342                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
3343                         declaration->storage_class          = STORAGE_CLASS_NONE;
3344                         declaration->source_position        = source_position;
3345                         declaration->modifiers              = specifiers->decl_modifiers;
3346                         declaration->type                   = type;
3347                 } else {
3348                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3349
3350                         type_t *orig_type = declaration->type;
3351                         type_t *type      = skip_typeref(orig_type);
3352
3353                         if(token.type == ':') {
3354                                 source_position_t source_position = HERE;
3355                                 next_token();
3356                                 expression_t *size = parse_constant_expression();
3357
3358                                 if(!is_type_integer(type)) {
3359                                         errorf(HERE, "bitfield base type '%T' is not an "
3360                                                "integer type", orig_type);
3361                                 }
3362
3363                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3364                                 declaration->type = bitfield_type;
3365                         } else {
3366                                 /* TODO we ignore arrays for now... what is missing is a check
3367                                  * that they're at the end of the struct */
3368                                 if(is_type_incomplete(type) && !is_type_array(type)) {
3369                                         errorf(HERE,
3370                                                "compound member '%Y' has incomplete type '%T'",
3371                                                declaration->symbol, orig_type);
3372                                 } else if(is_type_function(type)) {
3373                                         errorf(HERE, "compound member '%Y' must not have function "
3374                                                "type '%T'", declaration->symbol, orig_type);
3375                                 }
3376                         }
3377                 }
3378
3379                 /* make sure we don't define a symbol multiple times */
3380                 symbol_t *symbol = declaration->symbol;
3381                 if(symbol != NULL) {
3382                         declaration_t *prev_decl
3383                                 = find_compound_entry(struct_declaration, symbol);
3384
3385                         if(prev_decl != NULL) {
3386                                 assert(prev_decl->symbol == symbol);
3387                                 errorf(declaration->source_position,
3388                                        "multiple declarations of symbol '%Y'", symbol);
3389                                 errorf(prev_decl->source_position,
3390                                        "previous declaration of '%Y' was here", symbol);
3391                         }
3392                 }
3393
3394                 /* append declaration */
3395                 if(last_declaration != NULL) {
3396                         last_declaration->next = declaration;
3397                 } else {
3398                         struct_declaration->scope.declarations = declaration;
3399                 }
3400                 last_declaration = declaration;
3401
3402                 if(token.type != ',')
3403                         break;
3404                 next_token();
3405         }
3406         expect_void(';');
3407 }
3408
3409 static void parse_compound_type_entries(declaration_t *compound_declaration)
3410 {
3411         eat('{');
3412
3413         while(token.type != '}' && token.type != T_EOF) {
3414                 declaration_specifiers_t specifiers;
3415                 memset(&specifiers, 0, sizeof(specifiers));
3416                 parse_declaration_specifiers(&specifiers);
3417
3418                 parse_compound_declarators(compound_declaration, &specifiers);
3419         }
3420         if(token.type == T_EOF) {
3421                 errorf(HERE, "EOF while parsing struct");
3422         }
3423         next_token();
3424 }
3425
3426 static type_t *parse_typename(void)
3427 {
3428         declaration_specifiers_t specifiers;
3429         memset(&specifiers, 0, sizeof(specifiers));
3430         parse_declaration_specifiers(&specifiers);
3431         if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3432                 /* TODO: improve error message, user does probably not know what a
3433                  * storage class is...
3434                  */
3435                 errorf(HERE, "typename may not have a storage class");
3436         }
3437
3438         type_t *result = parse_abstract_declarator(specifiers.type);
3439
3440         return result;
3441 }
3442
3443
3444
3445
3446 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3447 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3448                                                           expression_t *left);
3449
3450 typedef struct expression_parser_function_t expression_parser_function_t;
3451 struct expression_parser_function_t {
3452         unsigned                         precedence;
3453         parse_expression_function        parser;
3454         unsigned                         infix_precedence;
3455         parse_expression_infix_function  infix_parser;
3456 };
3457
3458 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3459
3460 /**
3461  * Creates a new invalid expression.
3462  */
3463 static expression_t *create_invalid_expression(void)
3464 {
3465         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
3466         expression->base.source_position = token.source_position;
3467         return expression;
3468 }
3469
3470 /**
3471  * Prints an error message if an expression was expected but not read
3472  */
3473 static expression_t *expected_expression_error(void)
3474 {
3475         /* skip the error message if the error token was read */
3476         if (token.type != T_ERROR) {
3477                 errorf(HERE, "expected expression, got token '%K'", &token);
3478         }
3479         next_token();
3480
3481         return create_invalid_expression();
3482 }
3483
3484 /**
3485  * Parse a string constant.
3486  */
3487 static expression_t *parse_string_const(void)
3488 {
3489         wide_string_t wres;
3490         if (token.type == T_STRING_LITERAL) {
3491                 string_t res = token.v.string;
3492                 next_token();
3493                 while (token.type == T_STRING_LITERAL) {
3494                         res = concat_strings(&res, &token.v.string);
3495                         next_token();
3496                 }
3497                 if (token.type != T_WIDE_STRING_LITERAL) {
3498                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3499                         /* note: that we use type_char_ptr here, which is already the
3500                          * automatic converted type. revert_automatic_type_conversion
3501                          * will construct the array type */
3502                         cnst->base.type    = type_char_ptr;
3503                         cnst->string.value = res;
3504                         return cnst;
3505                 }
3506
3507                 wres = concat_string_wide_string(&res, &token.v.wide_string);
3508         } else {
3509                 wres = token.v.wide_string;
3510         }
3511         next_token();
3512
3513         for (;;) {
3514                 switch (token.type) {
3515                         case T_WIDE_STRING_LITERAL:
3516                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
3517                                 break;
3518
3519                         case T_STRING_LITERAL:
3520                                 wres = concat_wide_string_string(&wres, &token.v.string);
3521                                 break;
3522
3523                         default: {
3524                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3525                                 cnst->base.type         = type_wchar_t_ptr;
3526                                 cnst->wide_string.value = wres;
3527                                 return cnst;
3528                         }
3529                 }
3530                 next_token();
3531         }
3532 }
3533
3534 /**
3535  * Parse an integer constant.
3536  */
3537 static expression_t *parse_int_const(void)
3538 {
3539         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3540         cnst->base.source_position = HERE;
3541         cnst->base.type            = token.datatype;
3542         cnst->conste.v.int_value   = token.v.intvalue;
3543
3544         next_token();
3545
3546         return cnst;
3547 }
3548
3549 /**
3550  * Parse a character constant.
3551  */
3552 static expression_t *parse_character_constant(void)
3553 {
3554         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3555
3556         cnst->base.source_position = HERE;
3557         cnst->base.type            = token.datatype;
3558         cnst->conste.v.character   = token.v.string;
3559
3560         if (cnst->conste.v.character.size != 1) {
3561                 if (warning.multichar && (c_mode & _GNUC)) {
3562                         /* TODO */
3563                         warningf(HERE, "multi-character character constant");
3564                 } else {
3565                         errorf(HERE, "more than 1 characters in character constant");
3566                 }
3567         }
3568         next_token();
3569
3570         return cnst;
3571 }
3572
3573 /**
3574  * Parse a wide character constant.
3575  */
3576 static expression_t *parse_wide_character_constant(void)
3577 {
3578         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3579
3580         cnst->base.source_position    = HERE;
3581         cnst->base.type               = token.datatype;
3582         cnst->conste.v.wide_character = token.v.wide_string;
3583
3584         if (cnst->conste.v.wide_character.size != 1) {
3585                 if (warning.multichar && (c_mode & _GNUC)) {
3586                         /* TODO */
3587                         warningf(HERE, "multi-character character constant");
3588                 } else {
3589                         errorf(HERE, "more than 1 characters in character constant");
3590                 }
3591         }
3592         next_token();
3593
3594         return cnst;
3595 }
3596
3597 /**
3598  * Parse a float constant.
3599  */
3600 static expression_t *parse_float_const(void)
3601 {
3602         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3603         cnst->base.type            = token.datatype;
3604         cnst->conste.v.float_value = token.v.floatvalue;
3605
3606         next_token();
3607
3608         return cnst;
3609 }
3610
3611 static declaration_t *create_implicit_function(symbol_t *symbol,
3612                 const source_position_t source_position)
3613 {
3614         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
3615         ntype->function.return_type            = type_int;
3616         ntype->function.unspecified_parameters = true;
3617
3618         type_t *type = typehash_insert(ntype);
3619         if(type != ntype) {
3620                 free_type(ntype);
3621         }
3622
3623         declaration_t *const declaration    = allocate_declaration_zero();
3624         declaration->storage_class          = STORAGE_CLASS_EXTERN;
3625         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
3626         declaration->type                   = type;
3627         declaration->symbol                 = symbol;
3628         declaration->source_position        = source_position;
3629         declaration->parent_scope           = global_scope;
3630
3631         scope_t *old_scope = scope;
3632         set_scope(global_scope);
3633
3634         environment_push(declaration);
3635         /* prepends the declaration to the global declarations list */
3636         declaration->next   = scope->declarations;
3637         scope->declarations = declaration;
3638
3639         assert(scope == global_scope);
3640         set_scope(old_scope);
3641
3642         return declaration;
3643 }
3644
3645 /**
3646  * Creates a return_type (func)(argument_type) function type if not
3647  * already exists.
3648  *
3649  * @param return_type    the return type
3650  * @param argument_type  the argument type
3651  */
3652 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3653 {
3654         function_parameter_t *parameter
3655                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3656         memset(parameter, 0, sizeof(parameter[0]));
3657         parameter->type = argument_type;
3658
3659         type_t *type               = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3660         type->function.return_type = return_type;
3661         type->function.parameters  = parameter;
3662
3663         type_t *result = typehash_insert(type);
3664         if(result != type) {
3665                 free_type(type);
3666         }
3667
3668         return result;
3669 }
3670
3671 /**
3672  * Creates a function type for some function like builtins.
3673  *
3674  * @param symbol   the symbol describing the builtin
3675  */
3676 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3677 {
3678         switch(symbol->ID) {
3679         case T___builtin_alloca:
3680                 return make_function_1_type(type_void_ptr, type_size_t);
3681         case T___builtin_nan:
3682                 return make_function_1_type(type_double, type_char_ptr);
3683         case T___builtin_nanf:
3684                 return make_function_1_type(type_float, type_char_ptr);
3685         case T___builtin_nand:
3686                 return make_function_1_type(type_long_double, type_char_ptr);
3687         case T___builtin_va_end:
3688                 return make_function_1_type(type_void, type_valist);
3689         default:
3690                 panic("not implemented builtin symbol found");
3691         }
3692 }
3693
3694 /**
3695  * Performs automatic type cast as described in Â§ 6.3.2.1.
3696  *
3697  * @param orig_type  the original type
3698  */
3699 static type_t *automatic_type_conversion(type_t *orig_type)
3700 {
3701         type_t *type = skip_typeref(orig_type);
3702         if(is_type_array(type)) {
3703                 array_type_t *array_type   = &type->array;
3704                 type_t       *element_type = array_type->element_type;
3705                 unsigned      qualifiers   = array_type->type.qualifiers;
3706
3707                 return make_pointer_type(element_type, qualifiers);
3708         }
3709
3710         if(is_type_function(type)) {
3711                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3712         }
3713
3714         return orig_type;
3715 }
3716
3717 /**
3718  * reverts the automatic casts of array to pointer types and function
3719  * to function-pointer types as defined Â§ 6.3.2.1
3720  */
3721 type_t *revert_automatic_type_conversion(const expression_t *expression)
3722 {
3723         switch (expression->kind) {
3724                 case EXPR_REFERENCE: return expression->reference.declaration->type;
3725                 case EXPR_SELECT:    return expression->select.compound_entry->type;
3726
3727                 case EXPR_UNARY_DEREFERENCE: {
3728                         const expression_t *const value = expression->unary.value;
3729                         type_t             *const type  = skip_typeref(value->base.type);
3730                         assert(is_type_pointer(type));
3731                         return type->pointer.points_to;
3732                 }
3733
3734                 case EXPR_BUILTIN_SYMBOL:
3735                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3736
3737                 case EXPR_ARRAY_ACCESS: {
3738                         const expression_t *array_ref = expression->array_access.array_ref;
3739                         type_t             *type_left = skip_typeref(array_ref->base.type);
3740                         if (!is_type_valid(type_left))
3741                                 return type_left;
3742                         assert(is_type_pointer(type_left));
3743                         return type_left->pointer.points_to;
3744                 }
3745
3746                 case EXPR_STRING_LITERAL: {
3747                         size_t size = expression->string.value.size;
3748                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
3749                 }
3750
3751                 case EXPR_WIDE_STRING_LITERAL: {
3752                         size_t size = expression->wide_string.value.size;
3753                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
3754                 }
3755
3756                 case EXPR_COMPOUND_LITERAL:
3757                         return expression->compound_literal.type;
3758
3759                 default: break;
3760         }
3761
3762         return expression->base.type;
3763 }
3764
3765 static expression_t *parse_reference(void)
3766 {
3767         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3768
3769         reference_expression_t *ref = &expression->reference;
3770         ref->symbol = token.v.symbol;
3771
3772         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3773
3774         source_position_t source_position = token.source_position;
3775         next_token();
3776
3777         if(declaration == NULL) {
3778                 if (! strict_mode && token.type == '(') {
3779                         /* an implicitly defined function */
3780                         if (warning.implicit_function_declaration) {
3781                                 warningf(HERE, "implicit declaration of function '%Y'",
3782                                         ref->symbol);
3783                         }
3784
3785                         declaration = create_implicit_function(ref->symbol,
3786                                                                source_position);
3787                 } else {
3788                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3789                         return create_invalid_expression();
3790                 }
3791         }
3792
3793         type_t *type         = declaration->type;
3794
3795         /* we always do the auto-type conversions; the & and sizeof parser contains
3796          * code to revert this! */
3797         type = automatic_type_conversion(type);
3798
3799         ref->declaration = declaration;
3800         ref->base.type   = type;
3801
3802         /* this declaration is used */
3803         declaration->used = true;
3804
3805         return expression;
3806 }
3807
3808 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3809 {
3810         (void) expression;
3811         (void) dest_type;
3812         /* TODO check if explicit cast is allowed and issue warnings/errors */
3813 }
3814
3815 static expression_t *parse_compound_literal(type_t *type)
3816 {
3817         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
3818
3819         parse_initializer_env_t env;
3820         env.type             = type;
3821         env.must_be_constant = false;
3822         parse_initializer(&env);
3823         type = env.type;
3824
3825         expression->compound_literal.type        = type;
3826         expression->compound_literal.initializer = env.initializer;
3827         expression->base.type                    = automatic_type_conversion(type);
3828
3829         return expression;
3830 }
3831
3832 static expression_t *parse_cast(void)
3833 {
3834         source_position_t source_position = token.source_position;
3835
3836         type_t *type  = parse_typename();
3837
3838         expect(')');
3839
3840         if(token.type == '{') {
3841                 return parse_compound_literal(type);
3842         }
3843
3844         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3845         cast->base.source_position = source_position;
3846
3847         expression_t *value = parse_sub_expression(20);
3848
3849         check_cast_allowed(value, type);
3850
3851         cast->base.type   = type;
3852         cast->unary.value = value;
3853
3854         return cast;
3855 }
3856
3857 static expression_t *parse_statement_expression(void)
3858 {
3859         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3860
3861         statement_t *statement           = parse_compound_statement();
3862         expression->statement.statement  = statement;
3863         expression->base.source_position = statement->base.source_position;
3864
3865         /* find last statement and use its type */
3866         type_t *type = type_void;
3867         const statement_t *stmt = statement->compound.statements;
3868         if (stmt != NULL) {
3869                 while (stmt->base.next != NULL)
3870                         stmt = stmt->base.next;
3871
3872                 if (stmt->kind == STATEMENT_EXPRESSION) {
3873                         type = stmt->expression.expression->base.type;
3874                 }
3875         } else {
3876                 warningf(expression->base.source_position, "empty statement expression ({})");
3877         }
3878         expression->base.type = type;
3879
3880         expect(')');
3881
3882         return expression;
3883 }
3884
3885 static expression_t *parse_brace_expression(void)
3886 {
3887         eat('(');
3888
3889         switch(token.type) {
3890         case '{':
3891                 /* gcc extension: a statement expression */
3892                 return parse_statement_expression();
3893
3894         TYPE_QUALIFIERS
3895         TYPE_SPECIFIERS
3896                 return parse_cast();
3897         case T_IDENTIFIER:
3898                 if(is_typedef_symbol(token.v.symbol)) {
3899                         return parse_cast();
3900                 }
3901         }
3902
3903         expression_t *result = parse_expression();
3904         expect(')');
3905
3906         return result;
3907 }
3908
3909 static expression_t *parse_function_keyword(void)
3910 {
3911         next_token();
3912         /* TODO */
3913
3914         if (current_function == NULL) {
3915                 errorf(HERE, "'__func__' used outside of a function");
3916         }
3917
3918         expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
3919         expression->base.type    = type_char_ptr;
3920
3921         return expression;
3922 }
3923
3924 static expression_t *parse_pretty_function_keyword(void)
3925 {
3926         eat(T___PRETTY_FUNCTION__);
3927         /* TODO */
3928
3929         if (current_function == NULL) {
3930                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3931         }
3932
3933         expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
3934         expression->base.type    = type_char_ptr;
3935
3936         return expression;
3937 }
3938
3939 static designator_t *parse_designator(void)
3940 {
3941         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
3942         result->source_position = HERE;
3943
3944         if(token.type != T_IDENTIFIER) {
3945                 parse_error_expected("while parsing member designator",
3946                                      T_IDENTIFIER, 0);
3947                 eat_paren();
3948                 return NULL;
3949         }
3950         result->symbol = token.v.symbol;
3951         next_token();
3952
3953         designator_t *last_designator = result;
3954         while(true) {
3955                 if(token.type == '.') {
3956                         next_token();
3957                         if(token.type != T_IDENTIFIER) {
3958                                 parse_error_expected("while parsing member designator",
3959                                                      T_IDENTIFIER, 0);
3960                                 eat_paren();
3961                                 return NULL;
3962                         }
3963                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3964                         designator->source_position = HERE;
3965                         designator->symbol          = token.v.symbol;
3966                         next_token();
3967
3968                         last_designator->next = designator;
3969                         last_designator       = designator;
3970                         continue;
3971                 }
3972                 if(token.type == '[') {
3973                         next_token();
3974                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3975                         designator->source_position = HERE;
3976                         designator->array_index     = parse_expression();
3977                         if(designator->array_index == NULL) {
3978                                 eat_paren();
3979                                 return NULL;
3980                         }
3981                         expect(']');
3982
3983                         last_designator->next = designator;
3984                         last_designator       = designator;
3985                         continue;
3986                 }
3987                 break;
3988         }
3989
3990         return result;
3991 }
3992
3993 static expression_t *parse_offsetof(void)
3994 {
3995         eat(T___builtin_offsetof);
3996
3997         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
3998         expression->base.type    = type_size_t;
3999
4000         expect('(');
4001         type_t *type = parse_typename();
4002         expect(',');
4003         designator_t *designator = parse_designator();
4004         expect(')');
4005
4006         expression->offsetofe.type       = type;
4007         expression->offsetofe.designator = designator;
4008
4009         type_path_t path;
4010         memset(&path, 0, sizeof(path));
4011         path.top_type = type;
4012         path.path     = NEW_ARR_F(type_path_entry_t, 0);
4013
4014         descend_into_subtype(&path);
4015
4016         if(!walk_designator(&path, designator, true)) {
4017                 return create_invalid_expression();
4018         }
4019
4020         DEL_ARR_F(path.path);
4021
4022         return expression;
4023 }
4024
4025 static expression_t *parse_va_start(void)
4026 {
4027         eat(T___builtin_va_start);
4028
4029         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4030
4031         expect('(');
4032         expression->va_starte.ap = parse_assignment_expression();
4033         expect(',');
4034         expression_t *const expr = parse_assignment_expression();
4035         if (expr->kind == EXPR_REFERENCE) {
4036                 declaration_t *const decl = expr->reference.declaration;
4037                 if (decl == NULL)
4038                         return create_invalid_expression();
4039                 if (decl->parent_scope == &current_function->scope &&
4040                     decl->next == NULL) {
4041                         expression->va_starte.parameter = decl;
4042                         expect(')');
4043                         return expression;
4044                 }
4045         }
4046         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4047
4048         return create_invalid_expression();
4049 }
4050
4051 static expression_t *parse_va_arg(void)
4052 {
4053         eat(T___builtin_va_arg);
4054
4055         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4056
4057         expect('(');
4058         expression->va_arge.ap = parse_assignment_expression();
4059         expect(',');
4060         expression->base.type = parse_typename();
4061         expect(')');
4062
4063         return expression;
4064 }
4065
4066 static expression_t *parse_builtin_symbol(void)
4067 {
4068         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4069
4070         symbol_t *symbol = token.v.symbol;
4071
4072         expression->builtin_symbol.symbol = symbol;
4073         next_token();
4074
4075         type_t *type = get_builtin_symbol_type(symbol);
4076         type = automatic_type_conversion(type);
4077
4078         expression->base.type = type;
4079         return expression;
4080 }
4081
4082 static expression_t *parse_builtin_constant(void)
4083 {
4084         eat(T___builtin_constant_p);
4085
4086         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4087
4088         expect('(');
4089         expression->builtin_constant.value = parse_assignment_expression();
4090         expect(')');
4091         expression->base.type = type_int;
4092
4093         return expression;
4094 }
4095
4096 static expression_t *parse_builtin_prefetch(void)
4097 {
4098         eat(T___builtin_prefetch);
4099
4100         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4101
4102         expect('(');
4103         expression->builtin_prefetch.adr = parse_assignment_expression();
4104         if (token.type == ',') {
4105                 next_token();
4106                 expression->builtin_prefetch.rw = parse_assignment_expression();
4107         }
4108         if (token.type == ',') {
4109                 next_token();
4110                 expression->builtin_prefetch.locality = parse_assignment_expression();
4111         }
4112         expect(')');
4113         expression->base.type = type_void;
4114
4115         return expression;
4116 }
4117
4118 static expression_t *parse_compare_builtin(void)
4119 {
4120         expression_t *expression;
4121
4122         switch(token.type) {
4123         case T___builtin_isgreater:
4124                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4125                 break;
4126         case T___builtin_isgreaterequal:
4127                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4128                 break;
4129         case T___builtin_isless:
4130                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4131                 break;
4132         case T___builtin_islessequal:
4133                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4134                 break;
4135         case T___builtin_islessgreater:
4136                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4137                 break;
4138         case T___builtin_isunordered:
4139                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4140                 break;
4141         default:
4142                 panic("invalid compare builtin found");
4143                 break;
4144         }
4145         expression->base.source_position = HERE;
4146         next_token();
4147
4148         expect('(');
4149         expression->binary.left = parse_assignment_expression();
4150         expect(',');
4151         expression->binary.right = parse_assignment_expression();
4152         expect(')');
4153
4154         type_t *const orig_type_left  = expression->binary.left->base.type;
4155         type_t *const orig_type_right = expression->binary.right->base.type;
4156
4157         type_t *const type_left  = skip_typeref(orig_type_left);
4158         type_t *const type_right = skip_typeref(orig_type_right);
4159         if(!is_type_float(type_left) && !is_type_float(type_right)) {
4160                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4161                         type_error_incompatible("invalid operands in comparison",
4162                                 expression->base.source_position, orig_type_left, orig_type_right);
4163                 }
4164         } else {
4165                 semantic_comparison(&expression->binary);
4166         }
4167
4168         return expression;
4169 }
4170
4171 static expression_t *parse_builtin_expect(void)
4172 {
4173         eat(T___builtin_expect);
4174
4175         expression_t *expression
4176                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4177
4178         expect('(');
4179         expression->binary.left = parse_assignment_expression();
4180         expect(',');
4181         expression->binary.right = parse_constant_expression();
4182         expect(')');
4183
4184         expression->base.type = expression->binary.left->base.type;
4185
4186         return expression;
4187 }
4188
4189 static expression_t *parse_assume(void) {
4190         eat(T_assume);
4191
4192         expression_t *expression
4193                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4194
4195         expect('(');
4196         expression->unary.value = parse_assignment_expression();
4197         expect(')');
4198
4199         expression->base.type = type_void;
4200         return expression;
4201 }
4202
4203 static expression_t *parse_primary_expression(void)
4204 {
4205         switch (token.type) {
4206                 case T_INTEGER:                  return parse_int_const();
4207                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
4208                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
4209                 case T_FLOATINGPOINT:            return parse_float_const();
4210                 case T_STRING_LITERAL:
4211                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
4212                 case T_IDENTIFIER:               return parse_reference();
4213                 case T___FUNCTION__:
4214                 case T___func__:                 return parse_function_keyword();
4215                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
4216                 case T___builtin_offsetof:       return parse_offsetof();
4217                 case T___builtin_va_start:       return parse_va_start();
4218                 case T___builtin_va_arg:         return parse_va_arg();
4219                 case T___builtin_expect:         return parse_builtin_expect();
4220                 case T___builtin_alloca:
4221                 case T___builtin_nan:
4222                 case T___builtin_nand:
4223                 case T___builtin_nanf:
4224                 case T___builtin_va_end:         return parse_builtin_symbol();
4225                 case T___builtin_isgreater:
4226                 case T___builtin_isgreaterequal:
4227                 case T___builtin_isless:
4228                 case T___builtin_islessequal:
4229                 case T___builtin_islessgreater:
4230                 case T___builtin_isunordered:    return parse_compare_builtin();
4231                 case T___builtin_constant_p:     return parse_builtin_constant();
4232                 case T___builtin_prefetch:       return parse_builtin_prefetch();
4233                 case T_assume:                   return parse_assume();
4234
4235                 case '(':                        return parse_brace_expression();
4236         }
4237
4238         errorf(HERE, "unexpected token %K, expected an expression", &token);
4239         eat_statement();
4240
4241         return create_invalid_expression();
4242 }
4243
4244 /**
4245  * Check if the expression has the character type and issue a warning then.
4246  */
4247 static void check_for_char_index_type(const expression_t *expression) {
4248         type_t       *const type      = expression->base.type;
4249         const type_t *const base_type = skip_typeref(type);
4250
4251         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4252                         warning.char_subscripts) {
4253                 warningf(expression->base.source_position,
4254                         "array subscript has type '%T'", type);
4255         }
4256 }
4257
4258 static expression_t *parse_array_expression(unsigned precedence,
4259                                             expression_t *left)
4260 {
4261         (void) precedence;
4262
4263         eat('[');
4264
4265         expression_t *inside = parse_expression();
4266
4267         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4268
4269         array_access_expression_t *array_access = &expression->array_access;
4270
4271         type_t *const orig_type_left   = left->base.type;
4272         type_t *const orig_type_inside = inside->base.type;
4273
4274         type_t *const type_left   = skip_typeref(orig_type_left);
4275         type_t *const type_inside = skip_typeref(orig_type_inside);
4276
4277         type_t *return_type;
4278         if (is_type_pointer(type_left)) {
4279                 return_type             = type_left->pointer.points_to;
4280                 array_access->array_ref = left;
4281                 array_access->index     = inside;
4282                 check_for_char_index_type(inside);
4283         } else if (is_type_pointer(type_inside)) {
4284                 return_type             = type_inside->pointer.points_to;
4285                 array_access->array_ref = inside;
4286                 array_access->index     = left;
4287                 array_access->flipped   = true;
4288                 check_for_char_index_type(left);
4289         } else {
4290                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4291                         errorf(HERE,
4292                                 "array access on object with non-pointer types '%T', '%T'",
4293                                 orig_type_left, orig_type_inside);
4294                 }
4295                 return_type             = type_error_type;
4296                 array_access->array_ref = create_invalid_expression();
4297         }
4298
4299         if(token.type != ']') {
4300                 parse_error_expected("Problem while parsing array access", ']', 0);
4301                 return expression;
4302         }
4303         next_token();
4304
4305         return_type           = automatic_type_conversion(return_type);
4306         expression->base.type = return_type;
4307
4308         return expression;
4309 }
4310
4311 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4312 {
4313         expression_t *tp_expression = allocate_expression_zero(kind);
4314         tp_expression->base.type    = type_size_t;
4315
4316         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4317                 next_token();
4318                 tp_expression->typeprop.type = parse_typename();
4319                 expect(')');
4320         } else {
4321                 expression_t *expression = parse_sub_expression(precedence);
4322                 expression->base.type    = revert_automatic_type_conversion(expression);
4323
4324                 tp_expression->typeprop.type          = expression->base.type;
4325                 tp_expression->typeprop.tp_expression = expression;
4326         }
4327
4328         return tp_expression;
4329 }
4330
4331 static expression_t *parse_sizeof(unsigned precedence)
4332 {
4333         eat(T_sizeof);
4334         return parse_typeprop(EXPR_SIZEOF, precedence);
4335 }
4336
4337 static expression_t *parse_alignof(unsigned precedence)
4338 {
4339         eat(T___alignof__);
4340         return parse_typeprop(EXPR_SIZEOF, precedence);
4341 }
4342
4343 static expression_t *parse_select_expression(unsigned precedence,
4344                                              expression_t *compound)
4345 {
4346         (void) precedence;
4347         assert(token.type == '.' || token.type == T_MINUSGREATER);
4348
4349         bool is_pointer = (token.type == T_MINUSGREATER);
4350         next_token();
4351
4352         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
4353         select->select.compound = compound;
4354
4355         if(token.type != T_IDENTIFIER) {
4356                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4357                 return select;
4358         }
4359         symbol_t *symbol      = token.v.symbol;
4360         select->select.symbol = symbol;
4361         next_token();
4362
4363         type_t *const orig_type = compound->base.type;
4364         type_t *const type      = skip_typeref(orig_type);
4365
4366         type_t *type_left = type;
4367         if(is_pointer) {
4368                 if (!is_type_pointer(type)) {
4369                         if (is_type_valid(type)) {
4370                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4371                         }
4372                         return create_invalid_expression();
4373                 }
4374                 type_left = type->pointer.points_to;
4375         }
4376         type_left = skip_typeref(type_left);
4377
4378         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4379             type_left->kind != TYPE_COMPOUND_UNION) {
4380                 if (is_type_valid(type_left)) {
4381                         errorf(HERE, "request for member '%Y' in something not a struct or "
4382                                "union, but '%T'", symbol, type_left);
4383                 }
4384                 return create_invalid_expression();
4385         }
4386
4387         declaration_t *const declaration = type_left->compound.declaration;
4388
4389         if(!declaration->init.is_defined) {
4390                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4391                        symbol, type_left);
4392                 return create_invalid_expression();
4393         }
4394
4395         declaration_t *iter = find_compound_entry(declaration, symbol);
4396         if(iter == NULL) {
4397                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4398                 return create_invalid_expression();
4399         }
4400
4401         /* we always do the auto-type conversions; the & and sizeof parser contains
4402          * code to revert this! */
4403         type_t *expression_type = automatic_type_conversion(iter->type);
4404
4405         select->select.compound_entry = iter;
4406         select->base.type             = expression_type;
4407
4408         if(expression_type->kind == TYPE_BITFIELD) {
4409                 expression_t *extract
4410                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4411                 extract->unary.value = select;
4412                 extract->base.type   = expression_type->bitfield.base;
4413
4414                 return extract;
4415         }
4416
4417         return select;
4418 }
4419
4420 /**
4421  * Parse a call expression, ie. expression '( ... )'.
4422  *
4423  * @param expression  the function address
4424  */
4425 static expression_t *parse_call_expression(unsigned precedence,
4426                                            expression_t *expression)
4427 {
4428         (void) precedence;
4429         expression_t *result = allocate_expression_zero(EXPR_CALL);
4430
4431         call_expression_t *call = &result->call;
4432         call->function          = expression;
4433
4434         type_t *const orig_type = expression->base.type;
4435         type_t *const type      = skip_typeref(orig_type);
4436
4437         function_type_t *function_type = NULL;
4438         if (is_type_pointer(type)) {
4439                 type_t *const to_type = skip_typeref(type->pointer.points_to);
4440
4441                 if (is_type_function(to_type)) {
4442                         function_type   = &to_type->function;
4443                         call->base.type = function_type->return_type;
4444                 }
4445         }
4446
4447         if (function_type == NULL && is_type_valid(type)) {
4448                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4449         }
4450
4451         /* parse arguments */
4452         eat('(');
4453
4454         if(token.type != ')') {
4455                 call_argument_t *last_argument = NULL;
4456
4457                 while(true) {
4458                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4459
4460                         argument->expression = parse_assignment_expression();
4461                         if(last_argument == NULL) {
4462                                 call->arguments = argument;
4463                         } else {
4464                                 last_argument->next = argument;
4465                         }
4466                         last_argument = argument;
4467
4468                         if(token.type != ',')
4469                                 break;
4470                         next_token();
4471                 }
4472         }
4473         expect(')');
4474
4475         if(function_type != NULL) {
4476                 function_parameter_t *parameter = function_type->parameters;
4477                 call_argument_t      *argument  = call->arguments;
4478                 for( ; parameter != NULL && argument != NULL;
4479                                 parameter = parameter->next, argument = argument->next) {
4480                         type_t *expected_type = parameter->type;
4481                         /* TODO report scope in error messages */
4482                         expression_t *const arg_expr = argument->expression;
4483                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4484                         if (res_type == NULL) {
4485                                 /* TODO improve error message */
4486                                 errorf(arg_expr->base.source_position,
4487                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4488                                         arg_expr, arg_expr->base.type, expected_type);
4489                         } else {
4490                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
4491                         }
4492                 }
4493                 /* too few parameters */
4494                 if(parameter != NULL) {
4495                         errorf(HERE, "too few arguments to function '%E'", expression);
4496                 } else if(argument != NULL) {
4497                         /* too many parameters */
4498                         if(!function_type->variadic
4499                                         && !function_type->unspecified_parameters) {
4500                                 errorf(HERE, "too many arguments to function '%E'", expression);
4501                         } else {
4502                                 /* do default promotion */
4503                                 for( ; argument != NULL; argument = argument->next) {
4504                                         type_t *type = argument->expression->base.type;
4505
4506                                         type = skip_typeref(type);
4507                                         if(is_type_integer(type)) {
4508                                                 type = promote_integer(type);
4509                                         } else if(type == type_float) {
4510                                                 type = type_double;
4511                                         }
4512
4513                                         argument->expression
4514                                                 = create_implicit_cast(argument->expression, type);
4515                                 }
4516
4517                                 check_format(&result->call);
4518                         }
4519                 } else {
4520                         check_format(&result->call);
4521                 }
4522         }
4523
4524         return result;
4525 }
4526
4527 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4528
4529 static bool same_compound_type(const type_t *type1, const type_t *type2)
4530 {
4531         return
4532                 is_type_compound(type1) &&
4533                 type1->kind == type2->kind &&
4534                 type1->compound.declaration == type2->compound.declaration;
4535 }
4536
4537 /**
4538  * Parse a conditional expression, ie. 'expression ? ... : ...'.
4539  *
4540  * @param expression  the conditional expression
4541  */
4542 static expression_t *parse_conditional_expression(unsigned precedence,
4543                                                   expression_t *expression)
4544 {
4545         eat('?');
4546
4547         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4548
4549         conditional_expression_t *conditional = &result->conditional;
4550         conditional->condition = expression;
4551
4552         /* 6.5.15.2 */
4553         type_t *const condition_type_orig = expression->base.type;
4554         type_t *const condition_type      = skip_typeref(condition_type_orig);
4555         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4556                 type_error("expected a scalar type in conditional condition",
4557                            expression->base.source_position, condition_type_orig);
4558         }
4559
4560         expression_t *true_expression = parse_expression();
4561         expect(':');
4562         expression_t *false_expression = parse_sub_expression(precedence);
4563
4564         type_t *const orig_true_type  = true_expression->base.type;
4565         type_t *const orig_false_type = false_expression->base.type;
4566         type_t *const true_type       = skip_typeref(orig_true_type);
4567         type_t *const false_type      = skip_typeref(orig_false_type);
4568
4569         /* 6.5.15.3 */
4570         type_t *result_type;
4571         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4572                 result_type = semantic_arithmetic(true_type, false_type);
4573
4574                 true_expression  = create_implicit_cast(true_expression, result_type);
4575                 false_expression = create_implicit_cast(false_expression, result_type);
4576
4577                 conditional->true_expression  = true_expression;
4578                 conditional->false_expression = false_expression;
4579                 conditional->base.type        = result_type;
4580         } else if (same_compound_type(true_type, false_type) || (
4581             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4582             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4583                 )) {
4584                 /* just take 1 of the 2 types */
4585                 result_type = true_type;
4586         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4587                         && pointers_compatible(true_type, false_type)) {
4588                 /* ok */
4589                 result_type = true_type;
4590         } else if (is_type_pointer(true_type)
4591                         && is_null_pointer_constant(false_expression)) {
4592                 result_type = true_type;
4593         } else if (is_type_pointer(false_type)
4594                         && is_null_pointer_constant(true_expression)) {
4595                 result_type = false_type;
4596         } else {
4597                 /* TODO: one pointer to void*, other some pointer */
4598
4599                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4600                         type_error_incompatible("while parsing conditional",
4601                                                 expression->base.source_position, true_type,
4602                                                 false_type);
4603                 }
4604                 result_type = type_error_type;
4605         }
4606
4607         conditional->true_expression
4608                 = create_implicit_cast(true_expression, result_type);
4609         conditional->false_expression
4610                 = create_implicit_cast(false_expression, result_type);
4611         conditional->base.type = result_type;
4612         return result;
4613 }
4614
4615 /**
4616  * Parse an extension expression.
4617  */
4618 static expression_t *parse_extension(unsigned precedence)
4619 {
4620         eat(T___extension__);
4621
4622         /* TODO enable extensions */
4623         expression_t *expression = parse_sub_expression(precedence);
4624         /* TODO disable extensions */
4625         return expression;
4626 }
4627
4628 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4629 {
4630         eat(T___builtin_classify_type);
4631
4632         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4633         result->base.type    = type_int;
4634
4635         expect('(');
4636         expression_t *expression = parse_sub_expression(precedence);
4637         expect(')');
4638         result->classify_type.type_expression = expression;
4639
4640         return result;
4641 }
4642
4643 static void semantic_incdec(unary_expression_t *expression)
4644 {
4645         type_t *const orig_type = expression->value->base.type;
4646         type_t *const type      = skip_typeref(orig_type);
4647         /* TODO !is_type_real && !is_type_pointer */
4648         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4649                 if (is_type_valid(type)) {
4650                         /* TODO: improve error message */
4651                         errorf(HERE, "operation needs an arithmetic or pointer type");
4652                 }
4653                 return;
4654         }
4655
4656         expression->base.type = orig_type;
4657 }
4658
4659 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4660 {
4661         type_t *const orig_type = expression->value->base.type;
4662         type_t *const type      = skip_typeref(orig_type);
4663         if(!is_type_arithmetic(type)) {
4664                 if (is_type_valid(type)) {
4665                         /* TODO: improve error message */
4666                         errorf(HERE, "operation needs an arithmetic type");
4667                 }
4668                 return;
4669         }
4670
4671         expression->base.type = orig_type;
4672 }
4673
4674 static void semantic_unexpr_scalar(unary_expression_t *expression)
4675 {
4676         type_t *const orig_type = expression->value->base.type;
4677         type_t *const type      = skip_typeref(orig_type);
4678         if (!is_type_scalar(type)) {
4679                 if (is_type_valid(type)) {
4680                         errorf(HERE, "operand of ! must be of scalar type");
4681                 }
4682                 return;
4683         }
4684
4685         expression->base.type = orig_type;
4686 }
4687
4688 static void semantic_unexpr_integer(unary_expression_t *expression)
4689 {
4690         type_t *const orig_type = expression->value->base.type;
4691         type_t *const type      = skip_typeref(orig_type);
4692         if (!is_type_integer(type)) {
4693                 if (is_type_valid(type)) {
4694                         errorf(HERE, "operand of ~ must be of integer type");
4695                 }
4696                 return;
4697         }
4698
4699         expression->base.type = orig_type;
4700 }
4701
4702 static void semantic_dereference(unary_expression_t *expression)
4703 {
4704         type_t *const orig_type = expression->value->base.type;
4705         type_t *const type      = skip_typeref(orig_type);
4706         if(!is_type_pointer(type)) {
4707                 if (is_type_valid(type)) {
4708                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4709                 }
4710                 return;
4711         }
4712
4713         type_t *result_type   = type->pointer.points_to;
4714         result_type           = automatic_type_conversion(result_type);
4715         expression->base.type = result_type;
4716 }
4717
4718 /**
4719  * Check the semantic of the address taken expression.
4720  */
4721 static void semantic_take_addr(unary_expression_t *expression)
4722 {
4723         expression_t *value = expression->value;
4724         value->base.type    = revert_automatic_type_conversion(value);
4725
4726         type_t *orig_type = value->base.type;
4727         if(!is_type_valid(orig_type))
4728                 return;
4729
4730         if(value->kind == EXPR_REFERENCE) {
4731                 declaration_t *const declaration = value->reference.declaration;
4732                 if(declaration != NULL) {
4733                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4734                                 errorf(expression->base.source_position,
4735                                         "address of register variable '%Y' requested",
4736                                         declaration->symbol);
4737                         }
4738                         declaration->address_taken = 1;
4739                 }
4740         }
4741
4742         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4743 }
4744
4745 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4746 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4747 {                                                                              \
4748         eat(token_type);                                                           \
4749                                                                                    \
4750         expression_t *unary_expression                                             \
4751                 = allocate_expression_zero(unexpression_type);                         \
4752         unary_expression->base.source_position = HERE;                             \
4753         unary_expression->unary.value = parse_sub_expression(precedence);          \
4754                                                                                    \
4755         sfunc(&unary_expression->unary);                                           \
4756                                                                                    \
4757         return unary_expression;                                                   \
4758 }
4759
4760 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4761                                semantic_unexpr_arithmetic)
4762 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4763                                semantic_unexpr_arithmetic)
4764 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4765                                semantic_unexpr_scalar)
4766 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4767                                semantic_dereference)
4768 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4769                                semantic_take_addr)
4770 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4771                                semantic_unexpr_integer)
4772 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4773                                semantic_incdec)
4774 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4775                                semantic_incdec)
4776
4777 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4778                                                sfunc)                         \
4779 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4780                                                expression_t *left)            \
4781 {                                                                             \
4782         (void) precedence;                                                        \
4783         eat(token_type);                                                          \
4784                                                                               \
4785         expression_t *unary_expression                                            \
4786                 = allocate_expression_zero(unexpression_type);                        \
4787         unary_expression->unary.value = left;                                     \
4788                                                                                   \
4789         sfunc(&unary_expression->unary);                                          \
4790                                                                               \
4791         return unary_expression;                                                  \
4792 }
4793
4794 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4795                                        EXPR_UNARY_POSTFIX_INCREMENT,
4796                                        semantic_incdec)
4797 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4798                                        EXPR_UNARY_POSTFIX_DECREMENT,
4799                                        semantic_incdec)
4800
4801 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4802 {
4803         /* TODO: handle complex + imaginary types */
4804
4805         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4806         if(type_left == type_long_double || type_right == type_long_double) {
4807                 return type_long_double;
4808         } else if(type_left == type_double || type_right == type_double) {
4809                 return type_double;
4810         } else if(type_left == type_float || type_right == type_float) {
4811                 return type_float;
4812         }
4813
4814         type_right = promote_integer(type_right);
4815         type_left  = promote_integer(type_left);
4816
4817         if(type_left == type_right)
4818                 return type_left;
4819
4820         bool signed_left  = is_type_signed(type_left);
4821         bool signed_right = is_type_signed(type_right);
4822         int  rank_left    = get_rank(type_left);
4823         int  rank_right   = get_rank(type_right);
4824         if(rank_left < rank_right) {
4825                 if(signed_left == signed_right || !signed_right) {
4826                         return type_right;
4827                 } else {
4828                         return type_left;
4829                 }
4830         } else {
4831                 if(signed_left == signed_right || !signed_left) {
4832                         return type_left;
4833                 } else {
4834                         return type_right;
4835                 }
4836         }
4837 }
4838
4839 /**
4840  * Check the semantic restrictions for a binary expression.
4841  */
4842 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4843 {
4844         expression_t *const left            = expression->left;
4845         expression_t *const right           = expression->right;
4846         type_t       *const orig_type_left  = left->base.type;
4847         type_t       *const orig_type_right = right->base.type;
4848         type_t       *const type_left       = skip_typeref(orig_type_left);
4849         type_t       *const type_right      = skip_typeref(orig_type_right);
4850
4851         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4852                 /* TODO: improve error message */
4853                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4854                         errorf(HERE, "operation needs arithmetic types");
4855                 }
4856                 return;
4857         }
4858
4859         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4860         expression->left      = create_implicit_cast(left, arithmetic_type);
4861         expression->right     = create_implicit_cast(right, arithmetic_type);
4862         expression->base.type = arithmetic_type;
4863 }
4864
4865 static void semantic_shift_op(binary_expression_t *expression)
4866 {
4867         expression_t *const left            = expression->left;
4868         expression_t *const right           = expression->right;
4869         type_t       *const orig_type_left  = left->base.type;
4870         type_t       *const orig_type_right = right->base.type;
4871         type_t       *      type_left       = skip_typeref(orig_type_left);
4872         type_t       *      type_right      = skip_typeref(orig_type_right);
4873
4874         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4875                 /* TODO: improve error message */
4876                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4877                         errorf(HERE, "operation needs integer types");
4878                 }
4879                 return;
4880         }
4881
4882         type_left  = promote_integer(type_left);
4883         type_right = promote_integer(type_right);
4884
4885         expression->left      = create_implicit_cast(left, type_left);
4886         expression->right     = create_implicit_cast(right, type_right);
4887         expression->base.type = type_left;
4888 }
4889
4890 static void semantic_add(binary_expression_t *expression)
4891 {
4892         expression_t *const left            = expression->left;
4893         expression_t *const right           = expression->right;
4894         type_t       *const orig_type_left  = left->base.type;
4895         type_t       *const orig_type_right = right->base.type;
4896         type_t       *const type_left       = skip_typeref(orig_type_left);
4897         type_t       *const type_right      = skip_typeref(orig_type_right);
4898
4899         /* Â§ 5.6.5 */
4900         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4901                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4902                 expression->left  = create_implicit_cast(left, arithmetic_type);
4903                 expression->right = create_implicit_cast(right, arithmetic_type);
4904                 expression->base.type = arithmetic_type;
4905                 return;
4906         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4907                 expression->base.type = type_left;
4908         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4909                 expression->base.type = type_right;
4910         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4911                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4912         }
4913 }
4914
4915 static void semantic_sub(binary_expression_t *expression)
4916 {
4917         expression_t *const left            = expression->left;
4918         expression_t *const right           = expression->right;
4919         type_t       *const orig_type_left  = left->base.type;
4920         type_t       *const orig_type_right = right->base.type;
4921         type_t       *const type_left       = skip_typeref(orig_type_left);
4922         type_t       *const type_right      = skip_typeref(orig_type_right);
4923
4924         /* Â§ 5.6.5 */
4925         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4926                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4927                 expression->left        = create_implicit_cast(left, arithmetic_type);
4928                 expression->right       = create_implicit_cast(right, arithmetic_type);
4929                 expression->base.type =  arithmetic_type;
4930                 return;
4931         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4932                 expression->base.type = type_left;
4933         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4934                 if(!pointers_compatible(type_left, type_right)) {
4935                         errorf(HERE,
4936                                "pointers to incompatible objects to binary '-' ('%T', '%T')",
4937                                orig_type_left, orig_type_right);
4938                 } else {
4939                         expression->base.type = type_ptrdiff_t;
4940                 }
4941         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4942                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
4943                        orig_type_left, orig_type_right);
4944         }
4945 }
4946
4947 /**
4948  * Check the semantics of comparison expressions.
4949  *
4950  * @param expression   The expression to check.
4951  */
4952 static void semantic_comparison(binary_expression_t *expression)
4953 {
4954         expression_t *left            = expression->left;
4955         expression_t *right           = expression->right;
4956         type_t       *orig_type_left  = left->base.type;
4957         type_t       *orig_type_right = right->base.type;
4958
4959         type_t *type_left  = skip_typeref(orig_type_left);
4960         type_t *type_right = skip_typeref(orig_type_right);
4961
4962         /* TODO non-arithmetic types */
4963         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4964                 if (warning.sign_compare &&
4965                     (expression->base.kind != EXPR_BINARY_EQUAL &&
4966                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
4967                     (is_type_signed(type_left) != is_type_signed(type_right))) {
4968                         warningf(expression->base.source_position,
4969                                  "comparison between signed and unsigned");
4970                 }
4971                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4972                 expression->left        = create_implicit_cast(left, arithmetic_type);
4973                 expression->right       = create_implicit_cast(right, arithmetic_type);
4974                 expression->base.type   = arithmetic_type;
4975                 if (warning.float_equal &&
4976                     (expression->base.kind == EXPR_BINARY_EQUAL ||
4977                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
4978                     is_type_float(arithmetic_type)) {
4979                         warningf(expression->base.source_position,
4980                                  "comparing floating point with == or != is unsafe");
4981                 }
4982         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4983                 /* TODO check compatibility */
4984         } else if (is_type_pointer(type_left)) {
4985                 expression->right = create_implicit_cast(right, type_left);
4986         } else if (is_type_pointer(type_right)) {
4987                 expression->left = create_implicit_cast(left, type_right);
4988         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4989                 type_error_incompatible("invalid operands in comparison",
4990                                         expression->base.source_position,
4991                                         type_left, type_right);
4992         }
4993         expression->base.type = type_int;
4994 }
4995
4996 static void semantic_arithmetic_assign(binary_expression_t *expression)
4997 {
4998         expression_t *left            = expression->left;
4999         expression_t *right           = expression->right;
5000         type_t       *orig_type_left  = left->base.type;
5001         type_t       *orig_type_right = right->base.type;
5002
5003         type_t *type_left  = skip_typeref(orig_type_left);
5004         type_t *type_right = skip_typeref(orig_type_right);
5005
5006         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5007                 /* TODO: improve error message */
5008                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5009                         errorf(HERE, "operation needs arithmetic types");
5010                 }
5011                 return;
5012         }
5013
5014         /* combined instructions are tricky. We can't create an implicit cast on
5015          * the left side, because we need the uncasted form for the store.
5016          * The ast2firm pass has to know that left_type must be right_type
5017          * for the arithmetic operation and create a cast by itself */
5018         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5019         expression->right       = create_implicit_cast(right, arithmetic_type);
5020         expression->base.type   = type_left;
5021 }
5022
5023 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5024 {
5025         expression_t *const left            = expression->left;
5026         expression_t *const right           = expression->right;
5027         type_t       *const orig_type_left  = left->base.type;
5028         type_t       *const orig_type_right = right->base.type;
5029         type_t       *const type_left       = skip_typeref(orig_type_left);
5030         type_t       *const type_right      = skip_typeref(orig_type_right);
5031
5032         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5033                 /* combined instructions are tricky. We can't create an implicit cast on
5034                  * the left side, because we need the uncasted form for the store.
5035                  * The ast2firm pass has to know that left_type must be right_type
5036                  * for the arithmetic operation and create a cast by itself */
5037                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5038                 expression->right     = create_implicit_cast(right, arithmetic_type);
5039                 expression->base.type = type_left;
5040         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5041                 expression->base.type = type_left;
5042         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5043                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5044         }
5045 }
5046
5047 /**
5048  * Check the semantic restrictions of a logical expression.
5049  */
5050 static void semantic_logical_op(binary_expression_t *expression)
5051 {
5052         expression_t *const left            = expression->left;
5053         expression_t *const right           = expression->right;
5054         type_t       *const orig_type_left  = left->base.type;
5055         type_t       *const orig_type_right = right->base.type;
5056         type_t       *const type_left       = skip_typeref(orig_type_left);
5057         type_t       *const type_right      = skip_typeref(orig_type_right);
5058
5059         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5060                 /* TODO: improve error message */
5061                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5062                         errorf(HERE, "operation needs scalar types");
5063                 }
5064                 return;
5065         }
5066
5067         expression->base.type = type_int;
5068 }
5069
5070 /**
5071  * Checks if a compound type has constant fields.
5072  */
5073 static bool has_const_fields(const compound_type_t *type)
5074 {
5075         const scope_t       *scope       = &type->declaration->scope;
5076         const declaration_t *declaration = scope->declarations;
5077
5078         for (; declaration != NULL; declaration = declaration->next) {
5079                 if (declaration->namespc != NAMESPACE_NORMAL)
5080                         continue;
5081
5082                 const type_t *decl_type = skip_typeref(declaration->type);
5083                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5084                         return true;
5085         }
5086         /* TODO */
5087         return false;
5088 }
5089
5090 /**
5091  * Check the semantic restrictions of a binary assign expression.
5092  */
5093 static void semantic_binexpr_assign(binary_expression_t *expression)
5094 {
5095         expression_t *left           = expression->left;
5096         type_t       *orig_type_left = left->base.type;
5097
5098         type_t *type_left = revert_automatic_type_conversion(left);
5099         type_left         = skip_typeref(orig_type_left);
5100
5101         /* must be a modifiable lvalue */
5102         if (is_type_array(type_left)) {
5103                 errorf(HERE, "cannot assign to arrays ('%E')", left);
5104                 return;
5105         }
5106         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5107                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5108                        orig_type_left);
5109                 return;
5110         }
5111         if(is_type_incomplete(type_left)) {
5112                 errorf(HERE,
5113                        "left-hand side of assignment '%E' has incomplete type '%T'",
5114                        left, orig_type_left);
5115                 return;
5116         }
5117         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5118                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5119                        left, orig_type_left);
5120                 return;
5121         }
5122
5123         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5124                                                  "assignment");
5125         if (res_type == NULL) {
5126                 errorf(expression->base.source_position,
5127                         "cannot assign to '%T' from '%T'",
5128                         orig_type_left, expression->right->base.type);
5129         } else {
5130                 expression->right = create_implicit_cast(expression->right, res_type);
5131         }
5132
5133         expression->base.type = orig_type_left;
5134 }
5135
5136 /**
5137  * Determine if the outermost operation (or parts thereof) of the given
5138  * expression has no effect in order to generate a warning about this fact.
5139  * Therefore in some cases this only examines some of the operands of the
5140  * expression (see comments in the function and examples below).
5141  * Examples:
5142  *   f() + 23;    // warning, because + has no effect
5143  *   x || f();    // no warning, because x controls execution of f()
5144  *   x ? y : f(); // warning, because y has no effect
5145  *   (void)x;     // no warning to be able to suppress the warning
5146  * This function can NOT be used for an "expression has definitely no effect"-
5147  * analysis. */
5148 static bool expression_has_effect(const expression_t *const expr)
5149 {
5150         switch (expr->kind) {
5151                 case EXPR_UNKNOWN:                   break;
5152                 case EXPR_INVALID:                   break;
5153                 case EXPR_REFERENCE:                 return false;
5154                 case EXPR_CONST:                     return false;
5155                 case EXPR_CHARACTER_CONSTANT:        return false;
5156                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
5157                 case EXPR_STRING_LITERAL:            return false;
5158                 case EXPR_WIDE_STRING_LITERAL:       return false;
5159
5160                 case EXPR_CALL: {
5161                         const call_expression_t *const call = &expr->call;
5162                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5163                                 return true;
5164
5165                         switch (call->function->builtin_symbol.symbol->ID) {
5166                                 case T___builtin_va_end: return true;
5167                                 default:                 return false;
5168                         }
5169                 }
5170
5171                 /* Generate the warning if either the left or right hand side of a
5172                  * conditional expression has no effect */
5173                 case EXPR_CONDITIONAL: {
5174                         const conditional_expression_t *const cond = &expr->conditional;
5175                         return
5176                                 expression_has_effect(cond->true_expression) &&
5177                                 expression_has_effect(cond->false_expression);
5178                 }
5179
5180                 case EXPR_SELECT:                    return false;
5181                 case EXPR_ARRAY_ACCESS:              return false;
5182                 case EXPR_SIZEOF:                    return false;
5183                 case EXPR_CLASSIFY_TYPE:             return false;
5184                 case EXPR_ALIGNOF:                   return false;
5185
5186                 case EXPR_FUNCTION:                  return false;
5187                 case EXPR_PRETTY_FUNCTION:           return false;
5188                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
5189                 case EXPR_BUILTIN_CONSTANT_P:        return false;
5190                 case EXPR_BUILTIN_PREFETCH:          return true;
5191                 case EXPR_OFFSETOF:                  return false;
5192                 case EXPR_VA_START:                  return true;
5193                 case EXPR_VA_ARG:                    return true;
5194                 case EXPR_STATEMENT:                 return true; // TODO
5195                 case EXPR_COMPOUND_LITERAL:          return false;
5196
5197                 case EXPR_UNARY_NEGATE:              return false;
5198                 case EXPR_UNARY_PLUS:                return false;
5199                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
5200                 case EXPR_UNARY_NOT:                 return false;
5201                 case EXPR_UNARY_DEREFERENCE:         return false;
5202                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
5203                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
5204                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
5205                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
5206                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
5207
5208                 /* Treat void casts as if they have an effect in order to being able to
5209                  * suppress the warning */
5210                 case EXPR_UNARY_CAST: {
5211                         type_t *const type = skip_typeref(expr->base.type);
5212                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
5213                 }
5214
5215                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
5216                 case EXPR_UNARY_ASSUME:              return true;
5217                 case EXPR_UNARY_BITFIELD_EXTRACT:    return false;
5218
5219                 case EXPR_BINARY_ADD:                return false;
5220                 case EXPR_BINARY_SUB:                return false;
5221                 case EXPR_BINARY_MUL:                return false;
5222                 case EXPR_BINARY_DIV:                return false;
5223                 case EXPR_BINARY_MOD:                return false;
5224                 case EXPR_BINARY_EQUAL:              return false;
5225                 case EXPR_BINARY_NOTEQUAL:           return false;
5226                 case EXPR_BINARY_LESS:               return false;
5227                 case EXPR_BINARY_LESSEQUAL:          return false;
5228                 case EXPR_BINARY_GREATER:            return false;
5229                 case EXPR_BINARY_GREATEREQUAL:       return false;
5230                 case EXPR_BINARY_BITWISE_AND:        return false;
5231                 case EXPR_BINARY_BITWISE_OR:         return false;
5232                 case EXPR_BINARY_BITWISE_XOR:        return false;
5233                 case EXPR_BINARY_SHIFTLEFT:          return false;
5234                 case EXPR_BINARY_SHIFTRIGHT:         return false;
5235                 case EXPR_BINARY_ASSIGN:             return true;
5236                 case EXPR_BINARY_MUL_ASSIGN:         return true;
5237                 case EXPR_BINARY_DIV_ASSIGN:         return true;
5238                 case EXPR_BINARY_MOD_ASSIGN:         return true;
5239                 case EXPR_BINARY_ADD_ASSIGN:         return true;
5240                 case EXPR_BINARY_SUB_ASSIGN:         return true;
5241                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
5242                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
5243                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5244                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5245                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
5246
5247                 /* Only examine the right hand side of && and ||, because the left hand
5248                  * side already has the effect of controlling the execution of the right
5249                  * hand side */
5250                 case EXPR_BINARY_LOGICAL_AND:
5251                 case EXPR_BINARY_LOGICAL_OR:
5252                 /* Only examine the right hand side of a comma expression, because the left
5253                  * hand side has a separate warning */
5254                 case EXPR_BINARY_COMMA:
5255                         return expression_has_effect(expr->binary.right);
5256
5257                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
5258                 case EXPR_BINARY_ISGREATER:          return false;
5259                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
5260                 case EXPR_BINARY_ISLESS:             return false;
5261                 case EXPR_BINARY_ISLESSEQUAL:        return false;
5262                 case EXPR_BINARY_ISLESSGREATER:      return false;
5263                 case EXPR_BINARY_ISUNORDERED:        return false;
5264         }
5265
5266         panic("unexpected statement");
5267 }
5268
5269 static void semantic_comma(binary_expression_t *expression)
5270 {
5271         if (warning.unused_value) {
5272                 const expression_t *const left = expression->left;
5273                 if (!expression_has_effect(left)) {
5274                         warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5275                 }
5276         }
5277         expression->base.type = expression->right->base.type;
5278 }
5279
5280 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
5281 static expression_t *parse_##binexpression_type(unsigned precedence,      \
5282                                                 expression_t *left)       \
5283 {                                                                         \
5284         eat(token_type);                                                      \
5285         source_position_t pos = HERE;                                         \
5286                                                                           \
5287         expression_t *right = parse_sub_expression(precedence + lr);          \
5288                                                                           \
5289         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5290         binexpr->base.source_position = pos;                                  \
5291         binexpr->binary.left  = left;                                         \
5292         binexpr->binary.right = right;                                        \
5293         sfunc(&binexpr->binary);                                              \
5294                                                                           \
5295         return binexpr;                                                       \
5296 }
5297
5298 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
5299 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
5300 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
5301 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
5302 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
5303 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
5304 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
5305 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
5306 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
5307
5308 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
5309                       semantic_comparison, 1)
5310 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5311                       semantic_comparison, 1)
5312 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
5313                       semantic_comparison, 1)
5314 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
5315                       semantic_comparison, 1)
5316
5317 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5318                       semantic_binexpr_arithmetic, 1)
5319 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5320                       semantic_binexpr_arithmetic, 1)
5321 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5322                       semantic_binexpr_arithmetic, 1)
5323 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5324                       semantic_logical_op, 1)
5325 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5326                       semantic_logical_op, 1)
5327 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5328                       semantic_shift_op, 1)
5329 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5330                       semantic_shift_op, 1)
5331 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5332                       semantic_arithmetic_addsubb_assign, 0)
5333 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5334                       semantic_arithmetic_addsubb_assign, 0)
5335 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5336                       semantic_arithmetic_assign, 0)
5337 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5338                       semantic_arithmetic_assign, 0)
5339 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5340                       semantic_arithmetic_assign, 0)
5341 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5342                       semantic_arithmetic_assign, 0)
5343 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5344                       semantic_arithmetic_assign, 0)
5345 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5346                       semantic_arithmetic_assign, 0)
5347 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5348                       semantic_arithmetic_assign, 0)
5349 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5350                       semantic_arithmetic_assign, 0)
5351
5352 static expression_t *parse_sub_expression(unsigned precedence)
5353 {
5354         if(token.type < 0) {
5355                 return expected_expression_error();
5356         }
5357
5358         expression_parser_function_t *parser
5359                 = &expression_parsers[token.type];
5360         source_position_t             source_position = token.source_position;
5361         expression_t                 *left;
5362
5363         if(parser->parser != NULL) {
5364                 left = parser->parser(parser->precedence);
5365         } else {
5366                 left = parse_primary_expression();
5367         }
5368         assert(left != NULL);
5369         left->base.source_position = source_position;
5370
5371         while(true) {
5372                 if(token.type < 0) {
5373                         return expected_expression_error();
5374                 }
5375
5376                 parser = &expression_parsers[token.type];
5377                 if(parser->infix_parser == NULL)
5378                         break;
5379                 if(parser->infix_precedence < precedence)
5380                         break;
5381
5382                 left = parser->infix_parser(parser->infix_precedence, left);
5383
5384                 assert(left != NULL);
5385                 assert(left->kind != EXPR_UNKNOWN);
5386                 left->base.source_position = source_position;
5387         }
5388
5389         return left;
5390 }
5391
5392 /**
5393  * Parse an expression.
5394  */
5395 static expression_t *parse_expression(void)
5396 {
5397         return parse_sub_expression(1);
5398 }
5399
5400 /**
5401  * Register a parser for a prefix-like operator with given precedence.
5402  *
5403  * @param parser      the parser function
5404  * @param token_type  the token type of the prefix token
5405  * @param precedence  the precedence of the operator
5406  */
5407 static void register_expression_parser(parse_expression_function parser,
5408                                        int token_type, unsigned precedence)
5409 {
5410         expression_parser_function_t *entry = &expression_parsers[token_type];
5411
5412         if(entry->parser != NULL) {
5413                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5414                 panic("trying to register multiple expression parsers for a token");
5415         }
5416         entry->parser     = parser;
5417         entry->precedence = precedence;
5418 }
5419
5420 /**
5421  * Register a parser for an infix operator with given precedence.
5422  *
5423  * @param parser      the parser function
5424  * @param token_type  the token type of the infix operator
5425  * @param precedence  the precedence of the operator
5426  */
5427 static void register_infix_parser(parse_expression_infix_function parser,
5428                 int token_type, unsigned precedence)
5429 {
5430         expression_parser_function_t *entry = &expression_parsers[token_type];
5431
5432         if(entry->infix_parser != NULL) {
5433                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5434                 panic("trying to register multiple infix expression parsers for a "
5435                       "token");
5436         }
5437         entry->infix_parser     = parser;
5438         entry->infix_precedence = precedence;
5439 }
5440
5441 /**
5442  * Initialize the expression parsers.
5443  */
5444 static void init_expression_parsers(void)
5445 {
5446         memset(&expression_parsers, 0, sizeof(expression_parsers));
5447
5448         register_infix_parser(parse_array_expression,         '[',              30);
5449         register_infix_parser(parse_call_expression,          '(',              30);
5450         register_infix_parser(parse_select_expression,        '.',              30);
5451         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
5452         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5453                                                               T_PLUSPLUS,       30);
5454         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5455                                                               T_MINUSMINUS,     30);
5456
5457         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
5458         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
5459         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
5460         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
5461         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
5462         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
5463         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
5464         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
5465         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
5466         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
5467         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
5468         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
5469         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5470                                                     T_EXCLAMATIONMARKEQUAL, 13);
5471         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
5472         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
5473         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
5474         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
5475         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
5476         register_infix_parser(parse_conditional_expression,   '?',               7);
5477         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
5478         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
5479         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
5480         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
5481         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
5482         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
5483         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5484                                                                 T_LESSLESSEQUAL, 2);
5485         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5486                                                           T_GREATERGREATEREQUAL, 2);
5487         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5488                                                                      T_ANDEQUAL, 2);
5489         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5490                                                                     T_PIPEEQUAL, 2);
5491         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5492                                                                    T_CARETEQUAL, 2);
5493
5494         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
5495
5496         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
5497         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
5498         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
5499         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
5500         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
5501         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
5502         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5503                                                                   T_PLUSPLUS,   25);
5504         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5505                                                                   T_MINUSMINUS, 25);
5506         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
5507         register_expression_parser(parse_alignof,                T___alignof__, 25);
5508         register_expression_parser(parse_extension,            T___extension__, 25);
5509         register_expression_parser(parse_builtin_classify_type,
5510                                                      T___builtin_classify_type, 25);
5511 }
5512
5513 /**
5514  * Parse a asm statement constraints specification.
5515  */
5516 static asm_constraint_t *parse_asm_constraints(void)
5517 {
5518         asm_constraint_t *result = NULL;
5519         asm_constraint_t *last   = NULL;
5520
5521         while(token.type == T_STRING_LITERAL || token.type == '[') {
5522                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5523                 memset(constraint, 0, sizeof(constraint[0]));
5524
5525                 if(token.type == '[') {
5526                         eat('[');
5527                         if(token.type != T_IDENTIFIER) {
5528                                 parse_error_expected("while parsing asm constraint",
5529                                                      T_IDENTIFIER, 0);
5530                                 return NULL;
5531                         }
5532                         constraint->symbol = token.v.symbol;
5533
5534                         expect(']');
5535                 }
5536
5537                 constraint->constraints = parse_string_literals();
5538                 expect('(');
5539                 constraint->expression = parse_expression();
5540                 expect(')');
5541
5542                 if(last != NULL) {
5543                         last->next = constraint;
5544                 } else {
5545                         result = constraint;
5546                 }
5547                 last = constraint;
5548
5549                 if(token.type != ',')
5550                         break;
5551                 eat(',');
5552         }
5553
5554         return result;
5555 }
5556
5557 /**
5558  * Parse a asm statement clobber specification.
5559  */
5560 static asm_clobber_t *parse_asm_clobbers(void)
5561 {
5562         asm_clobber_t *result = NULL;
5563         asm_clobber_t *last   = NULL;
5564
5565         while(token.type == T_STRING_LITERAL) {
5566                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5567                 clobber->clobber       = parse_string_literals();
5568
5569                 if(last != NULL) {
5570                         last->next = clobber;
5571                 } else {
5572                         result = clobber;
5573                 }
5574                 last = clobber;
5575
5576                 if(token.type != ',')
5577                         break;
5578                 eat(',');
5579         }
5580
5581         return result;
5582 }
5583
5584 /**
5585  * Parse an asm statement.
5586  */
5587 static statement_t *parse_asm_statement(void)
5588 {
5589         eat(T_asm);
5590
5591         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
5592         statement->base.source_position = token.source_position;
5593
5594         asm_statement_t *asm_statement = &statement->asms;
5595
5596         if(token.type == T_volatile) {
5597                 next_token();
5598                 asm_statement->is_volatile = true;
5599         }
5600
5601         expect('(');
5602         asm_statement->asm_text = parse_string_literals();
5603
5604         if(token.type != ':')
5605                 goto end_of_asm;
5606         eat(':');
5607
5608         asm_statement->inputs = parse_asm_constraints();
5609         if(token.type != ':')
5610                 goto end_of_asm;
5611         eat(':');
5612
5613         asm_statement->outputs = parse_asm_constraints();
5614         if(token.type != ':')
5615                 goto end_of_asm;
5616         eat(':');
5617
5618         asm_statement->clobbers = parse_asm_clobbers();
5619
5620 end_of_asm:
5621         expect(')');
5622         expect(';');
5623         return statement;
5624 }
5625
5626 /**
5627  * Parse a case statement.
5628  */
5629 static statement_t *parse_case_statement(void)
5630 {
5631         eat(T_case);
5632
5633         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5634
5635         statement->base.source_position  = token.source_position;
5636         statement->case_label.expression = parse_expression();
5637
5638         if (c_mode & _GNUC) {
5639                 if (token.type == T_DOTDOTDOT) {
5640                         next_token();
5641                         statement->case_label.end_range = parse_expression();
5642                 }
5643         }
5644
5645         expect(':');
5646
5647         if (! is_constant_expression(statement->case_label.expression)) {
5648                 errorf(statement->base.source_position,
5649                         "case label does not reduce to an integer constant");
5650         } else {
5651                 /* TODO: check if the case label is already known */
5652                 if (current_switch != NULL) {
5653                         /* link all cases into the switch statement */
5654                         if (current_switch->last_case == NULL) {
5655                                 current_switch->first_case =
5656                                 current_switch->last_case  = &statement->case_label;
5657                         } else {
5658                                 current_switch->last_case->next = &statement->case_label;
5659                         }
5660                 } else {
5661                         errorf(statement->base.source_position,
5662                                 "case label not within a switch statement");
5663                 }
5664         }
5665         statement->case_label.statement = parse_statement();
5666
5667         return statement;
5668 }
5669
5670 /**
5671  * Finds an existing default label of a switch statement.
5672  */
5673 static case_label_statement_t *
5674 find_default_label(const switch_statement_t *statement)
5675 {
5676         case_label_statement_t *label = statement->first_case;
5677         for ( ; label != NULL; label = label->next) {
5678                 if (label->expression == NULL)
5679                         return label;
5680         }
5681         return NULL;
5682 }
5683
5684 /**
5685  * Parse a default statement.
5686  */
5687 static statement_t *parse_default_statement(void)
5688 {
5689         eat(T_default);
5690
5691         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5692
5693         statement->base.source_position = token.source_position;
5694
5695         expect(':');
5696         if (current_switch != NULL) {
5697                 const case_label_statement_t *def_label = find_default_label(current_switch);
5698                 if (def_label != NULL) {
5699                         errorf(HERE, "multiple default labels in one switch");
5700                         errorf(def_label->base.source_position,
5701                                 "this is the first default label");
5702                 } else {
5703                         /* link all cases into the switch statement */
5704                         if (current_switch->last_case == NULL) {
5705                                 current_switch->first_case =
5706                                         current_switch->last_case  = &statement->case_label;
5707                         } else {
5708                                 current_switch->last_case->next = &statement->case_label;
5709                         }
5710                 }
5711         } else {
5712                 errorf(statement->base.source_position,
5713                         "'default' label not within a switch statement");
5714         }
5715         statement->case_label.statement = parse_statement();
5716
5717         return statement;
5718 }
5719
5720 /**
5721  * Return the declaration for a given label symbol or create a new one.
5722  */
5723 static declaration_t *get_label(symbol_t *symbol)
5724 {
5725         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
5726         assert(current_function != NULL);
5727         /* if we found a label in the same function, then we already created the
5728          * declaration */
5729         if(candidate != NULL
5730                         && candidate->parent_scope == &current_function->scope) {
5731                 return candidate;
5732         }
5733
5734         /* otherwise we need to create a new one */
5735         declaration_t *const declaration = allocate_declaration_zero();
5736         declaration->namespc       = NAMESPACE_LABEL;
5737         declaration->symbol        = symbol;
5738
5739         label_push(declaration);
5740
5741         return declaration;
5742 }
5743
5744 /**
5745  * Parse a label statement.
5746  */
5747 static statement_t *parse_label_statement(void)
5748 {
5749         assert(token.type == T_IDENTIFIER);
5750         symbol_t *symbol = token.v.symbol;
5751         next_token();
5752
5753         declaration_t *label = get_label(symbol);
5754
5755         /* if source position is already set then the label is defined twice,
5756          * otherwise it was just mentioned in a goto so far */
5757         if(label->source_position.input_name != NULL) {
5758                 errorf(HERE, "duplicate label '%Y'", symbol);
5759                 errorf(label->source_position, "previous definition of '%Y' was here",
5760                        symbol);
5761         } else {
5762                 label->source_position = token.source_position;
5763         }
5764
5765         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
5766
5767         statement->base.source_position = token.source_position;
5768         statement->label.label          = label;
5769
5770         eat(':');
5771
5772         if(token.type == '}') {
5773                 /* TODO only warn? */
5774                 errorf(HERE, "label at end of compound statement");
5775                 return statement;
5776         } else {
5777                 if (token.type == ';') {
5778                         /* eat an empty statement here, to avoid the warning about an empty
5779                          * after a label.  label:; is commonly used to have a label before
5780                          * a }. */
5781                         next_token();
5782                 } else {
5783                         statement->label.statement = parse_statement();
5784                 }
5785         }
5786
5787         /* remember the labels's in a list for later checking */
5788         if (label_last == NULL) {
5789                 label_first = &statement->label;
5790         } else {
5791                 label_last->next = &statement->label;
5792         }
5793         label_last = &statement->label;
5794
5795         return statement;
5796 }
5797
5798 /**
5799  * Parse an if statement.
5800  */
5801 static statement_t *parse_if(void)
5802 {
5803         eat(T_if);
5804
5805         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
5806         statement->base.source_position = token.source_position;
5807
5808         expect('(');
5809         statement->ifs.condition = parse_expression();
5810         expect(')');
5811
5812         statement->ifs.true_statement = parse_statement();
5813         if(token.type == T_else) {
5814                 next_token();
5815                 statement->ifs.false_statement = parse_statement();
5816         }
5817
5818         return statement;
5819 }
5820
5821 /**
5822  * Parse a switch statement.
5823  */
5824 static statement_t *parse_switch(void)
5825 {
5826         eat(T_switch);
5827
5828         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
5829         statement->base.source_position = token.source_position;
5830
5831         expect('(');
5832         expression_t *const expr = parse_expression();
5833         type_t       *      type = skip_typeref(expr->base.type);
5834         if (is_type_integer(type)) {
5835                 type = promote_integer(type);
5836         } else if (is_type_valid(type)) {
5837                 errorf(expr->base.source_position,
5838                        "switch quantity is not an integer, but '%T'", type);
5839                 type = type_error_type;
5840         }
5841         statement->switchs.expression = create_implicit_cast(expr, type);
5842         expect(')');
5843
5844         switch_statement_t *rem = current_switch;
5845         current_switch          = &statement->switchs;
5846         statement->switchs.body = parse_statement();
5847         current_switch          = rem;
5848
5849         if (warning.switch_default
5850                         && find_default_label(&statement->switchs) == NULL) {
5851                 warningf(statement->base.source_position, "switch has no default case");
5852         }
5853
5854         return statement;
5855 }
5856
5857 static statement_t *parse_loop_body(statement_t *const loop)
5858 {
5859         statement_t *const rem = current_loop;
5860         current_loop = loop;
5861
5862         statement_t *const body = parse_statement();
5863
5864         current_loop = rem;
5865         return body;
5866 }
5867
5868 /**
5869  * Parse a while statement.
5870  */
5871 static statement_t *parse_while(void)
5872 {
5873         eat(T_while);
5874
5875         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
5876         statement->base.source_position = token.source_position;
5877
5878         expect('(');
5879         statement->whiles.condition = parse_expression();
5880         expect(')');
5881
5882         statement->whiles.body = parse_loop_body(statement);
5883
5884         return statement;
5885 }
5886
5887 /**
5888  * Parse a do statement.
5889  */
5890 static statement_t *parse_do(void)
5891 {
5892         eat(T_do);
5893
5894         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
5895
5896         statement->base.source_position = token.source_position;
5897
5898         statement->do_while.body = parse_loop_body(statement);
5899
5900         expect(T_while);
5901         expect('(');
5902         statement->do_while.condition = parse_expression();
5903         expect(')');
5904         expect(';');
5905
5906         return statement;
5907 }
5908
5909 /**
5910  * Parse a for statement.
5911  */
5912 static statement_t *parse_for(void)
5913 {
5914         eat(T_for);
5915
5916         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
5917         statement->base.source_position = token.source_position;
5918
5919         expect('(');
5920
5921         int      top        = environment_top();
5922         scope_t *last_scope = scope;
5923         set_scope(&statement->fors.scope);
5924
5925         if(token.type != ';') {
5926                 if(is_declaration_specifier(&token, false)) {
5927                         parse_declaration(record_declaration);
5928                 } else {
5929                         expression_t *const init = parse_expression();
5930                         statement->fors.initialisation = init;
5931                         if (warning.unused_value  && !expression_has_effect(init)) {
5932                                 warningf(init->base.source_position, "initialisation of 'for'-statement has no effect");
5933                         }
5934                         expect(';');
5935                 }
5936         } else {
5937                 expect(';');
5938         }
5939
5940         if(token.type != ';') {
5941                 statement->fors.condition = parse_expression();
5942         }
5943         expect(';');
5944         if(token.type != ')') {
5945                 expression_t *const step = parse_expression();
5946                 statement->fors.step = step;
5947                 if (warning.unused_value  && !expression_has_effect(step)) {
5948                         warningf(step->base.source_position, "step of 'for'-statement has no effect");
5949                 }
5950         }
5951         expect(')');
5952         statement->fors.body = parse_loop_body(statement);
5953
5954         assert(scope == &statement->fors.scope);
5955         set_scope(last_scope);
5956         environment_pop_to(top);
5957
5958         return statement;
5959 }
5960
5961 /**
5962  * Parse a goto statement.
5963  */
5964 static statement_t *parse_goto(void)
5965 {
5966         eat(T_goto);
5967
5968         if(token.type != T_IDENTIFIER) {
5969                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5970                 eat_statement();
5971                 return NULL;
5972         }
5973         symbol_t *symbol = token.v.symbol;
5974         next_token();
5975
5976         declaration_t *label = get_label(symbol);
5977
5978         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
5979         statement->base.source_position = token.source_position;
5980
5981         statement->gotos.label = label;
5982
5983         /* remember the goto's in a list for later checking */
5984         if (goto_last == NULL) {
5985                 goto_first = &statement->gotos;
5986         } else {
5987                 goto_last->next = &statement->gotos;
5988         }
5989         goto_last = &statement->gotos;
5990
5991         expect(';');
5992
5993         return statement;
5994 }
5995
5996 /**
5997  * Parse a continue statement.
5998  */
5999 static statement_t *parse_continue(void)
6000 {
6001         statement_t *statement;
6002         if (current_loop == NULL) {
6003                 errorf(HERE, "continue statement not within loop");
6004                 statement = NULL;
6005         } else {
6006                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6007
6008                 statement->base.source_position = token.source_position;
6009         }
6010
6011         eat(T_continue);
6012         expect(';');
6013
6014         return statement;
6015 }
6016
6017 /**
6018  * Parse a break statement.
6019  */
6020 static statement_t *parse_break(void)
6021 {
6022         statement_t *statement;
6023         if (current_switch == NULL && current_loop == NULL) {
6024                 errorf(HERE, "break statement not within loop or switch");
6025                 statement = NULL;
6026         } else {
6027                 statement = allocate_statement_zero(STATEMENT_BREAK);
6028
6029                 statement->base.source_position = token.source_position;
6030         }
6031
6032         eat(T_break);
6033         expect(';');
6034
6035         return statement;
6036 }
6037
6038 /**
6039  * Check if a given declaration represents a local variable.
6040  */
6041 static bool is_local_var_declaration(const declaration_t *declaration) {
6042         switch ((storage_class_tag_t) declaration->storage_class) {
6043         case STORAGE_CLASS_AUTO:
6044         case STORAGE_CLASS_REGISTER: {
6045                 const type_t *type = skip_typeref(declaration->type);
6046                 if(is_type_function(type)) {
6047                         return false;
6048                 } else {
6049                         return true;
6050                 }
6051         }
6052         default:
6053                 return false;
6054         }
6055 }
6056
6057 /**
6058  * Check if a given declaration represents a variable.
6059  */
6060 static bool is_var_declaration(const declaration_t *declaration) {
6061         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6062                 return false;
6063
6064         const type_t *type = skip_typeref(declaration->type);
6065         return !is_type_function(type);
6066 }
6067
6068 /**
6069  * Check if a given expression represents a local variable.
6070  */
6071 static bool is_local_variable(const expression_t *expression)
6072 {
6073         if (expression->base.kind != EXPR_REFERENCE) {
6074                 return false;
6075         }
6076         const declaration_t *declaration = expression->reference.declaration;
6077         return is_local_var_declaration(declaration);
6078 }
6079
6080 /**
6081  * Check if a given expression represents a local variable and
6082  * return its declaration then, else return NULL.
6083  */
6084 declaration_t *expr_is_variable(const expression_t *expression)
6085 {
6086         if (expression->base.kind != EXPR_REFERENCE) {
6087                 return NULL;
6088         }
6089         declaration_t *declaration = expression->reference.declaration;
6090         if (is_var_declaration(declaration))
6091                 return declaration;
6092         return NULL;
6093 }
6094
6095 /**
6096  * Parse a return statement.
6097  */
6098 static statement_t *parse_return(void)
6099 {
6100         eat(T_return);
6101
6102         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
6103         statement->base.source_position = token.source_position;
6104
6105         expression_t *return_value = NULL;
6106         if(token.type != ';') {
6107                 return_value = parse_expression();
6108         }
6109         expect(';');
6110
6111         const type_t *const func_type = current_function->type;
6112         assert(is_type_function(func_type));
6113         type_t *const return_type = skip_typeref(func_type->function.return_type);
6114
6115         if(return_value != NULL) {
6116                 type_t *return_value_type = skip_typeref(return_value->base.type);
6117
6118                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6119                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6120                         warningf(statement->base.source_position,
6121                                  "'return' with a value, in function returning void");
6122                         return_value = NULL;
6123                 } else {
6124                         type_t *const res_type = semantic_assign(return_type,
6125                                 return_value, "'return'");
6126                         if (res_type == NULL) {
6127                                 errorf(statement->base.source_position,
6128                                        "cannot return something of type '%T' in function returning '%T'",
6129                                        return_value->base.type, return_type);
6130                         } else {
6131                                 return_value = create_implicit_cast(return_value, res_type);
6132                         }
6133                 }
6134                 /* check for returning address of a local var */
6135                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6136                         const expression_t *expression = return_value->unary.value;
6137                         if (is_local_variable(expression)) {
6138                                 warningf(statement->base.source_position,
6139                                          "function returns address of local variable");
6140                         }
6141                 }
6142         } else {
6143                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6144                         warningf(statement->base.source_position,
6145                                  "'return' without value, in function returning non-void");
6146                 }
6147         }
6148         statement->returns.value = return_value;
6149
6150         return statement;
6151 }
6152
6153 /**
6154  * Parse a declaration statement.
6155  */
6156 static statement_t *parse_declaration_statement(void)
6157 {
6158         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6159
6160         statement->base.source_position = token.source_position;
6161
6162         declaration_t *before = last_declaration;
6163         parse_declaration(record_declaration);
6164
6165         if(before == NULL) {
6166                 statement->declaration.declarations_begin = scope->declarations;
6167         } else {
6168                 statement->declaration.declarations_begin = before->next;
6169         }
6170         statement->declaration.declarations_end = last_declaration;
6171
6172         return statement;
6173 }
6174
6175 /**
6176  * Parse an expression statement, ie. expr ';'.
6177  */
6178 static statement_t *parse_expression_statement(void)
6179 {
6180         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6181
6182         statement->base.source_position  = token.source_position;
6183         expression_t *const expr         = parse_expression();
6184         statement->expression.expression = expr;
6185
6186         if (warning.unused_value  && !expression_has_effect(expr)) {
6187                 warningf(expr->base.source_position, "statement has no effect");
6188         }
6189
6190         expect(';');
6191
6192         return statement;
6193 }
6194
6195 /**
6196  * Parse a statement.
6197  */
6198 static statement_t *parse_statement(void)
6199 {
6200         statement_t   *statement = NULL;
6201
6202         /* declaration or statement */
6203         switch(token.type) {
6204         case T_asm:
6205                 statement = parse_asm_statement();
6206                 break;
6207
6208         case T_case:
6209                 statement = parse_case_statement();
6210                 break;
6211
6212         case T_default:
6213                 statement = parse_default_statement();
6214                 break;
6215
6216         case '{':
6217                 statement = parse_compound_statement();
6218                 break;
6219
6220         case T_if:
6221                 statement = parse_if();
6222                 break;
6223
6224         case T_switch:
6225                 statement = parse_switch();
6226                 break;
6227
6228         case T_while:
6229                 statement = parse_while();
6230                 break;
6231
6232         case T_do:
6233                 statement = parse_do();
6234                 break;
6235
6236         case T_for:
6237                 statement = parse_for();
6238                 break;
6239
6240         case T_goto:
6241                 statement = parse_goto();
6242                 break;
6243
6244         case T_continue:
6245                 statement = parse_continue();
6246                 break;
6247
6248         case T_break:
6249                 statement = parse_break();
6250                 break;
6251
6252         case T_return:
6253                 statement = parse_return();
6254                 break;
6255
6256         case ';':
6257                 if (warning.empty_statement) {
6258                         warningf(HERE, "statement is empty");
6259                 }
6260                 next_token();
6261                 statement = NULL;
6262                 break;
6263
6264         case T_IDENTIFIER:
6265                 if(look_ahead(1)->type == ':') {
6266                         statement = parse_label_statement();
6267                         break;
6268                 }
6269
6270                 if(is_typedef_symbol(token.v.symbol)) {
6271                         statement = parse_declaration_statement();
6272                         break;
6273                 }
6274
6275                 statement = parse_expression_statement();
6276                 break;
6277
6278         case T___extension__:
6279                 /* this can be a prefix to a declaration or an expression statement */
6280                 /* we simply eat it now and parse the rest with tail recursion */
6281                 do {
6282                         next_token();
6283                 } while(token.type == T___extension__);
6284                 statement = parse_statement();
6285                 break;
6286
6287         DECLARATION_START
6288                 statement = parse_declaration_statement();
6289                 break;
6290
6291         default:
6292                 statement = parse_expression_statement();
6293                 break;
6294         }
6295
6296         assert(statement == NULL
6297                         || statement->base.source_position.input_name != NULL);
6298
6299         return statement;
6300 }
6301
6302 /**
6303  * Parse a compound statement.
6304  */
6305 static statement_t *parse_compound_statement(void)
6306 {
6307         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6308
6309         statement->base.source_position = token.source_position;
6310
6311         eat('{');
6312
6313         int      top        = environment_top();
6314         scope_t *last_scope = scope;
6315         set_scope(&statement->compound.scope);
6316
6317         statement_t *last_statement = NULL;
6318
6319         while(token.type != '}' && token.type != T_EOF) {
6320                 statement_t *sub_statement = parse_statement();
6321                 if(sub_statement == NULL)
6322                         continue;
6323
6324                 if(last_statement != NULL) {
6325                         last_statement->base.next = sub_statement;
6326                 } else {
6327                         statement->compound.statements = sub_statement;
6328                 }
6329
6330                 while(sub_statement->base.next != NULL)
6331                         sub_statement = sub_statement->base.next;
6332
6333                 last_statement = sub_statement;
6334         }
6335
6336         if(token.type == '}') {
6337                 next_token();
6338         } else {
6339                 errorf(statement->base.source_position,
6340                        "end of file while looking for closing '}'");
6341         }
6342
6343         assert(scope == &statement->compound.scope);
6344         set_scope(last_scope);
6345         environment_pop_to(top);
6346
6347         return statement;
6348 }
6349
6350 /**
6351  * Initialize builtin types.
6352  */
6353 static void initialize_builtin_types(void)
6354 {
6355         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
6356         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
6357         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
6358         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
6359         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
6360         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6361         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
6362         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
6363
6364         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
6365         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6366         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
6367         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
6368 }
6369
6370 /**
6371  * Check for unused global static functions and variables
6372  */
6373 static void check_unused_globals(void)
6374 {
6375         if (!warning.unused_function && !warning.unused_variable)
6376                 return;
6377
6378         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6379                 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6380                         continue;
6381
6382                 type_t *const type = decl->type;
6383                 const char *s;
6384                 if (is_type_function(skip_typeref(type))) {
6385                         if (!warning.unused_function || decl->is_inline)
6386                                 continue;
6387
6388                         s = (decl->init.statement != NULL ? "defined" : "declared");
6389                 } else {
6390                         if (!warning.unused_variable)
6391                                 continue;
6392
6393                         s = "defined";
6394                 }
6395
6396                 warningf(decl->source_position, "'%#T' %s but not used",
6397                         type, decl->symbol, s);
6398         }
6399 }
6400
6401 /**
6402  * Parse a translation unit.
6403  */
6404 static translation_unit_t *parse_translation_unit(void)
6405 {
6406         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6407
6408         assert(global_scope == NULL);
6409         global_scope = &unit->scope;
6410
6411         assert(scope == NULL);
6412         set_scope(&unit->scope);
6413
6414         initialize_builtin_types();
6415
6416         while(token.type != T_EOF) {
6417                 if (token.type == ';') {
6418                         /* TODO error in strict mode */
6419                         warningf(HERE, "stray ';' outside of function");
6420                         next_token();
6421                 } else {
6422                         parse_external_declaration();
6423                 }
6424         }
6425
6426         assert(scope == &unit->scope);
6427         scope          = NULL;
6428         last_declaration = NULL;
6429
6430         assert(global_scope == &unit->scope);
6431         check_unused_globals();
6432         global_scope = NULL;
6433
6434         return unit;
6435 }
6436
6437 /**
6438  * Parse the input.
6439  *
6440  * @return  the translation unit or NULL if errors occurred.
6441  */
6442 translation_unit_t *parse(void)
6443 {
6444         environment_stack = NEW_ARR_F(stack_entry_t, 0);
6445         label_stack       = NEW_ARR_F(stack_entry_t, 0);
6446         diagnostic_count  = 0;
6447         error_count       = 0;
6448         warning_count     = 0;
6449
6450         type_set_output(stderr);
6451         ast_set_output(stderr);
6452
6453         lookahead_bufpos = 0;
6454         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6455                 next_token();
6456         }
6457         translation_unit_t *unit = parse_translation_unit();
6458
6459         DEL_ARR_F(environment_stack);
6460         DEL_ARR_F(label_stack);
6461
6462         if(error_count > 0)
6463                 return NULL;
6464
6465         return unit;
6466 }
6467
6468 /**
6469  * Initialize the parser.
6470  */
6471 void init_parser(void)
6472 {
6473         init_expression_parsers();
6474         obstack_init(&temp_obst);
6475
6476         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6477         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6478 }
6479
6480 /**
6481  * Terminate the parser.
6482  */
6483 void exit_parser(void)
6484 {
6485         obstack_free(&temp_obst, NULL);
6486 }