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