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