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