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