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