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