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