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