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