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