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