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