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