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