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