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