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