Do not truncate the existing attribute list if a __declspec has no arguments.
[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         if (token.kind != ')') {
2663                 add_anchor_token(')');
2664
2665                 attribute_t **anchor = &first;
2666                 do {
2667                         while (*anchor != NULL)
2668                                 anchor = &(*anchor)->next;
2669
2670                         attribute_t *attribute
2671                                 = parse_microsoft_extended_decl_modifier_single();
2672                         if (attribute == NULL)
2673                                 break;
2674
2675                         *anchor = attribute;
2676                         anchor  = &attribute->next;
2677                 } while (next_if(','));
2678
2679                 rem_anchor_token(')');
2680         }
2681         expect(')', end_error);
2682 end_error:
2683         return first;
2684 }
2685
2686 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2687 {
2688         entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2689         entity->base.source_position = *HERE;
2690         if (is_declaration(entity)) {
2691                 entity->declaration.type     = type_error_type;
2692                 entity->declaration.implicit = true;
2693         } else if (kind == ENTITY_TYPEDEF) {
2694                 entity->typedefe.type    = type_error_type;
2695                 entity->typedefe.builtin = true;
2696         }
2697         if (kind != ENTITY_COMPOUND_MEMBER)
2698                 record_entity(entity, false);
2699         return entity;
2700 }
2701
2702 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2703 {
2704         type_t            *type            = NULL;
2705         type_qualifiers_t  qualifiers      = TYPE_QUALIFIER_NONE;
2706         unsigned           type_specifiers = 0;
2707         bool               newtype         = false;
2708         bool               saw_error       = false;
2709
2710         memset(specifiers, 0, sizeof(*specifiers));
2711         specifiers->source_position = token.base.source_position;
2712
2713         while (true) {
2714                 specifiers->attributes = parse_attributes(specifiers->attributes);
2715
2716                 switch (token.kind) {
2717                 /* storage class */
2718 #define MATCH_STORAGE_CLASS(token, class)                                  \
2719                 case token:                                                        \
2720                         if (specifiers->storage_class != STORAGE_CLASS_NONE) {         \
2721                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2722                         }                                                              \
2723                         specifiers->storage_class = class;                             \
2724                         if (specifiers->thread_local)                                  \
2725                                 goto check_thread_storage_class;                           \
2726                         next_token();                                                  \
2727                         break;
2728
2729                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
2730                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
2731                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
2732                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
2733                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2734
2735                 case T__declspec:
2736                         specifiers->attributes
2737                                 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2738                         break;
2739
2740                 case T___thread:
2741                         if (specifiers->thread_local) {
2742                                 errorf(HERE, "duplicate '__thread'");
2743                         } else {
2744                                 specifiers->thread_local = true;
2745 check_thread_storage_class:
2746                                 switch (specifiers->storage_class) {
2747                                         case STORAGE_CLASS_EXTERN:
2748                                         case STORAGE_CLASS_NONE:
2749                                         case STORAGE_CLASS_STATIC:
2750                                                 break;
2751
2752                                                 char const* wrong;
2753                                         case STORAGE_CLASS_AUTO:     wrong = "auto";     goto wrong_thread_storage_class;
2754                                         case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2755                                         case STORAGE_CLASS_TYPEDEF:  wrong = "typedef";  goto wrong_thread_storage_class;
2756 wrong_thread_storage_class:
2757                                                 errorf(HERE, "'__thread' used with '%s'", wrong);
2758                                                 break;
2759                                 }
2760                         }
2761                         next_token();
2762                         break;
2763
2764                 /* type qualifiers */
2765 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
2766                 case token:                                                     \
2767                         qualifiers |= qualifier;                                    \
2768                         next_token();                                               \
2769                         break
2770
2771                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2772                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2773                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2774                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
2775                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
2776                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
2777                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
2778                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
2779
2780                 /* type specifiers */
2781 #define MATCH_SPECIFIER(token, specifier, name)                         \
2782                 case token:                                                     \
2783                         if (type_specifiers & specifier) {                           \
2784                                 errorf(HERE, "multiple " name " type specifiers given"); \
2785                         } else {                                                    \
2786                                 type_specifiers |= specifier;                           \
2787                         }                                                           \
2788                         next_token();                                               \
2789                         break
2790
2791                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool");
2792                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex");
2793                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2794                 MATCH_SPECIFIER(T__int128,    SPECIFIER_INT128,    "_int128");
2795                 MATCH_SPECIFIER(T__int16,     SPECIFIER_INT16,     "_int16");
2796                 MATCH_SPECIFIER(T__int32,     SPECIFIER_INT32,     "_int32");
2797                 MATCH_SPECIFIER(T__int64,     SPECIFIER_INT64,     "_int64");
2798                 MATCH_SPECIFIER(T__int8,      SPECIFIER_INT8,      "_int8");
2799                 MATCH_SPECIFIER(T_bool,       SPECIFIER_BOOL,      "bool");
2800                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char");
2801                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double");
2802                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float");
2803                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int");
2804                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short");
2805                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed");
2806                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned");
2807                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void");
2808                 MATCH_SPECIFIER(T_wchar_t,    SPECIFIER_WCHAR_T,   "wchar_t");
2809
2810                 case T_inline:
2811                         next_token();
2812                         specifiers->is_inline = true;
2813                         break;
2814
2815 #if 0
2816                 case T__forceinline:
2817                         next_token();
2818                         specifiers->modifiers |= DM_FORCEINLINE;
2819                         break;
2820 #endif
2821
2822                 case T_long:
2823                         if (type_specifiers & SPECIFIER_LONG_LONG) {
2824                                 errorf(HERE, "too many long type specifiers given");
2825                         } else if (type_specifiers & SPECIFIER_LONG) {
2826                                 type_specifiers |= SPECIFIER_LONG_LONG;
2827                         } else {
2828                                 type_specifiers |= SPECIFIER_LONG;
2829                         }
2830                         next_token();
2831                         break;
2832
2833 #define CHECK_DOUBLE_TYPE() \
2834         (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2835
2836                 case T_struct:
2837                         CHECK_DOUBLE_TYPE();
2838                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2839
2840                         type->compound.compound = parse_compound_type_specifier(true);
2841                         break;
2842                 case T_union:
2843                         CHECK_DOUBLE_TYPE();
2844                         type = allocate_type_zero(TYPE_COMPOUND_UNION);
2845                         type->compound.compound = parse_compound_type_specifier(false);
2846                         break;
2847                 case T_enum:
2848                         CHECK_DOUBLE_TYPE();
2849                         type = parse_enum_specifier();
2850                         break;
2851                 case T___typeof__:
2852                         CHECK_DOUBLE_TYPE();
2853                         type = parse_typeof();
2854                         break;
2855                 case T___builtin_va_list:
2856                         CHECK_DOUBLE_TYPE();
2857                         type = duplicate_type(type_valist);
2858                         next_token();
2859                         break;
2860
2861                 case T_IDENTIFIER: {
2862                         /* only parse identifier if we haven't found a type yet */
2863                         if (type != NULL || type_specifiers != 0) {
2864                                 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2865                                  * declaration, so it doesn't generate errors about expecting '(' or
2866                                  * '{' later on. */
2867                                 switch (look_ahead(1)->kind) {
2868                                         STORAGE_CLASSES
2869                                         TYPE_SPECIFIERS
2870                                         case T_const:
2871                                         case T_restrict:
2872                                         case T_volatile:
2873                                         case T_inline:
2874                                         case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2875                                         case T_IDENTIFIER:
2876                                         case '&':
2877                                         case '*':
2878                                                 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2879                                                 next_token();
2880                                                 continue;
2881
2882                                         default:
2883                                                 goto finish_specifiers;
2884                                 }
2885                         }
2886
2887                         type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2888                         if (typedef_type == NULL) {
2889                                 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2890                                  * declaration, so it doesn't generate 'implicit int' followed by more
2891                                  * errors later on. */
2892                                 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2893                                 switch (la1_type) {
2894                                         DECLARATION_START
2895                                         case T_IDENTIFIER:
2896                                         case '&':
2897                                         case '*': {
2898                                                 errorf(HERE, "%K does not name a type", &token);
2899
2900                                                 symbol_t *symbol = token.identifier.symbol;
2901                                                 entity_t *entity
2902                                                         = create_error_entity(symbol, ENTITY_TYPEDEF);
2903
2904                                                 type = allocate_type_zero(TYPE_TYPEDEF);
2905                                                 type->typedeft.typedefe = &entity->typedefe;
2906
2907                                                 next_token();
2908                                                 saw_error = true;
2909                                                 continue;
2910                                         }
2911
2912                                         default:
2913                                                 goto finish_specifiers;
2914                                 }
2915                         }
2916
2917                         next_token();
2918                         type = typedef_type;
2919                         break;
2920                 }
2921
2922                 /* function specifier */
2923                 default:
2924                         goto finish_specifiers;
2925                 }
2926         }
2927
2928 finish_specifiers:
2929         specifiers->attributes = parse_attributes(specifiers->attributes);
2930
2931         if (type == NULL || (saw_error && type_specifiers != 0)) {
2932                 atomic_type_kind_t atomic_type;
2933
2934                 /* match valid basic types */
2935                 switch (type_specifiers) {
2936                 case SPECIFIER_VOID:
2937                         atomic_type = ATOMIC_TYPE_VOID;
2938                         break;
2939                 case SPECIFIER_WCHAR_T:
2940                         atomic_type = ATOMIC_TYPE_WCHAR_T;
2941                         break;
2942                 case SPECIFIER_CHAR:
2943                         atomic_type = ATOMIC_TYPE_CHAR;
2944                         break;
2945                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2946                         atomic_type = ATOMIC_TYPE_SCHAR;
2947                         break;
2948                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2949                         atomic_type = ATOMIC_TYPE_UCHAR;
2950                         break;
2951                 case SPECIFIER_SHORT:
2952                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2953                 case SPECIFIER_SHORT | SPECIFIER_INT:
2954                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2955                         atomic_type = ATOMIC_TYPE_SHORT;
2956                         break;
2957                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2958                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2959                         atomic_type = ATOMIC_TYPE_USHORT;
2960                         break;
2961                 case SPECIFIER_INT:
2962                 case SPECIFIER_SIGNED:
2963                 case SPECIFIER_SIGNED | SPECIFIER_INT:
2964                         atomic_type = ATOMIC_TYPE_INT;
2965                         break;
2966                 case SPECIFIER_UNSIGNED:
2967                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2968                         atomic_type = ATOMIC_TYPE_UINT;
2969                         break;
2970                 case SPECIFIER_LONG:
2971                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2972                 case SPECIFIER_LONG | SPECIFIER_INT:
2973                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2974                         atomic_type = ATOMIC_TYPE_LONG;
2975                         break;
2976                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2977                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2978                         atomic_type = ATOMIC_TYPE_ULONG;
2979                         break;
2980
2981                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2982                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2983                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2984                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2985                         | SPECIFIER_INT:
2986                         atomic_type = ATOMIC_TYPE_LONGLONG;
2987                         goto warn_about_long_long;
2988
2989                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2990                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2991                         | SPECIFIER_INT:
2992                         atomic_type = ATOMIC_TYPE_ULONGLONG;
2993 warn_about_long_long:
2994                         warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2995                         break;
2996
2997                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2998                         atomic_type = unsigned_int8_type_kind;
2999                         break;
3000
3001                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3002                         atomic_type = unsigned_int16_type_kind;
3003                         break;
3004
3005                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3006                         atomic_type = unsigned_int32_type_kind;
3007                         break;
3008
3009                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3010                         atomic_type = unsigned_int64_type_kind;
3011                         break;
3012
3013                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3014                         atomic_type = unsigned_int128_type_kind;
3015                         break;
3016
3017                 case SPECIFIER_INT8:
3018                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3019                         atomic_type = int8_type_kind;
3020                         break;
3021
3022                 case SPECIFIER_INT16:
3023                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3024                         atomic_type = int16_type_kind;
3025                         break;
3026
3027                 case SPECIFIER_INT32:
3028                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3029                         atomic_type = int32_type_kind;
3030                         break;
3031
3032                 case SPECIFIER_INT64:
3033                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3034                         atomic_type = int64_type_kind;
3035                         break;
3036
3037                 case SPECIFIER_INT128:
3038                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3039                         atomic_type = int128_type_kind;
3040                         break;
3041
3042                 case SPECIFIER_FLOAT:
3043                         atomic_type = ATOMIC_TYPE_FLOAT;
3044                         break;
3045                 case SPECIFIER_DOUBLE:
3046                         atomic_type = ATOMIC_TYPE_DOUBLE;
3047                         break;
3048                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3049                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3050                         break;
3051                 case SPECIFIER_BOOL:
3052                         atomic_type = ATOMIC_TYPE_BOOL;
3053                         break;
3054                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3055                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3056                         atomic_type = ATOMIC_TYPE_FLOAT;
3057                         break;
3058                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3059                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3060                         atomic_type = ATOMIC_TYPE_DOUBLE;
3061                         break;
3062                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3063                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3064                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3065                         break;
3066                 default: {
3067                         /* invalid specifier combination, give an error message */
3068                         source_position_t const* const pos = &specifiers->source_position;
3069                         if (type_specifiers == 0) {
3070                                 if (!saw_error) {
3071                                         /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3072                                         if (!(c_mode & _CXX) && !strict_mode) {
3073                                                 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3074                                                 atomic_type = ATOMIC_TYPE_INT;
3075                                                 break;
3076                                         } else {
3077                                                 errorf(pos, "no type specifiers given in declaration");
3078                                         }
3079                                 }
3080                         } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3081                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
3082                                 errorf(pos, "signed and unsigned specifiers given");
3083                         } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3084                                 errorf(pos, "only integer types can be signed or unsigned");
3085                         } else {
3086                                 errorf(pos, "multiple datatypes in declaration");
3087                         }
3088                         goto end_error;
3089                 }
3090                 }
3091
3092                 if (type_specifiers & SPECIFIER_COMPLEX) {
3093                         type = allocate_type_zero(TYPE_COMPLEX);
3094                 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3095                         type = allocate_type_zero(TYPE_IMAGINARY);
3096                 } else {
3097                         type = allocate_type_zero(TYPE_ATOMIC);
3098                 }
3099                 type->atomic.akind = atomic_type;
3100                 newtype = true;
3101         } else if (type_specifiers != 0) {
3102                 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3103         }
3104
3105         /* FIXME: check type qualifiers here */
3106         type->base.qualifiers = qualifiers;
3107
3108         if (newtype) {
3109                 type = identify_new_type(type);
3110         } else {
3111                 type = typehash_insert(type);
3112         }
3113
3114         if (specifiers->attributes != NULL)
3115                 type = handle_type_attributes(specifiers->attributes, type);
3116         specifiers->type = type;
3117         return;
3118
3119 end_error:
3120         specifiers->type = type_error_type;
3121 }
3122
3123 static type_qualifiers_t parse_type_qualifiers(void)
3124 {
3125         type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3126
3127         while (true) {
3128                 switch (token.kind) {
3129                 /* type qualifiers */
3130                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3131                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3132                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3133                 /* microsoft extended type modifiers */
3134                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3135                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3136                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3137                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3138                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3139
3140                 default:
3141                         return qualifiers;
3142                 }
3143         }
3144 }
3145
3146 /**
3147  * Parses an K&R identifier list
3148  */
3149 static void parse_identifier_list(scope_t *scope)
3150 {
3151         assert(token.kind == T_IDENTIFIER);
3152         do {
3153                 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3154                 entity->base.source_position = token.base.source_position;
3155                 /* a K&R parameter has no type, yet */
3156                 next_token();
3157
3158                 if (scope != NULL)
3159                         append_entity(scope, entity);
3160         } while (next_if(',') && token.kind == T_IDENTIFIER);
3161 }
3162
3163 static entity_t *parse_parameter(void)
3164 {
3165         declaration_specifiers_t specifiers;
3166         parse_declaration_specifiers(&specifiers);
3167
3168         entity_t *entity = parse_declarator(&specifiers,
3169                         DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3170         anonymous_entity = NULL;
3171         return entity;
3172 }
3173
3174 static void semantic_parameter_incomplete(const entity_t *entity)
3175 {
3176         assert(entity->kind == ENTITY_PARAMETER);
3177
3178         /* §6.7.5.3:4  After adjustment, the parameters in a parameter type
3179          *             list in a function declarator that is part of a
3180          *             definition of that function shall not have
3181          *             incomplete type. */
3182         type_t *type = skip_typeref(entity->declaration.type);
3183         if (is_type_incomplete(type)) {
3184                 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3185         }
3186 }
3187
3188 static bool has_parameters(void)
3189 {
3190         /* func(void) is not a parameter */
3191         if (look_ahead(1)->kind != ')')
3192                 return true;
3193         if (token.kind == T_IDENTIFIER) {
3194                 entity_t const *const entity
3195                         = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3196                 if (entity == NULL)
3197                         return true;
3198                 if (entity->kind != ENTITY_TYPEDEF)
3199                         return true;
3200                 type_t const *const type = skip_typeref(entity->typedefe.type);
3201                 if (!is_type_void(type))
3202                         return true;
3203                 if (c_mode & _CXX) {
3204                         /* ISO/IEC 14882:1998(E) §8.3.5:2  It must be literally (void).  A typedef
3205                          * is not allowed. */
3206                         errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3207                 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3208                         /* §6.7.5.3:10  Qualification is not allowed here. */
3209                         errorf(HERE, "'void' as parameter must not have type qualifiers");
3210                 }
3211         } else if (token.kind != T_void) {
3212                 return true;
3213         }
3214         next_token();
3215         return false;
3216 }
3217
3218 /**
3219  * Parses function type parameters (and optionally creates variable_t entities
3220  * for them in a scope)
3221  */
3222 static void parse_parameters(function_type_t *type, scope_t *scope)
3223 {
3224         eat('(');
3225         add_anchor_token(')');
3226         int saved_comma_state = save_and_reset_anchor_state(',');
3227
3228         if (token.kind == T_IDENTIFIER
3229             && !is_typedef_symbol(token.identifier.symbol)) {
3230                 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3231                 if (la1_type == ',' || la1_type == ')') {
3232                         type->kr_style_parameters = true;
3233                         parse_identifier_list(scope);
3234                         goto parameters_finished;
3235                 }
3236         }
3237
3238         if (token.kind == ')') {
3239                 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3240                 if (!(c_mode & _CXX))
3241                         type->unspecified_parameters = true;
3242         } else if (has_parameters()) {
3243                 function_parameter_t **anchor = &type->parameters;
3244                 do {
3245                         switch (token.kind) {
3246                         case T_DOTDOTDOT:
3247                                 next_token();
3248                                 type->variadic = true;
3249                                 goto parameters_finished;
3250
3251                         case T_IDENTIFIER:
3252                         DECLARATION_START
3253                         {
3254                                 entity_t *entity = parse_parameter();
3255                                 if (entity->kind == ENTITY_TYPEDEF) {
3256                                         errorf(&entity->base.source_position,
3257                                                         "typedef not allowed as function parameter");
3258                                         break;
3259                                 }
3260                                 assert(is_declaration(entity));
3261
3262                                 semantic_parameter_incomplete(entity);
3263
3264                                 function_parameter_t *const parameter =
3265                                         allocate_parameter(entity->declaration.type);
3266
3267                                 if (scope != NULL) {
3268                                         append_entity(scope, entity);
3269                                 }
3270
3271                                 *anchor = parameter;
3272                                 anchor  = &parameter->next;
3273                                 break;
3274                         }
3275
3276                         default:
3277                                 goto parameters_finished;
3278                         }
3279                 } while (next_if(','));
3280         }
3281
3282 parameters_finished:
3283         rem_anchor_token(')');
3284         expect(')', end_error);
3285
3286 end_error:
3287         restore_anchor_state(',', saved_comma_state);
3288 }
3289
3290 typedef enum construct_type_kind_t {
3291         CONSTRUCT_POINTER = 1,
3292         CONSTRUCT_REFERENCE,
3293         CONSTRUCT_FUNCTION,
3294         CONSTRUCT_ARRAY
3295 } construct_type_kind_t;
3296
3297 typedef union construct_type_t construct_type_t;
3298
3299 typedef struct construct_type_base_t {
3300         construct_type_kind_t  kind;
3301         source_position_t      pos;
3302         construct_type_t      *next;
3303 } construct_type_base_t;
3304
3305 typedef struct parsed_pointer_t {
3306         construct_type_base_t  base;
3307         type_qualifiers_t      type_qualifiers;
3308         variable_t            *base_variable;  /**< MS __based extension. */
3309 } parsed_pointer_t;
3310
3311 typedef struct parsed_reference_t {
3312         construct_type_base_t base;
3313 } parsed_reference_t;
3314
3315 typedef struct construct_function_type_t {
3316         construct_type_base_t  base;
3317         type_t                *function_type;
3318 } construct_function_type_t;
3319
3320 typedef struct parsed_array_t {
3321         construct_type_base_t  base;
3322         type_qualifiers_t      type_qualifiers;
3323         bool                   is_static;
3324         bool                   is_variable;
3325         expression_t          *size;
3326 } parsed_array_t;
3327
3328 union construct_type_t {
3329         construct_type_kind_t     kind;
3330         construct_type_base_t     base;
3331         parsed_pointer_t          pointer;
3332         parsed_reference_t        reference;
3333         construct_function_type_t function;
3334         parsed_array_t            array;
3335 };
3336
3337 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3338 {
3339         construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3340         memset(cons, 0, size);
3341         cons->kind     = kind;
3342         cons->base.pos = *HERE;
3343         return cons;
3344 }
3345
3346 /* §6.7.5.1 */
3347 static construct_type_t *parse_pointer_declarator(void)
3348 {
3349         construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3350         eat('*');
3351         cons->pointer.type_qualifiers = parse_type_qualifiers();
3352         //cons->pointer.base_variable   = base_variable;
3353
3354         return cons;
3355 }
3356
3357 /* ISO/IEC 14882:1998(E) §8.3.2 */
3358 static construct_type_t *parse_reference_declarator(void)
3359 {
3360         if (!(c_mode & _CXX))
3361                 errorf(HERE, "references are only available for C++");
3362
3363         construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3364         eat('&');
3365
3366         return cons;
3367 }
3368
3369 /* §6.7.5.2 */
3370 static construct_type_t *parse_array_declarator(void)
3371 {
3372         construct_type_t *const cons  = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3373         parsed_array_t   *const array = &cons->array;
3374
3375         eat('[');
3376         add_anchor_token(']');
3377
3378         bool is_static = next_if(T_static);
3379
3380         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3381
3382         if (!is_static)
3383                 is_static = next_if(T_static);
3384
3385         array->type_qualifiers = type_qualifiers;
3386         array->is_static       = is_static;
3387
3388         expression_t *size = NULL;
3389         if (token.kind == '*' && look_ahead(1)->kind == ']') {
3390                 array->is_variable = true;
3391                 next_token();
3392         } else if (token.kind != ']') {
3393                 size = parse_assignment_expression();
3394
3395                 /* §6.7.5.2:1  Array size must have integer type */
3396                 type_t *const orig_type = size->base.type;
3397                 type_t *const type      = skip_typeref(orig_type);
3398                 if (!is_type_integer(type) && is_type_valid(type)) {
3399                         errorf(&size->base.source_position,
3400                                "array size '%E' must have integer type but has type '%T'",
3401                                size, orig_type);
3402                 }
3403
3404                 array->size = size;
3405                 mark_vars_read(size, NULL);
3406         }
3407
3408         if (is_static && size == NULL)
3409                 errorf(&array->base.pos, "static array parameters require a size");
3410
3411         rem_anchor_token(']');
3412         expect(']', end_error);
3413
3414 end_error:
3415         return cons;
3416 }
3417
3418 /* §6.7.5.3 */
3419 static construct_type_t *parse_function_declarator(scope_t *scope)
3420 {
3421         construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3422
3423         type_t          *type  = allocate_type_zero(TYPE_FUNCTION);
3424         function_type_t *ftype = &type->function;
3425
3426         ftype->linkage            = current_linkage;
3427         ftype->calling_convention = CC_DEFAULT;
3428
3429         parse_parameters(ftype, scope);
3430
3431         cons->function.function_type = type;
3432
3433         return cons;
3434 }
3435
3436 typedef struct parse_declarator_env_t {
3437         bool               may_be_abstract : 1;
3438         bool               must_be_abstract : 1;
3439         decl_modifiers_t   modifiers;
3440         symbol_t          *symbol;
3441         source_position_t  source_position;
3442         scope_t            parameters;
3443         attribute_t       *attributes;
3444 } parse_declarator_env_t;
3445
3446 /* §6.7.5 */
3447 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3448 {
3449         /* construct a single linked list of construct_type_t's which describe
3450          * how to construct the final declarator type */
3451         construct_type_t  *first      = NULL;
3452         construct_type_t **anchor     = &first;
3453
3454         env->attributes = parse_attributes(env->attributes);
3455
3456         for (;;) {
3457                 construct_type_t *type;
3458                 //variable_t       *based = NULL; /* MS __based extension */
3459                 switch (token.kind) {
3460                         case '&':
3461                                 type = parse_reference_declarator();
3462                                 break;
3463
3464                         case T__based: {
3465                                 panic("based not supported anymore");
3466                                 /* FALLTHROUGH */
3467                         }
3468
3469                         case '*':
3470                                 type = parse_pointer_declarator();
3471                                 break;
3472
3473                         default:
3474                                 goto ptr_operator_end;
3475                 }
3476
3477                 *anchor = type;
3478                 anchor  = &type->base.next;
3479
3480                 /* TODO: find out if this is correct */
3481                 env->attributes = parse_attributes(env->attributes);
3482         }
3483
3484 ptr_operator_end: ;
3485         construct_type_t *inner_types = NULL;
3486
3487         switch (token.kind) {
3488         case T_IDENTIFIER:
3489                 if (env->must_be_abstract) {
3490                         errorf(HERE, "no identifier expected in typename");
3491                 } else {
3492                         env->symbol          = token.identifier.symbol;
3493                         env->source_position = token.base.source_position;
3494                 }
3495                 next_token();
3496                 break;
3497
3498         case '(': {
3499                 /* Parenthesized declarator or function declarator? */
3500                 token_t const *const la1 = look_ahead(1);
3501                 switch (la1->kind) {
3502                         case T_IDENTIFIER:
3503                                 if (is_typedef_symbol(la1->identifier.symbol)) {
3504                         case ')':
3505                                         /* §6.7.6:2 footnote 126:  Empty parentheses in a type name are
3506                                          * interpreted as ``function with no parameter specification'', rather
3507                                          * than redundant parentheses around the omitted identifier. */
3508                         default:
3509                                         /* Function declarator. */
3510                                         if (!env->may_be_abstract) {
3511                                                 errorf(HERE, "function declarator must have a name");
3512                                         }
3513                                 } else {
3514                         case '&':
3515                         case '(':
3516                         case '*':
3517                         case '[':
3518                         case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3519                                         /* Paranthesized declarator. */
3520                                         next_token();
3521                                         add_anchor_token(')');
3522                                         inner_types = parse_inner_declarator(env);
3523                                         if (inner_types != NULL) {
3524                                                 /* All later declarators only modify the return type */
3525                                                 env->must_be_abstract = true;
3526                                         }
3527                                         rem_anchor_token(')');
3528                                         expect(')', end_error);
3529                                 }
3530                                 break;
3531                 }
3532                 break;
3533         }
3534
3535         default:
3536                 if (env->may_be_abstract)
3537                         break;
3538                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3539                 eat_until_anchor();
3540                 return NULL;
3541         }
3542
3543         construct_type_t **const p = anchor;
3544
3545         for (;;) {
3546                 construct_type_t *type;
3547                 switch (token.kind) {
3548                 case '(': {
3549                         scope_t *scope = NULL;
3550                         if (!env->must_be_abstract) {
3551                                 scope = &env->parameters;
3552                         }
3553
3554                         type = parse_function_declarator(scope);
3555                         break;
3556                 }
3557                 case '[':
3558                         type = parse_array_declarator();
3559                         break;
3560                 default:
3561                         goto declarator_finished;
3562                 }
3563
3564                 /* insert in the middle of the list (at p) */
3565                 type->base.next = *p;
3566                 *p              = type;
3567                 if (anchor == p)
3568                         anchor = &type->base.next;
3569         }
3570
3571 declarator_finished:
3572         /* append inner_types at the end of the list, we don't to set anchor anymore
3573          * as it's not needed anymore */
3574         *anchor = inner_types;
3575
3576         return first;
3577 end_error:
3578         return NULL;
3579 }
3580
3581 static type_t *construct_declarator_type(construct_type_t *construct_list,
3582                                          type_t *type)
3583 {
3584         construct_type_t *iter = construct_list;
3585         for (; iter != NULL; iter = iter->base.next) {
3586                 source_position_t const* const pos = &iter->base.pos;
3587                 switch (iter->kind) {
3588                 case CONSTRUCT_FUNCTION: {
3589                         construct_function_type_t *function      = &iter->function;
3590                         type_t                    *function_type = function->function_type;
3591
3592                         function_type->function.return_type = type;
3593
3594                         type_t *skipped_return_type = skip_typeref(type);
3595                         /* §6.7.5.3:1 */
3596                         if (is_type_function(skipped_return_type)) {
3597                                 errorf(pos, "function returning function is not allowed");
3598                         } else if (is_type_array(skipped_return_type)) {
3599                                 errorf(pos, "function returning array is not allowed");
3600                         } else {
3601                                 if (skipped_return_type->base.qualifiers != 0) {
3602                                         warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3603                                 }
3604                         }
3605
3606                         /* The function type was constructed earlier.  Freeing it here will
3607                          * destroy other types. */
3608                         type = typehash_insert(function_type);
3609                         continue;
3610                 }
3611
3612                 case CONSTRUCT_POINTER: {
3613                         if (is_type_reference(skip_typeref(type)))
3614                                 errorf(pos, "cannot declare a pointer to reference");
3615
3616                         parsed_pointer_t *pointer = &iter->pointer;
3617                         type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3618                         continue;
3619                 }
3620
3621                 case CONSTRUCT_REFERENCE:
3622                         if (is_type_reference(skip_typeref(type)))
3623                                 errorf(pos, "cannot declare a reference to reference");
3624
3625                         type = make_reference_type(type);
3626                         continue;
3627
3628                 case CONSTRUCT_ARRAY: {
3629                         if (is_type_reference(skip_typeref(type)))
3630                                 errorf(pos, "cannot declare an array of references");
3631
3632                         parsed_array_t *array      = &iter->array;
3633                         type_t         *array_type = allocate_type_zero(TYPE_ARRAY);
3634
3635                         expression_t *size_expression = array->size;
3636                         if (size_expression != NULL) {
3637                                 size_expression
3638                                         = create_implicit_cast(size_expression, type_size_t);
3639                         }
3640
3641                         array_type->base.qualifiers       = array->type_qualifiers;
3642                         array_type->array.element_type    = type;
3643                         array_type->array.is_static       = array->is_static;
3644                         array_type->array.is_variable     = array->is_variable;
3645                         array_type->array.size_expression = size_expression;
3646
3647                         if (size_expression != NULL) {
3648                                 switch (is_constant_expression(size_expression)) {
3649                                 case EXPR_CLASS_CONSTANT: {
3650                                         long const size = fold_constant_to_int(size_expression);
3651                                         array_type->array.size          = size;
3652                                         array_type->array.size_constant = true;
3653                                         /* §6.7.5.2:1  If the expression is a constant expression,
3654                                          * it shall have a value greater than zero. */
3655                                         if (size < 0) {
3656                                                 errorf(&size_expression->base.source_position,
3657                                                            "size of array must be greater than zero");
3658                                         } else if (size == 0 && !GNU_MODE) {
3659                                                 errorf(&size_expression->base.source_position,
3660                                                            "size of array must be greater than zero (zero length arrays are a GCC extension)");
3661                                         }
3662                                         break;
3663                                 }
3664
3665                                 case EXPR_CLASS_VARIABLE:
3666                                         array_type->array.is_vla = true;
3667                                         break;
3668
3669                                 case EXPR_CLASS_ERROR:
3670                                         break;
3671                                 }
3672                         }
3673
3674                         type_t *skipped_type = skip_typeref(type);
3675                         /* §6.7.5.2:1 */
3676                         if (is_type_incomplete(skipped_type)) {
3677                                 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3678                         } else if (is_type_function(skipped_type)) {
3679                                 errorf(pos, "array of functions is not allowed");
3680                         }
3681                         type = identify_new_type(array_type);
3682                         continue;
3683                 }
3684                 }
3685                 internal_errorf(pos, "invalid type construction found");
3686         }
3687
3688         return type;
3689 }
3690
3691 static type_t *automatic_type_conversion(type_t *orig_type);
3692
3693 static type_t *semantic_parameter(const source_position_t *pos,
3694                                   type_t *type,
3695                                   const declaration_specifiers_t *specifiers,
3696                                   entity_t const *const param)
3697 {
3698         /* §6.7.5.3:7  A declaration of a parameter as ``array of type''
3699          *             shall be adjusted to ``qualified pointer to type'',
3700          *             [...]
3701          * §6.7.5.3:8  A declaration of a parameter as ``function returning
3702          *             type'' shall be adjusted to ``pointer to function
3703          *             returning type'', as in 6.3.2.1. */
3704         type = automatic_type_conversion(type);
3705
3706         if (specifiers->is_inline && is_type_valid(type)) {
3707                 errorf(pos, "'%N' declared 'inline'", param);
3708         }
3709
3710         /* §6.9.1:6  The declarations in the declaration list shall contain
3711          *           no storage-class specifier other than register and no
3712          *           initializations. */
3713         if (specifiers->thread_local || (
3714                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3715                         specifiers->storage_class != STORAGE_CLASS_REGISTER)
3716            ) {
3717                 errorf(pos, "invalid storage class for '%N'", param);
3718         }
3719
3720         /* delay test for incomplete type, because we might have (void)
3721          * which is legal but incomplete... */
3722
3723         return type;
3724 }
3725
3726 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3727                                   declarator_flags_t flags)
3728 {
3729         parse_declarator_env_t env;
3730         memset(&env, 0, sizeof(env));
3731         env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3732
3733         construct_type_t *construct_type = parse_inner_declarator(&env);
3734         type_t           *orig_type      =
3735                 construct_declarator_type(construct_type, specifiers->type);
3736         type_t           *type           = skip_typeref(orig_type);
3737
3738         if (construct_type != NULL) {
3739                 obstack_free(&temp_obst, construct_type);
3740         }
3741
3742         attribute_t *attributes = parse_attributes(env.attributes);
3743         /* append (shared) specifier attribute behind attributes of this
3744          * declarator */
3745         attribute_t **anchor = &attributes;
3746         while (*anchor != NULL)
3747                 anchor = &(*anchor)->next;
3748         *anchor = specifiers->attributes;
3749
3750         entity_t *entity;
3751         if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3752                 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3753                 entity->base.source_position = env.source_position;
3754                 entity->typedefe.type        = orig_type;
3755
3756                 if (anonymous_entity != NULL) {
3757                         if (is_type_compound(type)) {
3758                                 assert(anonymous_entity->compound.alias == NULL);
3759                                 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3760                                        anonymous_entity->kind == ENTITY_UNION);
3761                                 anonymous_entity->compound.alias = entity;
3762                                 anonymous_entity = NULL;
3763                         } else if (is_type_enum(type)) {
3764                                 assert(anonymous_entity->enume.alias == NULL);
3765                                 assert(anonymous_entity->kind == ENTITY_ENUM);
3766                                 anonymous_entity->enume.alias = entity;
3767                                 anonymous_entity = NULL;
3768                         }
3769                 }
3770         } else {
3771                 /* create a declaration type entity */
3772                 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3773                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3774
3775                         if (env.symbol != NULL) {
3776                                 if (specifiers->is_inline && is_type_valid(type)) {
3777                                         errorf(&env.source_position,
3778                                                         "compound member '%Y' declared 'inline'", env.symbol);
3779                                 }
3780
3781                                 if (specifiers->thread_local ||
3782                                                 specifiers->storage_class != STORAGE_CLASS_NONE) {
3783                                         errorf(&env.source_position,
3784                                                         "compound member '%Y' must have no storage class",
3785                                                         env.symbol);
3786                                 }
3787                         }
3788                 } else if (flags & DECL_IS_PARAMETER) {
3789                         entity    = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3790                         orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3791                 } else if (is_type_function(type)) {
3792                         entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3793                         entity->function.is_inline      = specifiers->is_inline;
3794                         entity->function.elf_visibility = default_visibility;
3795                         entity->function.parameters     = env.parameters;
3796
3797                         if (env.symbol != NULL) {
3798                                 /* this needs fixes for C++ */
3799                                 bool in_function_scope = current_function != NULL;
3800
3801                                 if (specifiers->thread_local || (
3802                                                         specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3803                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3804                                                         (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3805                                                 )) {
3806                                         errorf(&env.source_position, "invalid storage class for '%N'", entity);
3807                                 }
3808                         }
3809                 } else {
3810                         entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3811                         entity->variable.elf_visibility = default_visibility;
3812                         entity->variable.thread_local   = specifiers->thread_local;
3813
3814                         if (env.symbol != NULL) {
3815                                 if (specifiers->is_inline && is_type_valid(type)) {
3816                                         errorf(&env.source_position, "'%N' declared 'inline'", entity);
3817                                 }
3818
3819                                 bool invalid_storage_class = false;
3820                                 if (current_scope == file_scope) {
3821                                         if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3822                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3823                                                         specifiers->storage_class != STORAGE_CLASS_STATIC) {
3824                                                 invalid_storage_class = true;
3825                                         }
3826                                 } else {
3827                                         if (specifiers->thread_local &&
3828                                                         specifiers->storage_class == STORAGE_CLASS_NONE) {
3829                                                 invalid_storage_class = true;
3830                                         }
3831                                 }
3832                                 if (invalid_storage_class) {
3833                                         errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3834                                 }
3835                         }
3836                 }
3837
3838                 entity->base.source_position   = env.symbol != NULL ? env.source_position : specifiers->source_position;
3839                 entity->declaration.type       = orig_type;
3840                 entity->declaration.alignment  = get_type_alignment(orig_type);
3841                 entity->declaration.modifiers  = env.modifiers;
3842                 entity->declaration.attributes = attributes;
3843
3844                 storage_class_t storage_class = specifiers->storage_class;
3845                 entity->declaration.declared_storage_class = storage_class;
3846
3847                 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3848                         storage_class = STORAGE_CLASS_AUTO;
3849                 entity->declaration.storage_class = storage_class;
3850         }
3851
3852         if (attributes != NULL) {
3853                 handle_entity_attributes(attributes, entity);
3854         }
3855
3856         if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3857                 adapt_special_functions(&entity->function);
3858         }
3859
3860         return entity;
3861 }
3862
3863 static type_t *parse_abstract_declarator(type_t *base_type)
3864 {
3865         parse_declarator_env_t env;
3866         memset(&env, 0, sizeof(env));
3867         env.may_be_abstract = true;
3868         env.must_be_abstract = true;
3869
3870         construct_type_t *construct_type = parse_inner_declarator(&env);
3871
3872         type_t *result = construct_declarator_type(construct_type, base_type);
3873         if (construct_type != NULL) {
3874                 obstack_free(&temp_obst, construct_type);
3875         }
3876         result = handle_type_attributes(env.attributes, result);
3877
3878         return result;
3879 }
3880
3881 /**
3882  * Check if the declaration of main is suspicious.  main should be a
3883  * function with external linkage, returning int, taking either zero
3884  * arguments, two, or three arguments of appropriate types, ie.
3885  *
3886  * int main([ int argc, char **argv [, char **env ] ]).
3887  *
3888  * @param decl    the declaration to check
3889  * @param type    the function type of the declaration
3890  */
3891 static void check_main(const entity_t *entity)
3892 {
3893         const source_position_t *pos = &entity->base.source_position;
3894         if (entity->kind != ENTITY_FUNCTION) {
3895                 warningf(WARN_MAIN, pos, "'main' is not a function");
3896                 return;
3897         }
3898
3899         if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3900                 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3901         }
3902
3903         type_t *type = skip_typeref(entity->declaration.type);
3904         assert(is_type_function(type));
3905
3906         function_type_t const *const func_type = &type->function;
3907         type_t                *const ret_type  = func_type->return_type;
3908         if (!types_compatible(skip_typeref(ret_type), type_int)) {
3909                 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3910         }
3911         const function_parameter_t *parm = func_type->parameters;
3912         if (parm != NULL) {
3913                 type_t *const first_type        = skip_typeref(parm->type);
3914                 type_t *const first_type_unqual = get_unqualified_type(first_type);
3915                 if (!types_compatible(first_type_unqual, type_int)) {
3916                         warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3917                 }
3918                 parm = parm->next;
3919                 if (parm != NULL) {
3920                         type_t *const second_type = skip_typeref(parm->type);
3921                         type_t *const second_type_unqual
3922                                 = get_unqualified_type(second_type);
3923                         if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3924                                 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3925                         }
3926                         parm = parm->next;
3927                         if (parm != NULL) {
3928                                 type_t *const third_type = skip_typeref(parm->type);
3929                                 type_t *const third_type_unqual
3930                                         = get_unqualified_type(third_type);
3931                                 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3932                                         warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3933                                 }
3934                                 parm = parm->next;
3935                                 if (parm != NULL)
3936                                         goto warn_arg_count;
3937                         }
3938                 } else {
3939 warn_arg_count:
3940                         warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3941                 }
3942         }
3943 }
3944
3945 /**
3946  * Check if a symbol is the equal to "main".
3947  */
3948 static bool is_sym_main(const symbol_t *const sym)
3949 {
3950         return streq(sym->string, "main");
3951 }
3952
3953 static void error_redefined_as_different_kind(const source_position_t *pos,
3954                 const entity_t *old, entity_kind_t new_kind)
3955 {
3956         char              const *const what = get_entity_kind_name(new_kind);
3957         source_position_t const *const ppos = &old->base.source_position;
3958         errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3959 }
3960
3961 static bool is_entity_valid(entity_t *const ent)
3962 {
3963         if (is_declaration(ent)) {
3964                 return is_type_valid(skip_typeref(ent->declaration.type));
3965         } else if (ent->kind == ENTITY_TYPEDEF) {
3966                 return is_type_valid(skip_typeref(ent->typedefe.type));
3967         }
3968         return true;
3969 }
3970
3971 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3972 {
3973         for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3974                 if (attributes_equal(tattr, attr))
3975                         return true;
3976         }
3977         return false;
3978 }
3979
3980 /**
3981  * test wether new_list contains any attributes not included in old_list
3982  */
3983 static bool has_new_attributes(const attribute_t *old_list,
3984                                const attribute_t *new_list)
3985 {
3986         for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3987                 if (!contains_attribute(old_list, attr))
3988                         return true;
3989         }
3990         return false;
3991 }
3992
3993 /**
3994  * Merge in attributes from an attribute list (probably from a previous
3995  * declaration with the same name). Warning: destroys the old structure
3996  * of the attribute list - don't reuse attributes after this call.
3997  */
3998 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3999 {
4000         attribute_t *next;
4001         for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4002                 next = attr->next;
4003                 if (contains_attribute(decl->attributes, attr))
4004                         continue;
4005
4006                 /* move attribute to new declarations attributes list */
4007                 attr->next       = decl->attributes;
4008                 decl->attributes = attr;
4009         }
4010 }
4011
4012 /**
4013  * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4014  * for various problems that occur for multiple definitions
4015  */
4016 entity_t *record_entity(entity_t *entity, const bool is_definition)
4017 {
4018         const symbol_t *const    symbol  = entity->base.symbol;
4019         const namespace_tag_t    namespc = (namespace_tag_t)entity->base.namespc;
4020         const source_position_t *pos     = &entity->base.source_position;
4021
4022         /* can happen in error cases */
4023         if (symbol == NULL)
4024                 return entity;
4025
4026         entity_t *const previous_entity = get_entity(symbol, namespc);
4027         /* pushing the same entity twice will break the stack structure */
4028         assert(previous_entity != entity);
4029
4030         if (entity->kind == ENTITY_FUNCTION) {
4031                 type_t *const orig_type = entity->declaration.type;
4032                 type_t *const type      = skip_typeref(orig_type);
4033
4034                 assert(is_type_function(type));
4035                 if (type->function.unspecified_parameters &&
4036                     previous_entity == NULL               &&
4037                     !entity->declaration.implicit) {
4038                         warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4039                 }
4040
4041                 if (current_scope == file_scope && is_sym_main(symbol)) {
4042                         check_main(entity);
4043                 }
4044         }
4045
4046         if (is_declaration(entity)                                    &&
4047             entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4048             current_scope != file_scope                               &&
4049             !entity->declaration.implicit) {
4050                 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4051         }
4052
4053         if (previous_entity != NULL) {
4054                 source_position_t const *const ppos = &previous_entity->base.source_position;
4055
4056                 if (previous_entity->base.parent_scope == &current_function->parameters &&
4057                                 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4058                         assert(previous_entity->kind == ENTITY_PARAMETER);
4059                         errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4060                         goto finish;
4061                 }
4062
4063                 if (previous_entity->base.parent_scope == current_scope) {
4064                         if (previous_entity->kind != entity->kind) {
4065                                 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4066                                         error_redefined_as_different_kind(pos, previous_entity,
4067                                                         entity->kind);
4068                                 }
4069                                 goto finish;
4070                         }
4071                         if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4072                                 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4073                                 goto finish;
4074                         }
4075                         if (previous_entity->kind == ENTITY_TYPEDEF) {
4076                                 type_t *const type      = skip_typeref(entity->typedefe.type);
4077                                 type_t *const prev_type
4078                                         = skip_typeref(previous_entity->typedefe.type);
4079                                 if (c_mode & _CXX) {
4080                                         /* C++ allows double typedef if they are identical
4081                                          * (after skipping typedefs) */
4082                                         if (type == prev_type)
4083                                                 goto finish;
4084                                 } else {
4085                                         /* GCC extension: redef in system headers is allowed */
4086                                         if ((pos->is_system_header || ppos->is_system_header) &&
4087                                             types_compatible(type, prev_type))
4088                                                 goto finish;
4089                                 }
4090                                 errorf(pos, "redefinition of '%N' (declared %P)",
4091                                        entity, ppos);
4092                                 goto finish;
4093                         }
4094
4095                         /* at this point we should have only VARIABLES or FUNCTIONS */
4096                         assert(is_declaration(previous_entity) && is_declaration(entity));
4097
4098                         declaration_t *const prev_decl = &previous_entity->declaration;
4099                         declaration_t *const decl      = &entity->declaration;
4100
4101                         /* can happen for K&R style declarations */
4102                         if (prev_decl->type       == NULL             &&
4103                                         previous_entity->kind == ENTITY_PARAMETER &&
4104                                         entity->kind          == ENTITY_PARAMETER) {
4105                                 prev_decl->type                   = decl->type;
4106                                 prev_decl->storage_class          = decl->storage_class;
4107                                 prev_decl->declared_storage_class = decl->declared_storage_class;
4108                                 prev_decl->modifiers              = decl->modifiers;
4109                                 return previous_entity;
4110                         }
4111
4112                         type_t *const type      = skip_typeref(decl->type);
4113                         type_t *const prev_type = skip_typeref(prev_decl->type);
4114
4115                         if (!types_compatible(type, prev_type)) {
4116                                 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4117                         } else {
4118                                 unsigned old_storage_class = prev_decl->storage_class;
4119
4120                                 if (is_definition                     &&
4121                                                 !prev_decl->used                  &&
4122                                                 !(prev_decl->modifiers & DM_USED) &&
4123                                                 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4124                                         warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4125                                 }
4126
4127                                 storage_class_t new_storage_class = decl->storage_class;
4128
4129                                 /* pretend no storage class means extern for function
4130                                  * declarations (except if the previous declaration is neither
4131                                  * none nor extern) */
4132                                 if (entity->kind == ENTITY_FUNCTION) {
4133                                         /* the previous declaration could have unspecified parameters or
4134                                          * be a typedef, so use the new type */
4135                                         if (prev_type->function.unspecified_parameters || is_definition)
4136                                                 prev_decl->type = type;
4137
4138                                         switch (old_storage_class) {
4139                                                 case STORAGE_CLASS_NONE:
4140                                                         old_storage_class = STORAGE_CLASS_EXTERN;
4141                                                         /* FALLTHROUGH */
4142
4143                                                 case STORAGE_CLASS_EXTERN:
4144                                                         if (is_definition) {
4145                                                                 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4146                                                                         warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4147                                                                 }
4148                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
4149                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
4150                                                         }
4151                                                         break;
4152
4153                                                 default:
4154                                                         break;
4155                                         }
4156                                 } else if (is_type_incomplete(prev_type)) {
4157                                         prev_decl->type = type;
4158                                 }
4159
4160                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4161                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
4162
4163 warn_redundant_declaration: ;
4164                                         bool has_new_attrs
4165                                                 = has_new_attributes(prev_decl->attributes,
4166                                                                      decl->attributes);
4167                                         if (has_new_attrs) {
4168                                                 merge_in_attributes(decl, prev_decl->attributes);
4169                                         } else if (!is_definition        &&
4170                                                         is_type_valid(prev_type) &&
4171                                                         !pos->is_system_header) {
4172                                                 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4173                                         }
4174                                 } else if (current_function == NULL) {
4175                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
4176                                                         new_storage_class == STORAGE_CLASS_STATIC) {
4177                                                 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4178                                         } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4179                                                 prev_decl->storage_class          = STORAGE_CLASS_NONE;
4180                                                 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4181                                         } else {
4182                                                 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4183                                                 if (c_mode & _CXX)
4184                                                         goto error_redeclaration;
4185                                                 goto warn_redundant_declaration;
4186                                         }
4187                                 } else if (is_type_valid(prev_type)) {
4188                                         if (old_storage_class == new_storage_class) {
4189 error_redeclaration:
4190                                                 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4191                                         } else {
4192                                                 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4193                                         }
4194                                 }
4195                         }
4196
4197                         prev_decl->modifiers |= decl->modifiers;
4198                         if (entity->kind == ENTITY_FUNCTION) {
4199                                 previous_entity->function.is_inline |= entity->function.is_inline;
4200                         }
4201                         return previous_entity;
4202                 }
4203
4204                 warning_t why;
4205                 if (is_warn_on(why = WARN_SHADOW) ||
4206                     (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4207                         char const *const what = get_entity_kind_name(previous_entity->kind);
4208                         warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4209                 }
4210         }
4211
4212         if (entity->kind == ENTITY_FUNCTION) {
4213                 if (is_definition &&
4214                                 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4215                                 !is_sym_main(symbol)) {
4216                         if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4217                                 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4218                         } else {
4219                                 goto warn_missing_declaration;
4220                         }
4221                 }
4222         } else if (entity->kind == ENTITY_VARIABLE) {
4223                 if (current_scope                     == file_scope &&
4224                                 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4225                                 !entity->declaration.implicit) {
4226 warn_missing_declaration:
4227                         warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4228                 }
4229         }
4230
4231 finish:
4232         assert(entity->base.parent_scope == NULL);
4233         assert(current_scope != NULL);
4234
4235         entity->base.parent_scope = current_scope;
4236         environment_push(entity);
4237         append_entity(current_scope, entity);
4238
4239         return entity;
4240 }
4241
4242 static void parser_error_multiple_definition(entity_t *entity,
4243                 const source_position_t *source_position)
4244 {
4245         errorf(source_position, "multiple definition of '%Y' (declared %P)",
4246                entity->base.symbol, &entity->base.source_position);
4247 }
4248
4249 static bool is_declaration_specifier(const token_t *token)
4250 {
4251         switch (token->kind) {
4252                 DECLARATION_START
4253                         return true;
4254                 case T_IDENTIFIER:
4255                         return is_typedef_symbol(token->identifier.symbol);
4256
4257                 default:
4258                         return false;
4259         }
4260 }
4261
4262 static void parse_init_declarator_rest(entity_t *entity)
4263 {
4264         type_t *orig_type = type_error_type;
4265
4266         if (entity->base.kind == ENTITY_TYPEDEF) {
4267                 source_position_t const *const pos = &entity->base.source_position;
4268                 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4269         } else {
4270                 assert(is_declaration(entity));
4271                 orig_type = entity->declaration.type;
4272         }
4273
4274         type_t *type = skip_typeref(orig_type);
4275
4276         if (entity->kind == ENTITY_VARIABLE
4277                         && entity->variable.initializer != NULL) {
4278                 parser_error_multiple_definition(entity, HERE);
4279         }
4280         eat('=');
4281
4282         declaration_t *const declaration = &entity->declaration;
4283         bool must_be_constant = false;
4284         if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4285             entity->base.parent_scope  == file_scope) {
4286                 must_be_constant = true;
4287         }
4288
4289         if (is_type_function(type)) {
4290                 source_position_t const *const pos = &entity->base.source_position;
4291                 errorf(pos, "'%N' is initialized like a variable", entity);
4292                 orig_type = type_error_type;
4293         }
4294
4295         parse_initializer_env_t env;
4296         env.type             = orig_type;
4297         env.must_be_constant = must_be_constant;
4298         env.entity           = entity;
4299
4300         initializer_t *initializer = parse_initializer(&env);
4301
4302         if (entity->kind == ENTITY_VARIABLE) {
4303                 /* §6.7.5:22  array initializers for arrays with unknown size
4304                  * determine the array type size */
4305                 declaration->type            = env.type;
4306                 entity->variable.initializer = initializer;
4307         }
4308 }
4309
4310 /* parse rest of a declaration without any declarator */
4311 static void parse_anonymous_declaration_rest(
4312                 const declaration_specifiers_t *specifiers)
4313 {
4314         eat(';');
4315         anonymous_entity = NULL;
4316
4317         source_position_t const *const pos = &specifiers->source_position;
4318         if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4319                         specifiers->thread_local) {
4320                 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4321         }
4322
4323         type_t *type = specifiers->type;
4324         switch (type->kind) {
4325                 case TYPE_COMPOUND_STRUCT:
4326                 case TYPE_COMPOUND_UNION: {
4327                         if (type->compound.compound->base.symbol == NULL) {
4328                                 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4329                         }
4330                         break;
4331                 }
4332
4333                 case TYPE_ENUM:
4334                         break;
4335
4336                 default:
4337                         warningf(WARN_OTHER, pos, "empty declaration");
4338                         break;
4339         }
4340 }
4341
4342 static void check_variable_type_complete(entity_t *ent)
4343 {
4344         if (ent->kind != ENTITY_VARIABLE)
4345                 return;
4346
4347         /* §6.7:7  If an identifier for an object is declared with no linkage, the
4348          *         type for the object shall be complete [...] */
4349         declaration_t *decl = &ent->declaration;
4350         if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4351                         decl->storage_class == STORAGE_CLASS_STATIC)
4352                 return;
4353
4354         type_t *const type = skip_typeref(decl->type);
4355         if (!is_type_incomplete(type))
4356                 return;
4357
4358         /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4359          * are given length one. */
4360         if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4361                 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4362                 return;
4363         }
4364
4365         errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4366 }
4367
4368
4369 static void parse_declaration_rest(entity_t *ndeclaration,
4370                 const declaration_specifiers_t *specifiers,
4371                 parsed_declaration_func         finished_declaration,
4372                 declarator_flags_t              flags)
4373 {
4374         add_anchor_token(';');
4375         add_anchor_token(',');
4376         while (true) {
4377                 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4378
4379                 if (token.kind == '=') {
4380                         parse_init_declarator_rest(entity);
4381                 } else if (entity->kind == ENTITY_VARIABLE) {
4382                         /* ISO/IEC 14882:1998(E) §8.5.3:3  The initializer can be omitted
4383                          * [...] where the extern specifier is explicitly used. */
4384                         declaration_t *decl = &entity->declaration;
4385                         if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4386                                 type_t *type = decl->type;
4387                                 if (is_type_reference(skip_typeref(type))) {
4388                                         source_position_t const *const pos = &entity->base.source_position;
4389                                         errorf(pos, "reference '%#N' must be initialized", entity);
4390                                 }
4391                         }
4392                 }
4393
4394                 check_variable_type_complete(entity);
4395
4396                 if (!next_if(','))
4397                         break;
4398
4399                 add_anchor_token('=');
4400                 ndeclaration = parse_declarator(specifiers, flags);
4401                 rem_anchor_token('=');
4402         }
4403         expect(';', end_error);
4404
4405 end_error:
4406         anonymous_entity = NULL;
4407         rem_anchor_token(';');
4408         rem_anchor_token(',');
4409 }
4410
4411 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4412 {
4413         symbol_t *symbol = entity->base.symbol;
4414         if (symbol == NULL)
4415                 return entity;
4416
4417         assert(entity->base.namespc == NAMESPACE_NORMAL);
4418         entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4419         if (previous_entity == NULL
4420                         || previous_entity->base.parent_scope != current_scope) {
4421                 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4422                        symbol);
4423                 return entity;
4424         }
4425
4426         if (is_definition) {
4427                 errorf(HERE, "'%N' is initialised", entity);
4428         }
4429
4430         return record_entity(entity, false);
4431 }
4432
4433 static void parse_declaration(parsed_declaration_func finished_declaration,
4434                               declarator_flags_t      flags)
4435 {
4436         add_anchor_token(';');
4437         declaration_specifiers_t specifiers;
4438         parse_declaration_specifiers(&specifiers);
4439         rem_anchor_token(';');
4440
4441         if (token.kind == ';') {
4442                 parse_anonymous_declaration_rest(&specifiers);
4443         } else {
4444                 entity_t *entity = parse_declarator(&specifiers, flags);
4445                 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4446         }
4447 }
4448
4449 /* §6.5.2.2:6 */
4450 static type_t *get_default_promoted_type(type_t *orig_type)
4451 {
4452         type_t *result = orig_type;
4453
4454         type_t *type = skip_typeref(orig_type);
4455         if (is_type_integer(type)) {
4456                 result = promote_integer(type);
4457         } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4458                 result = type_double;
4459         }
4460
4461         return result;
4462 }
4463
4464 static void parse_kr_declaration_list(entity_t *entity)
4465 {
4466         if (entity->kind != ENTITY_FUNCTION)
4467                 return;
4468
4469         type_t *type = skip_typeref(entity->declaration.type);
4470         assert(is_type_function(type));
4471         if (!type->function.kr_style_parameters)
4472                 return;
4473
4474         add_anchor_token('{');
4475
4476         PUSH_SCOPE(&entity->function.parameters);
4477
4478         entity_t *parameter = entity->function.parameters.entities;
4479         for ( ; parameter != NULL; parameter = parameter->base.next) {
4480                 assert(parameter->base.parent_scope == NULL);
4481                 parameter->base.parent_scope = current_scope;
4482                 environment_push(parameter);
4483         }
4484
4485         /* parse declaration list */
4486         for (;;) {
4487                 switch (token.kind) {
4488                         DECLARATION_START
4489                         /* This covers symbols, which are no type, too, and results in
4490                          * better error messages.  The typical cases are misspelled type
4491                          * names and missing includes. */
4492                         case T_IDENTIFIER:
4493                                 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4494                                 break;
4495                         default:
4496                                 goto decl_list_end;
4497                 }
4498         }
4499 decl_list_end:
4500
4501         POP_SCOPE();
4502
4503         /* update function type */
4504         type_t *new_type = duplicate_type(type);
4505
4506         function_parameter_t  *parameters = NULL;
4507         function_parameter_t **anchor     = &parameters;
4508
4509         /* did we have an earlier prototype? */
4510         entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4511         if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4512                 proto_type = NULL;
4513
4514         function_parameter_t *proto_parameter = NULL;
4515         if (proto_type != NULL) {
4516                 type_t *proto_type_type = proto_type->declaration.type;
4517                 proto_parameter         = proto_type_type->function.parameters;
4518                 /* If a K&R function definition has a variadic prototype earlier, then
4519                  * make the function definition variadic, too. This should conform to
4520                  * §6.7.5.3:15 and §6.9.1:8. */
4521                 new_type->function.variadic = proto_type_type->function.variadic;
4522         } else {
4523                 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4524                  * prototype */
4525                 new_type->function.unspecified_parameters = true;
4526         }
4527
4528         bool need_incompatible_warning = false;
4529         parameter = entity->function.parameters.entities;
4530         for (; parameter != NULL; parameter = parameter->base.next,
4531                         proto_parameter =
4532                                 proto_parameter == NULL ? NULL : proto_parameter->next) {
4533                 if (parameter->kind != ENTITY_PARAMETER)
4534                         continue;
4535
4536                 type_t *parameter_type = parameter->declaration.type;
4537                 if (parameter_type == NULL) {
4538                         source_position_t const* const pos = &parameter->base.source_position;
4539                         if (strict_mode) {
4540                                 errorf(pos, "no type specified for function '%N'", parameter);
4541                                 parameter_type = type_error_type;
4542                         } else {
4543                                 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4544                                 parameter_type = type_int;
4545                         }
4546                         parameter->declaration.type = parameter_type;
4547                 }
4548
4549                 semantic_parameter_incomplete(parameter);
4550
4551                 /* we need the default promoted types for the function type */
4552                 type_t *not_promoted = parameter_type;
4553                 parameter_type       = get_default_promoted_type(parameter_type);
4554
4555                 /* gcc special: if the type of the prototype matches the unpromoted
4556                  * type don't promote */
4557                 if (!strict_mode && proto_parameter != NULL) {
4558                         type_t *proto_p_type = skip_typeref(proto_parameter->type);
4559                         type_t *promo_skip   = skip_typeref(parameter_type);
4560                         type_t *param_skip   = skip_typeref(not_promoted);
4561                         if (!types_compatible(proto_p_type, promo_skip)
4562                                 && types_compatible(proto_p_type, param_skip)) {
4563                                 /* don't promote */
4564                                 need_incompatible_warning = true;
4565                                 parameter_type = not_promoted;
4566                         }
4567                 }
4568                 function_parameter_t *const function_parameter
4569                         = allocate_parameter(parameter_type);
4570
4571                 *anchor = function_parameter;
4572                 anchor  = &function_parameter->next;
4573         }
4574
4575         new_type->function.parameters = parameters;
4576         new_type = identify_new_type(new_type);
4577
4578         if (need_incompatible_warning) {
4579                 symbol_t          const *const sym  = entity->base.symbol;
4580                 source_position_t const *const pos  = &entity->base.source_position;
4581                 source_position_t const *const ppos = &proto_type->base.source_position;
4582                 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4583         }
4584         entity->declaration.type = new_type;
4585
4586         rem_anchor_token('{');
4587 }
4588
4589 static bool first_err = true;
4590
4591 /**
4592  * When called with first_err set, prints the name of the current function,
4593  * else does noting.
4594  */
4595 static void print_in_function(void)
4596 {
4597         if (first_err) {
4598                 first_err = false;
4599                 char const *const file = current_function->base.base.source_position.input_name;
4600                 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4601         }
4602 }
4603
4604 /**
4605  * Check if all labels are defined in the current function.
4606  * Check if all labels are used in the current function.
4607  */
4608 static void check_labels(void)
4609 {
4610         for (const goto_statement_t *goto_statement = goto_first;
4611             goto_statement != NULL;
4612             goto_statement = goto_statement->next) {
4613                 label_t *label = goto_statement->label;
4614                 if (label->base.source_position.input_name == NULL) {
4615                         print_in_function();
4616                         source_position_t const *const pos = &goto_statement->base.source_position;
4617                         errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4618                  }
4619         }
4620
4621         if (is_warn_on(WARN_UNUSED_LABEL)) {
4622                 for (const label_statement_t *label_statement = label_first;
4623                          label_statement != NULL;
4624                          label_statement = label_statement->next) {
4625                         label_t *label = label_statement->label;
4626
4627                         if (! label->used) {
4628                                 print_in_function();
4629                                 source_position_t const *const pos = &label_statement->base.source_position;
4630                                 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4631                         }
4632                 }
4633         }
4634 }
4635
4636 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4637 {
4638         entity_t const *const end = last != NULL ? last->base.next : NULL;
4639         for (; entity != end; entity = entity->base.next) {
4640                 if (!is_declaration(entity))
4641                         continue;
4642
4643                 declaration_t *declaration = &entity->declaration;
4644                 if (declaration->implicit)
4645                         continue;
4646
4647                 if (!declaration->used) {
4648                         print_in_function();
4649                         warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4650                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4651                         print_in_function();
4652                         warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4653                 }
4654         }
4655 }
4656
4657 static void check_unused_variables(statement_t *const stmt, void *const env)
4658 {
4659         (void)env;
4660
4661         switch (stmt->kind) {
4662                 case STATEMENT_DECLARATION: {
4663                         declaration_statement_t const *const decls = &stmt->declaration;
4664                         warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4665                         return;
4666                 }
4667
4668                 case STATEMENT_FOR:
4669                         warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4670                         return;
4671
4672                 default:
4673                         return;
4674         }
4675 }
4676
4677 /**
4678  * Check declarations of current_function for unused entities.
4679  */
4680 static void check_declarations(void)
4681 {
4682         if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4683                 const scope_t *scope = &current_function->parameters;
4684
4685                 /* do not issue unused warnings for main */
4686                 if (!is_sym_main(current_function->base.base.symbol)) {
4687                         warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4688                 }
4689         }
4690         if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4691                 walk_statements(current_function->statement, check_unused_variables,
4692                                 NULL);
4693         }
4694 }
4695
4696 static int determine_truth(expression_t const* const cond)
4697 {
4698         return
4699                 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4700                 fold_constant_to_bool(cond)                         ? 1 :
4701                 -1;
4702 }
4703
4704 static void check_reachable(statement_t *);
4705 static bool reaches_end;
4706
4707 static bool expression_returns(expression_t const *const expr)
4708 {
4709         switch (expr->kind) {
4710                 case EXPR_CALL: {
4711                         expression_t const *const func = expr->call.function;
4712                         type_t       const *const type = skip_typeref(func->base.type);
4713                         if (type->kind == TYPE_POINTER) {
4714                                 type_t const *const points_to
4715                                         = skip_typeref(type->pointer.points_to);
4716                                 if (points_to->kind == TYPE_FUNCTION
4717                                     && points_to->function.modifiers & DM_NORETURN)
4718                                         return false;
4719                         }
4720
4721                         if (!expression_returns(func))
4722                                 return false;
4723
4724                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4725                                 if (!expression_returns(arg->expression))
4726                                         return false;
4727                         }
4728
4729                         return true;
4730                 }
4731
4732                 case EXPR_REFERENCE:
4733                 case EXPR_ENUM_CONSTANT:
4734                 case EXPR_LITERAL_CASES:
4735                 case EXPR_STRING_LITERAL:
4736                 case EXPR_WIDE_STRING_LITERAL:
4737                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4738                 case EXPR_LABEL_ADDRESS:
4739                 case EXPR_CLASSIFY_TYPE:
4740                 case EXPR_SIZEOF: // TODO handle obscure VLA case
4741                 case EXPR_ALIGNOF:
4742                 case EXPR_FUNCNAME:
4743                 case EXPR_BUILTIN_CONSTANT_P:
4744                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4745                 case EXPR_OFFSETOF:
4746                 case EXPR_ERROR:
4747                         return true;
4748
4749                 case EXPR_STATEMENT: {
4750                         bool old_reaches_end = reaches_end;
4751                         reaches_end = false;
4752                         check_reachable(expr->statement.statement);
4753                         bool returns = reaches_end;
4754                         reaches_end = old_reaches_end;
4755                         return returns;
4756                 }
4757
4758                 case EXPR_CONDITIONAL:
4759                         // TODO handle constant expression
4760
4761                         if (!expression_returns(expr->conditional.condition))
4762                                 return false;
4763
4764                         if (expr->conditional.true_expression != NULL
4765                                         && expression_returns(expr->conditional.true_expression))
4766                                 return true;
4767
4768                         return expression_returns(expr->conditional.false_expression);
4769
4770                 case EXPR_SELECT:
4771                         return expression_returns(expr->select.compound);
4772
4773                 case EXPR_ARRAY_ACCESS:
4774                         return
4775                                 expression_returns(expr->array_access.array_ref) &&
4776                                 expression_returns(expr->array_access.index);
4777
4778                 case EXPR_VA_START:
4779                         return expression_returns(expr->va_starte.ap);
4780
4781                 case EXPR_VA_ARG:
4782                         return expression_returns(expr->va_arge.ap);
4783
4784                 case EXPR_VA_COPY:
4785                         return expression_returns(expr->va_copye.src);
4786
4787                 case EXPR_UNARY_CASES_MANDATORY:
4788                         return expression_returns(expr->unary.value);
4789
4790                 case EXPR_UNARY_THROW:
4791                         return false;
4792
4793                 case EXPR_BINARY_CASES:
4794                         // TODO handle constant lhs of && and ||
4795                         return
4796                                 expression_returns(expr->binary.left) &&
4797                                 expression_returns(expr->binary.right);
4798         }
4799
4800         panic("unhandled expression");
4801 }
4802
4803 static bool initializer_returns(initializer_t const *const init)
4804 {
4805         switch (init->kind) {
4806                 case INITIALIZER_VALUE:
4807                         return expression_returns(init->value.value);
4808
4809                 case INITIALIZER_LIST: {
4810                         initializer_t * const*       i       = init->list.initializers;
4811                         initializer_t * const* const end     = i + init->list.len;
4812                         bool                         returns = true;
4813                         for (; i != end; ++i) {
4814                                 if (!initializer_returns(*i))
4815                                         returns = false;
4816                         }
4817                         return returns;
4818                 }
4819
4820                 case INITIALIZER_STRING:
4821                 case INITIALIZER_WIDE_STRING:
4822                 case INITIALIZER_DESIGNATOR: // designators have no payload
4823                         return true;
4824         }
4825         panic("unhandled initializer");
4826 }
4827
4828 static bool noreturn_candidate;
4829
4830 static void check_reachable(statement_t *const stmt)
4831 {
4832         if (stmt->base.reachable)
4833                 return;
4834         if (stmt->kind != STATEMENT_DO_WHILE)
4835                 stmt->base.reachable = true;
4836
4837         statement_t *last = stmt;
4838         statement_t *next;
4839         switch (stmt->kind) {
4840                 case STATEMENT_ERROR:
4841                 case STATEMENT_EMPTY:
4842                 case STATEMENT_ASM:
4843                         next = stmt->base.next;
4844                         break;
4845
4846                 case STATEMENT_DECLARATION: {
4847                         declaration_statement_t const *const decl = &stmt->declaration;
4848                         entity_t                const *      ent  = decl->declarations_begin;
4849                         entity_t                const *const last_decl = decl->declarations_end;
4850                         if (ent != NULL) {
4851                                 for (;; ent = ent->base.next) {
4852                                         if (ent->kind                 == ENTITY_VARIABLE &&
4853                                             ent->variable.initializer != NULL            &&
4854                                             !initializer_returns(ent->variable.initializer)) {
4855                                                 return;
4856                                         }
4857                                         if (ent == last_decl)
4858                                                 break;
4859                                 }
4860                         }
4861                         next = stmt->base.next;
4862                         break;
4863                 }
4864
4865                 case STATEMENT_COMPOUND:
4866                         next = stmt->compound.statements;
4867                         if (next == NULL)
4868                                 next = stmt->base.next;
4869                         break;
4870
4871                 case STATEMENT_RETURN: {
4872                         expression_t const *const val = stmt->returns.value;
4873                         if (val == NULL || expression_returns(val))
4874                                 noreturn_candidate = false;
4875                         return;
4876                 }
4877
4878                 case STATEMENT_IF: {
4879                         if_statement_t const *const ifs  = &stmt->ifs;
4880                         expression_t   const *const cond = ifs->condition;
4881
4882                         if (!expression_returns(cond))
4883                                 return;
4884
4885                         int const val = determine_truth(cond);
4886
4887                         if (val >= 0)
4888                                 check_reachable(ifs->true_statement);
4889
4890                         if (val > 0)
4891                                 return;
4892
4893                         if (ifs->false_statement != NULL) {
4894                                 check_reachable(ifs->false_statement);
4895                                 return;
4896                         }
4897
4898                         next = stmt->base.next;
4899                         break;
4900                 }
4901
4902                 case STATEMENT_SWITCH: {
4903                         switch_statement_t const *const switchs = &stmt->switchs;
4904                         expression_t       const *const expr    = switchs->expression;
4905
4906                         if (!expression_returns(expr))
4907                                 return;
4908
4909                         if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4910                                 long                    const val      = fold_constant_to_int(expr);
4911                                 case_label_statement_t *      defaults = NULL;
4912                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4913                                         if (i->expression == NULL) {
4914                                                 defaults = i;
4915                                                 continue;
4916                                         }
4917
4918                                         if (i->first_case <= val && val <= i->last_case) {
4919                                                 check_reachable((statement_t*)i);
4920                                                 return;
4921                                         }
4922                                 }
4923
4924                                 if (defaults != NULL) {
4925                                         check_reachable((statement_t*)defaults);
4926                                         return;
4927                                 }
4928                         } else {
4929                                 bool has_default = false;
4930                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4931                                         if (i->expression == NULL)
4932                                                 has_default = true;
4933
4934                                         check_reachable((statement_t*)i);
4935                                 }
4936
4937                                 if (has_default)
4938                                         return;
4939                         }
4940
4941                         next = stmt->base.next;
4942                         break;
4943                 }
4944
4945                 case STATEMENT_EXPRESSION: {
4946                         /* Check for noreturn function call */
4947                         expression_t const *const expr = stmt->expression.expression;
4948                         if (!expression_returns(expr))
4949                                 return;
4950
4951                         next = stmt->base.next;
4952                         break;
4953                 }
4954
4955                 case STATEMENT_CONTINUE:
4956                         for (statement_t *parent = stmt;;) {
4957                                 parent = parent->base.parent;
4958                                 if (parent == NULL) /* continue not within loop */
4959                                         return;
4960
4961                                 next = parent;
4962                                 switch (parent->kind) {
4963                                         case STATEMENT_WHILE:    goto continue_while;
4964                                         case STATEMENT_DO_WHILE: goto continue_do_while;
4965                                         case STATEMENT_FOR:      goto continue_for;
4966
4967                                         default: break;
4968                                 }
4969                         }
4970
4971                 case STATEMENT_BREAK:
4972                         for (statement_t *parent = stmt;;) {
4973                                 parent = parent->base.parent;
4974                                 if (parent == NULL) /* break not within loop/switch */
4975                                         return;
4976
4977                                 switch (parent->kind) {
4978                                         case STATEMENT_SWITCH:
4979                                         case STATEMENT_WHILE:
4980                                         case STATEMENT_DO_WHILE:
4981                                         case STATEMENT_FOR:
4982                                                 last = parent;
4983                                                 next = parent->base.next;
4984                                                 goto found_break_parent;
4985
4986                                         default: break;
4987                                 }
4988                         }
4989 found_break_parent:
4990                         break;
4991
4992                 case STATEMENT_COMPUTED_GOTO: {
4993                         if (!expression_returns(stmt->computed_goto.expression))
4994                                 return;
4995
4996                         statement_t *parent = stmt->base.parent;
4997                         if (parent == NULL) /* top level goto */
4998                                 return;
4999                         next = parent;
5000                         break;
5001                 }
5002
5003                 case STATEMENT_GOTO:
5004                         next = stmt->gotos.label->statement;
5005                         if (next == NULL) /* missing label */
5006                                 return;
5007                         break;
5008
5009                 case STATEMENT_LABEL:
5010                         next = stmt->label.statement;
5011                         break;
5012
5013                 case STATEMENT_CASE_LABEL:
5014                         next = stmt->case_label.statement;
5015                         break;
5016
5017                 case STATEMENT_WHILE: {
5018                         while_statement_t const *const whiles = &stmt->whiles;
5019                         expression_t      const *const cond   = whiles->condition;
5020
5021                         if (!expression_returns(cond))
5022                                 return;
5023
5024                         int const val = determine_truth(cond);
5025
5026                         if (val >= 0)
5027                                 check_reachable(whiles->body);
5028
5029                         if (val > 0)
5030                                 return;
5031
5032                         next = stmt->base.next;
5033                         break;
5034                 }
5035
5036                 case STATEMENT_DO_WHILE:
5037                         next = stmt->do_while.body;
5038                         break;
5039
5040                 case STATEMENT_FOR: {
5041                         for_statement_t *const fors = &stmt->fors;
5042
5043                         if (fors->condition_reachable)
5044                                 return;
5045                         fors->condition_reachable = true;
5046
5047                         expression_t const *const cond = fors->condition;
5048
5049                         int val;
5050                         if (cond == NULL) {
5051                                 val = 1;
5052                         } else if (expression_returns(cond)) {
5053                                 val = determine_truth(cond);
5054                         } else {
5055                                 return;
5056                         }
5057
5058                         if (val >= 0)
5059                                 check_reachable(fors->body);
5060
5061                         if (val > 0)
5062                                 return;
5063
5064                         next = stmt->base.next;
5065                         break;
5066                 }
5067
5068                 case STATEMENT_MS_TRY: {
5069                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
5070                         check_reachable(ms_try->try_statement);
5071                         next = ms_try->final_statement;
5072                         break;
5073                 }
5074
5075                 case STATEMENT_LEAVE: {
5076                         statement_t *parent = stmt;
5077                         for (;;) {
5078                                 parent = parent->base.parent;
5079                                 if (parent == NULL) /* __leave not within __try */
5080                                         return;
5081
5082                                 if (parent->kind == STATEMENT_MS_TRY) {
5083                                         last = parent;
5084                                         next = parent->ms_try.final_statement;
5085                                         break;
5086                                 }
5087                         }
5088                         break;
5089                 }
5090
5091                 default:
5092                         panic("invalid statement kind");
5093         }
5094
5095         while (next == NULL) {
5096                 next = last->base.parent;
5097                 if (next == NULL) {
5098                         noreturn_candidate = false;
5099
5100                         type_t *const type = skip_typeref(current_function->base.type);
5101                         assert(is_type_function(type));
5102                         type_t *const ret  = skip_typeref(type->function.return_type);
5103                         if (!is_type_void(ret) &&
5104                             is_type_valid(ret) &&
5105                             !is_sym_main(current_function->base.base.symbol)) {
5106                                 source_position_t const *const pos = &stmt->base.source_position;
5107                                 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5108                         }
5109                         return;
5110                 }
5111
5112                 switch (next->kind) {
5113                         case STATEMENT_ERROR:
5114                         case STATEMENT_EMPTY:
5115                         case STATEMENT_DECLARATION:
5116                         case STATEMENT_EXPRESSION:
5117                         case STATEMENT_ASM:
5118                         case STATEMENT_RETURN:
5119                         case STATEMENT_CONTINUE:
5120                         case STATEMENT_BREAK:
5121                         case STATEMENT_COMPUTED_GOTO:
5122                         case STATEMENT_GOTO:
5123                         case STATEMENT_LEAVE:
5124                                 panic("invalid control flow in function");
5125
5126                         case STATEMENT_COMPOUND:
5127                                 if (next->compound.stmt_expr) {
5128                                         reaches_end = true;
5129                                         return;
5130                                 }
5131                                 /* FALLTHROUGH */
5132                         case STATEMENT_IF:
5133                         case STATEMENT_SWITCH:
5134                         case STATEMENT_LABEL:
5135                         case STATEMENT_CASE_LABEL:
5136                                 last = next;
5137                                 next = next->base.next;
5138                                 break;
5139
5140                         case STATEMENT_WHILE: {
5141 continue_while:
5142                                 if (next->base.reachable)
5143                                         return;
5144                                 next->base.reachable = true;
5145
5146                                 while_statement_t const *const whiles = &next->whiles;
5147                                 expression_t      const *const cond   = whiles->condition;
5148
5149                                 if (!expression_returns(cond))
5150                                         return;
5151
5152                                 int const val = determine_truth(cond);
5153
5154                                 if (val >= 0)
5155                                         check_reachable(whiles->body);
5156
5157                                 if (val > 0)
5158                                         return;
5159
5160                                 last = next;
5161                                 next = next->base.next;
5162                                 break;
5163                         }
5164
5165                         case STATEMENT_DO_WHILE: {
5166 continue_do_while:
5167                                 if (next->base.reachable)
5168                                         return;
5169                                 next->base.reachable = true;
5170
5171                                 do_while_statement_t const *const dw   = &next->do_while;
5172                                 expression_t         const *const cond = dw->condition;
5173
5174                                 if (!expression_returns(cond))
5175                                         return;
5176
5177                                 int const val = determine_truth(cond);
5178
5179                                 if (val >= 0)
5180                                         check_reachable(dw->body);
5181
5182                                 if (val > 0)
5183                                         return;
5184
5185                                 last = next;
5186                                 next = next->base.next;
5187                                 break;
5188                         }
5189
5190                         case STATEMENT_FOR: {
5191 continue_for:;
5192                                 for_statement_t *const fors = &next->fors;
5193
5194                                 fors->step_reachable = true;
5195
5196                                 if (fors->condition_reachable)
5197                                         return;
5198                                 fors->condition_reachable = true;
5199
5200                                 expression_t const *const cond = fors->condition;
5201
5202                                 int val;
5203                                 if (cond == NULL) {
5204                                         val = 1;
5205                                 } else if (expression_returns(cond)) {
5206                                         val = determine_truth(cond);
5207                                 } else {
5208                                         return;
5209                                 }
5210
5211                                 if (val >= 0)
5212                                         check_reachable(fors->body);
5213
5214                                 if (val > 0)
5215                                         return;
5216
5217                                 last = next;
5218                                 next = next->base.next;
5219                                 break;
5220                         }
5221
5222                         case STATEMENT_MS_TRY:
5223                                 last = next;
5224                                 next = next->ms_try.final_statement;
5225                                 break;
5226                 }
5227         }
5228
5229         check_reachable(next);
5230 }
5231
5232 static void check_unreachable(statement_t* const stmt, void *const env)
5233 {
5234         (void)env;
5235
5236         switch (stmt->kind) {
5237                 case STATEMENT_DO_WHILE:
5238                         if (!stmt->base.reachable) {
5239                                 expression_t const *const cond = stmt->do_while.condition;
5240                                 if (determine_truth(cond) >= 0) {
5241                                         source_position_t const *const pos = &cond->base.source_position;
5242                                         warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5243                                 }
5244                         }
5245                         return;
5246
5247                 case STATEMENT_FOR: {
5248                         for_statement_t const* const fors = &stmt->fors;
5249
5250                         // if init and step are unreachable, cond is unreachable, too
5251                         if (!stmt->base.reachable && !fors->step_reachable) {
5252                                 goto warn_unreachable;
5253                         } else {
5254                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
5255                                         source_position_t const *const pos = &fors->initialisation->base.source_position;
5256                                         warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5257                                 }
5258
5259                                 if (!fors->condition_reachable && fors->condition != NULL) {
5260                                         source_position_t const *const pos = &fors->condition->base.source_position;
5261                                         warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5262                                 }
5263
5264                                 if (!fors->step_reachable && fors->step != NULL) {
5265                                         source_position_t const *const pos = &fors->step->base.source_position;
5266                                         warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5267                                 }
5268                         }
5269                         return;
5270                 }
5271
5272                 case STATEMENT_COMPOUND:
5273                         if (stmt->compound.statements != NULL)
5274                                 return;
5275                         goto warn_unreachable;
5276
5277                 case STATEMENT_DECLARATION: {
5278                         /* Only warn if there is at least one declarator with an initializer.
5279                          * This typically occurs in switch statements. */
5280                         declaration_statement_t const *const decl = &stmt->declaration;
5281                         entity_t                const *      ent  = decl->declarations_begin;
5282                         entity_t                const *const last = decl->declarations_end;
5283                         if (ent != NULL) {
5284                                 for (;; ent = ent->base.next) {
5285                                         if (ent->kind                 == ENTITY_VARIABLE &&
5286                                                         ent->variable.initializer != NULL) {
5287                                                 goto warn_unreachable;
5288                                         }
5289                                         if (ent == last)
5290                                                 return;
5291                                 }
5292                         }
5293                 }
5294
5295                 default:
5296 warn_unreachable:
5297                         if (!stmt->base.reachable) {
5298                                 source_position_t const *const pos = &stmt->base.source_position;
5299                                 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5300                         }
5301                         return;
5302         }
5303 }
5304
5305 static bool is_main(entity_t *entity)
5306 {
5307         static symbol_t *sym_main = NULL;
5308         if (sym_main == NULL) {
5309                 sym_main = symbol_table_insert("main");
5310         }
5311
5312         if (entity->base.symbol != sym_main)
5313                 return false;
5314         /* must be in outermost scope */
5315         if (entity->base.parent_scope != file_scope)
5316                 return false;
5317
5318         return true;
5319 }
5320
5321 static void parse_external_declaration(void)
5322 {
5323         /* function-definitions and declarations both start with declaration
5324          * specifiers */
5325         add_anchor_token(';');
5326         declaration_specifiers_t specifiers;
5327         parse_declaration_specifiers(&specifiers);
5328         rem_anchor_token(';');
5329
5330         /* must be a declaration */
5331         if (token.kind == ';') {
5332                 parse_anonymous_declaration_rest(&specifiers);
5333                 return;
5334         }
5335
5336         add_anchor_token(',');
5337         add_anchor_token('=');
5338         add_anchor_token(';');
5339         add_anchor_token('{');
5340
5341         /* declarator is common to both function-definitions and declarations */
5342         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5343
5344         rem_anchor_token('{');
5345         rem_anchor_token(';');
5346         rem_anchor_token('=');
5347         rem_anchor_token(',');
5348
5349         /* must be a declaration */
5350         switch (token.kind) {
5351                 case ',':
5352                 case ';':
5353                 case '=':
5354                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5355                                         DECL_FLAGS_NONE);
5356                         return;
5357         }
5358
5359         /* must be a function definition */
5360         parse_kr_declaration_list(ndeclaration);
5361
5362         if (token.kind != '{') {
5363                 parse_error_expected("while parsing function definition", '{', NULL);
5364                 eat_until_matching_token(';');
5365                 return;
5366         }
5367
5368         assert(is_declaration(ndeclaration));
5369         type_t *const orig_type = ndeclaration->declaration.type;
5370         type_t *      type      = skip_typeref(orig_type);
5371
5372         if (!is_type_function(type)) {
5373                 if (is_type_valid(type)) {
5374                         errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5375                 }
5376                 eat_block();
5377                 return;
5378         }
5379
5380         source_position_t const *const pos = &ndeclaration->base.source_position;
5381         if (is_typeref(orig_type)) {
5382                 /* §6.9.1:2 */
5383                 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5384         }
5385
5386         if (is_type_compound(skip_typeref(type->function.return_type))) {
5387                 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5388         }
5389         if (type->function.unspecified_parameters) {
5390                 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5391         } else {
5392                 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5393         }
5394
5395         /* §6.7.5.3:14 a function definition with () means no
5396          * parameters (and not unspecified parameters) */
5397         if (type->function.unspecified_parameters &&
5398                         type->function.parameters == NULL) {
5399                 type_t *copy                          = duplicate_type(type);
5400                 copy->function.unspecified_parameters = false;
5401                 type                                  = identify_new_type(copy);
5402
5403                 ndeclaration->declaration.type = type;
5404         }
5405
5406         entity_t *const entity = record_entity(ndeclaration, true);
5407         assert(entity->kind == ENTITY_FUNCTION);
5408         assert(ndeclaration->kind == ENTITY_FUNCTION);
5409
5410         function_t *const function = &entity->function;
5411         if (ndeclaration != entity) {
5412                 function->parameters = ndeclaration->function.parameters;
5413         }
5414         assert(is_declaration(entity));
5415         type = skip_typeref(entity->declaration.type);
5416
5417         PUSH_SCOPE(&function->parameters);
5418
5419         entity_t *parameter = function->parameters.entities;
5420         for (; parameter != NULL; parameter = parameter->base.next) {
5421                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5422                         parameter->base.parent_scope = current_scope;
5423                 }
5424                 assert(parameter->base.parent_scope == NULL
5425                                 || parameter->base.parent_scope == current_scope);
5426                 parameter->base.parent_scope = current_scope;
5427                 if (parameter->base.symbol == NULL) {
5428                         errorf(&parameter->base.source_position, "parameter name omitted");
5429                         continue;
5430                 }
5431                 environment_push(parameter);
5432         }
5433
5434         if (function->statement != NULL) {
5435                 parser_error_multiple_definition(entity, HERE);
5436                 eat_block();
5437         } else {
5438                 /* parse function body */
5439                 int         label_stack_top      = label_top();
5440                 function_t *old_current_function = current_function;
5441                 entity_t   *old_current_entity   = current_entity;
5442                 current_function                 = function;
5443                 current_entity                   = entity;
5444                 PUSH_PARENT(NULL);
5445
5446                 goto_first   = NULL;
5447                 goto_anchor  = &goto_first;
5448                 label_first  = NULL;
5449                 label_anchor = &label_first;
5450
5451                 statement_t *const body = parse_compound_statement(false);
5452                 function->statement = body;
5453                 first_err = true;
5454                 check_labels();
5455                 check_declarations();
5456                 if (is_warn_on(WARN_RETURN_TYPE)      ||
5457                     is_warn_on(WARN_UNREACHABLE_CODE) ||
5458                     (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5459                         noreturn_candidate = true;
5460                         check_reachable(body);
5461                         if (is_warn_on(WARN_UNREACHABLE_CODE))
5462                                 walk_statements(body, check_unreachable, NULL);
5463                         if (noreturn_candidate &&
5464                             !(function->base.modifiers & DM_NORETURN)) {
5465                                 source_position_t const *const pos = &body->base.source_position;
5466                                 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5467                         }
5468                 }
5469
5470                 if (is_main(entity) && enable_main_collect2_hack)
5471                         prepare_main_collect2(entity);
5472
5473                 POP_PARENT();
5474                 assert(current_function == function);
5475                 assert(current_entity   == entity);
5476                 current_entity   = old_current_entity;
5477                 current_function = old_current_function;
5478                 label_pop_to(label_stack_top);
5479         }
5480
5481         POP_SCOPE();
5482 }
5483
5484 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5485 {
5486         entity_t *iter = compound->members.entities;
5487         for (; iter != NULL; iter = iter->base.next) {
5488                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5489                         continue;
5490
5491                 if (iter->base.symbol == symbol) {
5492                         return iter;
5493                 } else if (iter->base.symbol == NULL) {
5494                         /* search in anonymous structs and unions */
5495                         type_t *type = skip_typeref(iter->declaration.type);
5496                         if (is_type_compound(type)) {
5497                                 if (find_compound_entry(type->compound.compound, symbol)
5498                                                 != NULL)
5499                                         return iter;
5500                         }
5501                         continue;
5502                 }
5503         }
5504
5505         return NULL;
5506 }
5507
5508 static void check_deprecated(const source_position_t *source_position,
5509                              const entity_t *entity)
5510 {
5511         if (!is_declaration(entity))
5512                 return;
5513         if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5514                 return;
5515
5516         source_position_t const *const epos = &entity->base.source_position;
5517         char              const *const msg  = get_deprecated_string(entity->declaration.attributes);
5518         if (msg != NULL) {
5519                 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5520         } else {
5521                 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5522         }
5523 }
5524
5525
5526 static expression_t *create_select(const source_position_t *pos,
5527                                    expression_t *addr,
5528                                    type_qualifiers_t qualifiers,
5529                                                                    entity_t *entry)
5530 {
5531         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5532
5533         check_deprecated(pos, entry);
5534
5535         expression_t *select          = allocate_expression_zero(EXPR_SELECT);
5536         select->select.compound       = addr;
5537         select->select.compound_entry = entry;
5538
5539         type_t *entry_type = entry->declaration.type;
5540         type_t *res_type   = get_qualified_type(entry_type, qualifiers);
5541
5542         /* bitfields need special treatment */
5543         if (entry->compound_member.bitfield) {
5544                 unsigned bit_size = entry->compound_member.bit_size;
5545                 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5546                 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5547                         res_type = type_int;
5548                 }
5549         }
5550
5551         /* we always do the auto-type conversions; the & and sizeof parser contains
5552          * code to revert this! */
5553         select->base.type = automatic_type_conversion(res_type);
5554
5555
5556         return select;
5557 }
5558
5559 /**
5560  * Find entry with symbol in compound. Search anonymous structs and unions and
5561  * creates implicit select expressions for them.
5562  * Returns the adress for the innermost compound.
5563  */
5564 static expression_t *find_create_select(const source_position_t *pos,
5565                                         expression_t *addr,
5566                                         type_qualifiers_t qualifiers,
5567                                         compound_t *compound, symbol_t *symbol)
5568 {
5569         entity_t *iter = compound->members.entities;
5570         for (; iter != NULL; iter = iter->base.next) {
5571                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5572                         continue;
5573
5574                 symbol_t *iter_symbol = iter->base.symbol;
5575                 if (iter_symbol == NULL) {
5576                         type_t *type = iter->declaration.type;
5577                         if (type->kind != TYPE_COMPOUND_STRUCT
5578                                         && type->kind != TYPE_COMPOUND_UNION)
5579                                 continue;
5580
5581                         compound_t *sub_compound = type->compound.compound;
5582
5583                         if (find_compound_entry(sub_compound, symbol) == NULL)
5584                                 continue;
5585
5586                         expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5587                         sub_addr->base.source_position = *pos;
5588                         sub_addr->base.implicit        = true;
5589                         return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5590                                                   symbol);
5591                 }
5592
5593                 if (iter_symbol == symbol) {
5594                         return create_select(pos, addr, qualifiers, iter);
5595                 }
5596         }
5597
5598         return NULL;
5599 }
5600
5601 static void parse_bitfield_member(entity_t *entity)
5602 {
5603         eat(':');
5604
5605         expression_t *size = parse_constant_expression();
5606         long          size_long;
5607
5608         assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5609         type_t *type = entity->declaration.type;
5610         if (!is_type_integer(skip_typeref(type))) {
5611                 errorf(HERE, "bitfield base type '%T' is not an integer type",
5612                            type);
5613         }
5614
5615         if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5616                 /* error already reported by parse_constant_expression */
5617                 size_long = get_type_size(type) * 8;
5618         } else {
5619                 size_long = fold_constant_to_int(size);
5620
5621                 const symbol_t *symbol = entity->base.symbol;
5622                 const symbol_t *user_symbol
5623                         = symbol == NULL ? sym_anonymous : symbol;
5624                 unsigned bit_size = get_type_size(type) * 8;
5625                 if (size_long < 0) {
5626                         errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5627                 } else if (size_long == 0 && symbol != NULL) {
5628                         errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5629                 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5630                         errorf(HERE, "width of bitfield '%Y' exceeds its type",
5631                                    user_symbol);
5632                 } else {
5633                         /* hope that people don't invent crazy types with more bits
5634                          * than our struct can hold */
5635                         assert(size_long <
5636                                    (1 << sizeof(entity->compound_member.bit_size)*8));
5637                 }
5638         }
5639
5640         entity->compound_member.bitfield = true;
5641         entity->compound_member.bit_size = (unsigned char)size_long;
5642 }
5643
5644 static void parse_compound_declarators(compound_t *compound,
5645                 const declaration_specifiers_t *specifiers)
5646 {
5647         do {
5648                 entity_t *entity;
5649
5650                 if (token.kind == ':') {
5651                         /* anonymous bitfield */
5652                         type_t *type = specifiers->type;
5653                         entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5654                                                                 NAMESPACE_NORMAL, NULL);
5655                         entity->base.source_position               = *HERE;
5656                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5657                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
5658                         entity->declaration.type                   = type;
5659
5660                         parse_bitfield_member(entity);
5661
5662                         attribute_t  *attributes = parse_attributes(NULL);
5663                         attribute_t **anchor     = &attributes;
5664                         while (*anchor != NULL)
5665                                 anchor = &(*anchor)->next;
5666                         *anchor = specifiers->attributes;
5667                         if (attributes != NULL) {
5668                                 handle_entity_attributes(attributes, entity);
5669                         }
5670                         entity->declaration.attributes = attributes;
5671
5672                         append_entity(&compound->members, entity);
5673                 } else {
5674                         entity = parse_declarator(specifiers,
5675                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5676                         source_position_t const *const pos = &entity->base.source_position;
5677                         if (entity->kind == ENTITY_TYPEDEF) {
5678                                 errorf(pos, "typedef not allowed as compound member");
5679                         } else {
5680                                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5681
5682                                 /* make sure we don't define a symbol multiple times */
5683                                 symbol_t *symbol = entity->base.symbol;
5684                                 if (symbol != NULL) {
5685                                         entity_t *prev = find_compound_entry(compound, symbol);
5686                                         if (prev != NULL) {
5687                                                 source_position_t const *const ppos = &prev->base.source_position;
5688                                                 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5689                                         }
5690                                 }
5691
5692                                 if (token.kind == ':') {
5693                                         parse_bitfield_member(entity);
5694
5695                                         attribute_t *attributes = parse_attributes(NULL);
5696                                         handle_entity_attributes(attributes, entity);
5697                                 } else {
5698                                         type_t *orig_type = entity->declaration.type;
5699                                         type_t *type      = skip_typeref(orig_type);
5700                                         if (is_type_function(type)) {
5701                                                 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5702                                         } else if (is_type_incomplete(type)) {
5703                                                 /* §6.7.2.1:16 flexible array member */
5704                                                 if (!is_type_array(type)       ||
5705                                                                 token.kind          != ';' ||
5706                                                                 look_ahead(1)->kind != '}') {
5707                                                         errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5708                                                 } else if (compound->members.entities == NULL) {
5709                                                         errorf(pos, "flexible array member in otherwise empty struct");
5710                                                 }
5711                                         }
5712                                 }
5713
5714                                 append_entity(&compound->members, entity);
5715                         }
5716                 }
5717         } while (next_if(','));
5718         expect(';', end_error);
5719
5720 end_error:
5721         anonymous_entity = NULL;
5722 }
5723
5724 static void parse_compound_type_entries(compound_t *compound)
5725 {
5726         eat('{');
5727         add_anchor_token('}');
5728
5729         for (;;) {
5730                 switch (token.kind) {
5731                         DECLARATION_START
5732                         case T___extension__:
5733                         case T_IDENTIFIER: {
5734                                 PUSH_EXTENSION();
5735                                 declaration_specifiers_t specifiers;
5736                                 parse_declaration_specifiers(&specifiers);
5737                                 parse_compound_declarators(compound, &specifiers);
5738                                 POP_EXTENSION();
5739                                 break;
5740                         }
5741
5742                         default:
5743                                 rem_anchor_token('}');
5744                                 expect('}', end_error);
5745 end_error:
5746                                 /* §6.7.2.1:7 */
5747                                 compound->complete = true;
5748                                 return;
5749                 }
5750         }
5751 }
5752
5753 static type_t *parse_typename(void)
5754 {
5755         declaration_specifiers_t specifiers;
5756         parse_declaration_specifiers(&specifiers);
5757         if (specifiers.storage_class != STORAGE_CLASS_NONE
5758                         || specifiers.thread_local) {
5759                 /* TODO: improve error message, user does probably not know what a
5760                  * storage class is...
5761                  */
5762                 errorf(&specifiers.source_position, "typename must not have a storage class");
5763         }
5764
5765         type_t *result = parse_abstract_declarator(specifiers.type);
5766
5767         return result;
5768 }
5769
5770
5771
5772
5773 typedef expression_t* (*parse_expression_function)(void);
5774 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5775
5776 typedef struct expression_parser_function_t expression_parser_function_t;
5777 struct expression_parser_function_t {
5778         parse_expression_function        parser;
5779         precedence_t                     infix_precedence;
5780         parse_expression_infix_function  infix_parser;
5781 };
5782
5783 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5784
5785 /**
5786  * Prints an error message if an expression was expected but not read
5787  */
5788 static expression_t *expected_expression_error(void)
5789 {
5790         /* skip the error message if the error token was read */
5791         if (token.kind != T_ERROR) {
5792                 errorf(HERE, "expected expression, got token %K", &token);
5793         }
5794         next_token();
5795
5796         return create_error_expression();
5797 }
5798
5799 static type_t *get_string_type(void)
5800 {
5801         return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5802 }
5803
5804 static type_t *get_wide_string_type(void)
5805 {
5806         return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5807 }
5808
5809 /**
5810  * Parse a string constant.
5811  */
5812 static expression_t *parse_string_literal(void)
5813 {
5814         source_position_t begin   = token.base.source_position;
5815         string_t          res     = token.string.string;
5816         bool              is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5817
5818         next_token();
5819         while (token.kind == T_STRING_LITERAL
5820                         || token.kind == T_WIDE_STRING_LITERAL) {
5821                 warn_string_concat(&token.base.source_position);
5822                 res = concat_strings(&res, &token.string.string);
5823                 next_token();
5824                 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5825         }
5826
5827         expression_t *literal;
5828         if (is_wide) {
5829                 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5830                 literal->base.type = get_wide_string_type();
5831         } else {
5832                 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5833                 literal->base.type = get_string_type();
5834         }
5835         literal->base.source_position = begin;
5836         literal->literal.value        = res;
5837
5838         return literal;
5839 }
5840
5841 /**
5842  * Parse a boolean constant.
5843  */
5844 static expression_t *parse_boolean_literal(bool value)
5845 {
5846         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5847         literal->base.type           = type_bool;
5848         literal->literal.value.begin = value ? "true" : "false";
5849         literal->literal.value.size  = value ? 4 : 5;
5850
5851         next_token();
5852         return literal;
5853 }
5854
5855 static void warn_traditional_suffix(void)
5856 {
5857         warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5858                  &token.number.suffix);
5859 }
5860
5861 static void check_integer_suffix(void)
5862 {
5863         const string_t *suffix = &token.number.suffix;
5864         if (suffix->size == 0)
5865                 return;
5866
5867         bool not_traditional = false;
5868         const char *c = suffix->begin;
5869         if (*c == 'l' || *c == 'L') {
5870                 ++c;
5871                 if (*c == *(c-1)) {
5872                         not_traditional = true;
5873                         ++c;
5874                         if (*c == 'u' || *c == 'U') {
5875                                 ++c;
5876                         }
5877                 } else if (*c == 'u' || *c == 'U') {
5878                         not_traditional = true;
5879                         ++c;
5880                 }
5881         } else if (*c == 'u' || *c == 'U') {
5882                 not_traditional = true;
5883                 ++c;
5884                 if (*c == 'l' || *c == 'L') {
5885                         ++c;
5886                         if (*c == *(c-1)) {
5887                                 ++c;
5888                         }
5889                 }
5890         }
5891         if (*c != '\0') {
5892                 errorf(&token.base.source_position,
5893                        "invalid suffix '%S' on integer constant", suffix);
5894         } else if (not_traditional) {
5895                 warn_traditional_suffix();
5896         }
5897 }
5898
5899 static type_t *check_floatingpoint_suffix(void)
5900 {
5901         const string_t *suffix = &token.number.suffix;
5902         type_t         *type   = type_double;
5903         if (suffix->size == 0)
5904                 return type;
5905
5906         bool not_traditional = false;
5907         const char *c = suffix->begin;
5908         if (*c == 'f' || *c == 'F') {
5909                 ++c;
5910                 type = type_float;
5911         } else if (*c == 'l' || *c == 'L') {
5912                 ++c;
5913                 type = type_long_double;
5914         }
5915         if (*c != '\0') {
5916                 errorf(&token.base.source_position,
5917                        "invalid suffix '%S' on floatingpoint constant", suffix);
5918         } else if (not_traditional) {
5919                 warn_traditional_suffix();
5920         }
5921
5922         return type;
5923 }
5924
5925 /**
5926  * Parse an integer constant.
5927  */
5928 static expression_t *parse_number_literal(void)
5929 {
5930         expression_kind_t  kind;
5931         type_t            *type;
5932
5933         switch (token.kind) {
5934         case T_INTEGER:
5935                 kind = EXPR_LITERAL_INTEGER;
5936                 check_integer_suffix();
5937                 type = type_int;
5938                 break;
5939         case T_INTEGER_OCTAL:
5940                 kind = EXPR_LITERAL_INTEGER_OCTAL;
5941                 check_integer_suffix();
5942                 type = type_int;
5943                 break;
5944         case T_INTEGER_HEXADECIMAL:
5945                 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5946                 check_integer_suffix();
5947                 type = type_int;
5948                 break;
5949         case T_FLOATINGPOINT:
5950                 kind = EXPR_LITERAL_FLOATINGPOINT;
5951                 type = check_floatingpoint_suffix();
5952                 break;
5953         case T_FLOATINGPOINT_HEXADECIMAL:
5954                 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5955                 type = check_floatingpoint_suffix();
5956                 break;
5957         default:
5958                 panic("unexpected token type in parse_number_literal");
5959         }
5960
5961         expression_t *literal = allocate_expression_zero(kind);
5962         literal->base.type      = type;
5963         literal->literal.value  = token.number.number;
5964         literal->literal.suffix = token.number.suffix;
5965         next_token();
5966
5967         /* integer type depends on the size of the number and the size
5968          * representable by the types. The backend/codegeneration has to determine
5969          * that
5970          */
5971         determine_literal_type(&literal->literal);
5972         return literal;
5973 }
5974
5975 /**
5976  * Parse a character constant.
5977  */
5978 static expression_t *parse_character_constant(void)
5979 {
5980         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5981         literal->base.type     = c_mode & _CXX ? type_char : type_int;
5982         literal->literal.value = token.string.string;
5983
5984         size_t len = literal->literal.value.size;
5985         if (len > 1) {
5986                 if (!GNU_MODE && !(c_mode & _C99)) {
5987                         errorf(HERE, "more than 1 character in character constant");
5988                 } else {
5989                         literal->base.type = type_int;
5990                         warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5991                 }
5992         }
5993
5994         next_token();
5995         return literal;
5996 }
5997
5998 /**
5999  * Parse a wide character constant.
6000  */
6001 static expression_t *parse_wide_character_constant(void)
6002 {
6003         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6004         literal->base.type     = type_int;
6005         literal->literal.value = token.string.string;
6006
6007         size_t len = wstrlen(&literal->literal.value);
6008         if (len > 1) {
6009                 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6010         }
6011
6012         next_token();
6013         return literal;
6014 }
6015
6016 static entity_t *create_implicit_function(symbol_t *symbol,
6017                 const source_position_t *source_position)
6018 {
6019         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
6020         ntype->function.return_type            = type_int;
6021         ntype->function.unspecified_parameters = true;
6022         ntype->function.linkage                = LINKAGE_C;
6023         type_t *type                           = identify_new_type(ntype);
6024
6025         entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6026         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
6027         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6028         entity->declaration.type                   = type;
6029         entity->declaration.implicit               = true;
6030         entity->base.source_position               = *source_position;
6031
6032         if (current_scope != NULL)
6033                 record_entity(entity, false);
6034
6035         return entity;
6036 }
6037
6038 /**
6039  * Performs automatic type cast as described in §6.3.2.1.
6040  *
6041  * @param orig_type  the original type
6042  */
6043 static type_t *automatic_type_conversion(type_t *orig_type)
6044 {
6045         type_t *type = skip_typeref(orig_type);
6046         if (is_type_array(type)) {
6047                 array_type_t *array_type   = &type->array;
6048                 type_t       *element_type = array_type->element_type;
6049                 unsigned      qualifiers   = array_type->base.qualifiers;
6050
6051                 return make_pointer_type(element_type, qualifiers);
6052         }
6053
6054         if (is_type_function(type)) {
6055                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6056         }
6057
6058         return orig_type;
6059 }
6060
6061 /**
6062  * reverts the automatic casts of array to pointer types and function
6063  * to function-pointer types as defined §6.3.2.1
6064  */
6065 type_t *revert_automatic_type_conversion(const expression_t *expression)
6066 {
6067         switch (expression->kind) {
6068         case EXPR_REFERENCE: {
6069                 entity_t *entity = expression->reference.entity;
6070                 if (is_declaration(entity)) {
6071                         return entity->declaration.type;
6072                 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6073                         return entity->enum_value.enum_type;
6074                 } else {
6075                         panic("no declaration or enum in reference");
6076                 }
6077         }
6078
6079         case EXPR_SELECT: {
6080                 entity_t *entity = expression->select.compound_entry;
6081                 assert(is_declaration(entity));
6082                 type_t   *type   = entity->declaration.type;
6083                 return get_qualified_type(type, expression->base.type->base.qualifiers);
6084         }
6085
6086         case EXPR_UNARY_DEREFERENCE: {
6087                 const expression_t *const value = expression->unary.value;
6088                 type_t             *const type  = skip_typeref(value->base.type);
6089                 if (!is_type_pointer(type))
6090                         return type_error_type;
6091                 return type->pointer.points_to;
6092         }
6093
6094         case EXPR_ARRAY_ACCESS: {
6095                 const expression_t *array_ref = expression->array_access.array_ref;
6096                 type_t             *type_left = skip_typeref(array_ref->base.type);
6097                 if (!is_type_pointer(type_left))
6098                         return type_error_type;
6099                 return type_left->pointer.points_to;
6100         }
6101
6102         case EXPR_STRING_LITERAL: {
6103                 size_t size = expression->string_literal.value.size;
6104                 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6105         }
6106
6107         case EXPR_WIDE_STRING_LITERAL: {
6108                 size_t size = wstrlen(&expression->string_literal.value);
6109                 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6110         }
6111
6112         case EXPR_COMPOUND_LITERAL:
6113                 return expression->compound_literal.type;
6114
6115         default:
6116                 break;
6117         }
6118         return expression->base.type;
6119 }
6120
6121 /**
6122  * Find an entity matching a symbol in a scope.
6123  * Uses current scope if scope is NULL
6124  */
6125 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6126                                namespace_tag_t namespc)
6127 {
6128         if (scope == NULL) {
6129                 return get_entity(symbol, namespc);
6130         }
6131
6132         /* we should optimize here, if scope grows above a certain size we should
6133            construct a hashmap here... */
6134         entity_t *entity = scope->entities;
6135         for ( ; entity != NULL; entity = entity->base.next) {
6136                 if (entity->base.symbol == symbol
6137                     && (namespace_tag_t)entity->base.namespc == namespc)
6138                         break;
6139         }
6140
6141         return entity;
6142 }
6143
6144 static entity_t *parse_qualified_identifier(void)
6145 {
6146         /* namespace containing the symbol */
6147         symbol_t          *symbol;
6148         source_position_t  pos;
6149         const scope_t     *lookup_scope = NULL;
6150
6151         if (next_if(T_COLONCOLON))
6152                 lookup_scope = &unit->scope;
6153
6154         entity_t *entity;
6155         while (true) {
6156                 if (token.kind != T_IDENTIFIER) {
6157                         parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6158                         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6159                 }
6160                 symbol = token.identifier.symbol;
6161                 pos    = *HERE;
6162                 next_token();
6163
6164                 /* lookup entity */
6165                 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6166
6167                 if (!next_if(T_COLONCOLON))
6168                         break;
6169
6170                 switch (entity->kind) {
6171                 case ENTITY_NAMESPACE:
6172                         lookup_scope = &entity->namespacee.members;
6173                         break;
6174                 case ENTITY_STRUCT:
6175                 case ENTITY_UNION:
6176                 case ENTITY_CLASS:
6177                         lookup_scope = &entity->compound.members;
6178                         break;
6179                 default:
6180                         errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6181                                symbol, get_entity_kind_name(entity->kind));
6182
6183                         /* skip further qualifications */
6184                         while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6185
6186                         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6187                 }
6188         }
6189
6190         if (entity == NULL) {
6191                 if (!strict_mode && token.kind == '(') {
6192                         /* an implicitly declared function */
6193                         warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6194                                  "implicit declaration of function '%Y'", symbol);
6195                         entity = create_implicit_function(symbol, &pos);
6196                 } else {
6197                         errorf(&pos, "unknown identifier '%Y' found.", symbol);
6198                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
6199                 }
6200         }
6201
6202         return entity;
6203 }
6204
6205 static expression_t *parse_reference(void)
6206 {
6207         source_position_t const pos    = token.base.source_position;
6208         entity_t         *const entity = parse_qualified_identifier();
6209
6210         type_t *orig_type;
6211         if (is_declaration(entity)) {
6212                 orig_type = entity->declaration.type;
6213         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6214                 orig_type = entity->enum_value.enum_type;
6215         } else {
6216                 panic("expected declaration or enum value in reference");
6217         }
6218
6219         /* we always do the auto-type conversions; the & and sizeof parser contains
6220          * code to revert this! */
6221         type_t *type = automatic_type_conversion(orig_type);
6222
6223         expression_kind_t kind = EXPR_REFERENCE;
6224         if (entity->kind == ENTITY_ENUM_VALUE)
6225                 kind = EXPR_ENUM_CONSTANT;
6226
6227         expression_t *expression         = allocate_expression_zero(kind);
6228         expression->base.source_position = pos;
6229         expression->base.type            = type;
6230         expression->reference.entity     = entity;
6231
6232         /* this declaration is used */
6233         if (is_declaration(entity)) {
6234                 entity->declaration.used = true;
6235         }
6236
6237         if (entity->base.parent_scope != file_scope
6238                 && (current_function != NULL
6239                         && entity->base.parent_scope->depth < current_function->parameters.depth)
6240                 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6241                 if (entity->kind == ENTITY_VARIABLE) {
6242                         /* access of a variable from an outer function */
6243                         entity->variable.address_taken = true;
6244                 } else if (entity->kind == ENTITY_PARAMETER) {
6245                         entity->parameter.address_taken = true;
6246                 }
6247                 current_function->need_closure = true;
6248         }
6249
6250         check_deprecated(&pos, entity);
6251
6252         return expression;
6253 }
6254
6255 static bool semantic_cast(expression_t *cast)
6256 {
6257         expression_t            *expression      = cast->unary.value;
6258         type_t                  *orig_dest_type  = cast->base.type;
6259         type_t                  *orig_type_right = expression->base.type;
6260         type_t            const *dst_type        = skip_typeref(orig_dest_type);
6261         type_t            const *src_type        = skip_typeref(orig_type_right);
6262         source_position_t const *pos             = &cast->base.source_position;
6263
6264         /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6265         if (is_type_void(dst_type))
6266                 return true;
6267
6268         /* only integer and pointer can be casted to pointer */
6269         if (is_type_pointer(dst_type)  &&
6270             !is_type_pointer(src_type) &&
6271             !is_type_integer(src_type) &&
6272             is_type_valid(src_type)) {
6273                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6274                 return false;
6275         }
6276
6277         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6278                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6279                 return false;
6280         }
6281
6282         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6283                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6284                 return false;
6285         }
6286
6287         if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6288                 type_t *src = skip_typeref(src_type->pointer.points_to);
6289                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6290                 unsigned missing_qualifiers =
6291                         src->base.qualifiers & ~dst->base.qualifiers;
6292                 if (missing_qualifiers != 0) {
6293                         warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6294                 }
6295         }
6296         return true;
6297 }
6298
6299 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6300 {
6301         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6302         expression->base.source_position = *pos;
6303
6304         parse_initializer_env_t env;
6305         env.type             = type;
6306         env.entity           = NULL;
6307         env.must_be_constant = false;
6308         initializer_t *initializer = parse_initializer(&env);
6309         type = env.type;
6310
6311         expression->compound_literal.initializer = initializer;
6312         expression->compound_literal.type        = type;
6313         expression->base.type                    = automatic_type_conversion(type);
6314
6315         return expression;
6316 }
6317
6318 /**
6319  * Parse a cast expression.
6320  */
6321 static expression_t *parse_cast(void)
6322 {
6323         source_position_t const pos = *HERE;
6324
6325         eat('(');
6326         add_anchor_token(')');
6327
6328         type_t *type = parse_typename();
6329
6330         rem_anchor_token(')');
6331         expect(')', end_error);
6332
6333         if (token.kind == '{') {
6334                 return parse_compound_literal(&pos, type);
6335         }
6336
6337         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6338         cast->base.source_position = pos;
6339
6340         expression_t *value = parse_subexpression(PREC_CAST);
6341         cast->base.type   = type;
6342         cast->unary.value = value;
6343
6344         if (! semantic_cast(cast)) {
6345                 /* TODO: record the error in the AST. else it is impossible to detect it */
6346         }
6347
6348         return cast;
6349 end_error:
6350         return create_error_expression();
6351 }
6352
6353 /**
6354  * Parse a statement expression.
6355  */
6356 static expression_t *parse_statement_expression(void)
6357 {
6358         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6359
6360         eat('(');
6361         add_anchor_token(')');
6362
6363         statement_t *statement          = parse_compound_statement(true);
6364         statement->compound.stmt_expr   = true;
6365         expression->statement.statement = statement;
6366
6367         /* find last statement and use its type */
6368         type_t *type = type_void;
6369         const statement_t *stmt = statement->compound.statements;
6370         if (stmt != NULL) {
6371                 while (stmt->base.next != NULL)
6372                         stmt = stmt->base.next;
6373
6374                 if (stmt->kind == STATEMENT_EXPRESSION) {
6375                         type = stmt->expression.expression->base.type;
6376                 }
6377         } else {
6378                 source_position_t const *const pos = &expression->base.source_position;
6379                 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6380         }
6381         expression->base.type = type;
6382
6383         rem_anchor_token(')');
6384         expect(')', end_error);
6385
6386 end_error:
6387         return expression;
6388 }
6389
6390 /**
6391  * Parse a parenthesized expression.
6392  */
6393 static expression_t *parse_parenthesized_expression(void)
6394 {
6395         token_t const* const la1 = look_ahead(1);
6396         switch (la1->kind) {
6397         case '{':
6398                 /* gcc extension: a statement expression */
6399                 return parse_statement_expression();
6400
6401         case T_IDENTIFIER:
6402                 if (is_typedef_symbol(la1->identifier.symbol)) {
6403         DECLARATION_START
6404                         return parse_cast();
6405                 }
6406         }
6407
6408         eat('(');
6409         add_anchor_token(')');
6410         expression_t *result = parse_expression();
6411         result->base.parenthesized = true;
6412         rem_anchor_token(')');
6413         expect(')', end_error);
6414
6415 end_error:
6416         return result;
6417 }
6418
6419 static expression_t *parse_function_keyword(void)
6420 {
6421         /* TODO */
6422
6423         if (current_function == NULL) {
6424                 errorf(HERE, "'__func__' used outside of a function");
6425         }
6426
6427         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6428         expression->base.type     = type_char_ptr;
6429         expression->funcname.kind = FUNCNAME_FUNCTION;
6430
6431         next_token();
6432
6433         return expression;
6434 }
6435
6436 static expression_t *parse_pretty_function_keyword(void)
6437 {
6438         if (current_function == NULL) {
6439                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6440         }
6441
6442         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6443         expression->base.type     = type_char_ptr;
6444         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6445
6446         eat(T___PRETTY_FUNCTION__);
6447
6448         return expression;
6449 }
6450
6451 static expression_t *parse_funcsig_keyword(void)
6452 {
6453         if (current_function == NULL) {
6454                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6455         }
6456
6457         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6458         expression->base.type     = type_char_ptr;
6459         expression->funcname.kind = FUNCNAME_FUNCSIG;
6460
6461         eat(T___FUNCSIG__);
6462
6463         return expression;
6464 }
6465
6466 static expression_t *parse_funcdname_keyword(void)
6467 {
6468         if (current_function == NULL) {
6469                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6470         }
6471
6472         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6473         expression->base.type     = type_char_ptr;
6474         expression->funcname.kind = FUNCNAME_FUNCDNAME;
6475
6476         eat(T___FUNCDNAME__);
6477
6478         return expression;
6479 }
6480
6481 static designator_t *parse_designator(void)
6482 {
6483         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
6484         result->source_position = *HERE;
6485
6486         if (token.kind != T_IDENTIFIER) {
6487                 parse_error_expected("while parsing member designator",
6488                                      T_IDENTIFIER, NULL);
6489                 return NULL;
6490         }
6491         result->symbol = token.identifier.symbol;
6492         next_token();
6493
6494         designator_t *last_designator = result;
6495         while (true) {
6496                 if (next_if('.')) {
6497                         if (token.kind != T_IDENTIFIER) {
6498                                 parse_error_expected("while parsing member designator",
6499                                                      T_IDENTIFIER, NULL);
6500                                 return NULL;
6501                         }
6502                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6503                         designator->source_position = *HERE;
6504                         designator->symbol          = token.identifier.symbol;
6505                         next_token();
6506
6507                         last_designator->next = designator;
6508                         last_designator       = designator;
6509                         continue;
6510                 }
6511                 if (next_if('[')) {
6512                         add_anchor_token(']');
6513                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6514                         designator->source_position = *HERE;
6515                         designator->array_index     = parse_expression();
6516                         rem_anchor_token(']');
6517                         expect(']', end_error);
6518                         if (designator->array_index == NULL) {
6519                                 return NULL;
6520                         }
6521
6522                         last_designator->next = designator;
6523                         last_designator       = designator;
6524                         continue;
6525                 }
6526                 break;
6527         }
6528
6529         return result;
6530 end_error:
6531         return NULL;
6532 }
6533
6534 /**
6535  * Parse the __builtin_offsetof() expression.
6536  */
6537 static expression_t *parse_offsetof(void)
6538 {
6539         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6540         expression->base.type    = type_size_t;
6541
6542         eat(T___builtin_offsetof);
6543
6544         expect('(', end_error);
6545         add_anchor_token(',');
6546         type_t *type = parse_typename();
6547         rem_anchor_token(',');
6548         expect(',', end_error);
6549         add_anchor_token(')');
6550         designator_t *designator = parse_designator();
6551         rem_anchor_token(')');
6552         expect(')', end_error);
6553
6554         expression->offsetofe.type       = type;
6555         expression->offsetofe.designator = designator;
6556
6557         type_path_t path;
6558         memset(&path, 0, sizeof(path));
6559         path.top_type = type;
6560         path.path     = NEW_ARR_F(type_path_entry_t, 0);
6561
6562         descend_into_subtype(&path);
6563
6564         if (!walk_designator(&path, designator, true)) {
6565                 return create_error_expression();
6566         }
6567
6568         DEL_ARR_F(path.path);
6569
6570         return expression;
6571 end_error:
6572         return create_error_expression();
6573 }
6574
6575 /**
6576  * Parses a _builtin_va_start() expression.
6577  */
6578 static expression_t *parse_va_start(void)
6579 {
6580         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6581
6582         eat(T___builtin_va_start);
6583
6584         expect('(', end_error);
6585         add_anchor_token(',');
6586         expression->va_starte.ap = parse_assignment_expression();
6587         rem_anchor_token(',');
6588         expect(',', end_error);
6589         expression_t *const expr = parse_assignment_expression();
6590         if (expr->kind == EXPR_REFERENCE) {
6591                 entity_t *const entity = expr->reference.entity;
6592                 if (!current_function->base.type->function.variadic) {
6593                         errorf(&expr->base.source_position,
6594                                         "'va_start' used in non-variadic function");
6595                 } else if (entity->base.parent_scope != &current_function->parameters ||
6596                                 entity->base.next != NULL ||
6597                                 entity->kind != ENTITY_PARAMETER) {
6598                         errorf(&expr->base.source_position,
6599                                "second argument of 'va_start' must be last parameter of the current function");
6600                 } else {
6601                         expression->va_starte.parameter = &entity->variable;
6602                 }
6603                 expect(')', end_error);
6604                 return expression;
6605         }
6606         expect(')', end_error);
6607 end_error:
6608         return create_error_expression();
6609 }
6610
6611 /**
6612  * Parses a __builtin_va_arg() expression.
6613  */
6614 static expression_t *parse_va_arg(void)
6615 {
6616         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6617
6618         eat(T___builtin_va_arg);
6619
6620         expect('(', end_error);
6621         call_argument_t ap;
6622         ap.expression = parse_assignment_expression();
6623         expression->va_arge.ap = ap.expression;
6624         check_call_argument(type_valist, &ap, 1);
6625
6626         expect(',', end_error);
6627         expression->base.type = parse_typename();
6628         expect(')', end_error);
6629
6630         return expression;
6631 end_error:
6632         return create_error_expression();
6633 }
6634
6635 /**
6636  * Parses a __builtin_va_copy() expression.
6637  */
6638 static expression_t *parse_va_copy(void)
6639 {
6640         expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6641
6642         eat(T___builtin_va_copy);
6643
6644         expect('(', end_error);
6645         expression_t *dst = parse_assignment_expression();
6646         assign_error_t error = semantic_assign(type_valist, dst);
6647         report_assign_error(error, type_valist, dst, "call argument 1",
6648                             &dst->base.source_position);
6649         expression->va_copye.dst = dst;
6650
6651         expect(',', end_error);
6652
6653         call_argument_t src;
6654         src.expression = parse_assignment_expression();
6655         check_call_argument(type_valist, &src, 2);
6656         expression->va_copye.src = src.expression;
6657         expect(')', end_error);
6658
6659         return expression;
6660 end_error:
6661         return create_error_expression();
6662 }
6663
6664 /**
6665  * Parses a __builtin_constant_p() expression.
6666  */
6667 static expression_t *parse_builtin_constant(void)
6668 {
6669         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6670
6671         eat(T___builtin_constant_p);
6672
6673         expect('(', end_error);
6674         add_anchor_token(')');
6675         expression->builtin_constant.value = parse_assignment_expression();
6676         rem_anchor_token(')');
6677         expect(')', end_error);
6678         expression->base.type = type_int;
6679
6680         return expression;
6681 end_error:
6682         return create_error_expression();
6683 }
6684
6685 /**
6686  * Parses a __builtin_types_compatible_p() expression.
6687  */
6688 static expression_t *parse_builtin_types_compatible(void)
6689 {
6690         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6691
6692         eat(T___builtin_types_compatible_p);
6693
6694         expect('(', end_error);
6695         add_anchor_token(')');
6696         add_anchor_token(',');
6697         expression->builtin_types_compatible.left = parse_typename();
6698         rem_anchor_token(',');
6699         expect(',', end_error);
6700         expression->builtin_types_compatible.right = parse_typename();
6701         rem_anchor_token(')');
6702         expect(')', end_error);
6703         expression->base.type = type_int;
6704
6705         return expression;
6706 end_error:
6707         return create_error_expression();
6708 }
6709
6710 /**
6711  * Parses a __builtin_is_*() compare expression.
6712  */
6713 static expression_t *parse_compare_builtin(void)
6714 {
6715         expression_t *expression;
6716
6717         switch (token.kind) {
6718         case T___builtin_isgreater:
6719                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6720                 break;
6721         case T___builtin_isgreaterequal:
6722                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6723                 break;
6724         case T___builtin_isless:
6725                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6726                 break;
6727         case T___builtin_islessequal:
6728                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6729                 break;
6730         case T___builtin_islessgreater:
6731                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6732                 break;
6733         case T___builtin_isunordered:
6734                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6735                 break;
6736         default:
6737                 internal_errorf(HERE, "invalid compare builtin found");
6738         }
6739         expression->base.source_position = *HERE;
6740         next_token();
6741
6742         expect('(', end_error);
6743         expression->binary.left = parse_assignment_expression();
6744         expect(',', end_error);
6745         expression->binary.right = parse_assignment_expression();
6746         expect(')', end_error);
6747
6748         type_t *const orig_type_left  = expression->binary.left->base.type;
6749         type_t *const orig_type_right = expression->binary.right->base.type;
6750
6751         type_t *const type_left  = skip_typeref(orig_type_left);
6752         type_t *const type_right = skip_typeref(orig_type_right);
6753         if (!is_type_float(type_left) && !is_type_float(type_right)) {
6754                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6755                         type_error_incompatible("invalid operands in comparison",
6756                                 &expression->base.source_position, orig_type_left, orig_type_right);
6757                 }
6758         } else {
6759                 semantic_comparison(&expression->binary);
6760         }
6761
6762         return expression;
6763 end_error:
6764         return create_error_expression();
6765 }
6766
6767 /**
6768  * Parses a MS assume() expression.
6769  */
6770 static expression_t *parse_assume(void)
6771 {
6772         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6773
6774         eat(T__assume);
6775
6776         expect('(', end_error);
6777         add_anchor_token(')');
6778         expression->unary.value = parse_assignment_expression();
6779         rem_anchor_token(')');
6780         expect(')', end_error);
6781
6782         expression->base.type = type_void;
6783         return expression;
6784 end_error:
6785         return create_error_expression();
6786 }
6787
6788 /**
6789  * Return the label for the current symbol or create a new one.
6790  */
6791 static label_t *get_label(void)
6792 {
6793         assert(token.kind == T_IDENTIFIER);
6794         assert(current_function != NULL);
6795
6796         entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6797         /* If we find a local label, we already created the declaration. */
6798         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6799                 if (label->base.parent_scope != current_scope) {
6800                         assert(label->base.parent_scope->depth < current_scope->depth);
6801                         current_function->goto_to_outer = true;
6802                 }
6803         } else if (label == NULL || label->base.parent_scope != &current_function->parameters) {
6804                 /* There is no matching label in the same function, so create a new one. */
6805                 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6806                 label_push(label);
6807         }
6808
6809         eat(T_IDENTIFIER);
6810         return &label->label;
6811 }
6812
6813 /**
6814  * Parses a GNU && label address expression.
6815  */
6816 static expression_t *parse_label_address(void)
6817 {
6818         source_position_t source_position = token.base.source_position;
6819         eat(T_ANDAND);
6820         if (token.kind != T_IDENTIFIER) {
6821                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6822                 return create_error_expression();
6823         }
6824
6825         label_t *const label = get_label();
6826         label->used          = true;
6827         label->address_taken = true;
6828
6829         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6830         expression->base.source_position = source_position;
6831
6832         /* label address is treated as a void pointer */
6833         expression->base.type           = type_void_ptr;
6834         expression->label_address.label = label;
6835         return expression;
6836 }
6837
6838 /**
6839  * Parse a microsoft __noop expression.
6840  */
6841 static expression_t *parse_noop_expression(void)
6842 {
6843         /* the result is a (int)0 */
6844         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6845         literal->base.type           = type_int;
6846         literal->literal.value.begin = "__noop";
6847         literal->literal.value.size  = 6;
6848
6849         eat(T___noop);
6850
6851         if (token.kind == '(') {
6852                 /* parse arguments */
6853                 eat('(');
6854                 add_anchor_token(')');
6855                 add_anchor_token(',');
6856
6857                 if (token.kind != ')') do {
6858                         (void)parse_assignment_expression();
6859                 } while (next_if(','));
6860
6861                 rem_anchor_token(',');
6862                 rem_anchor_token(')');
6863         }
6864         expect(')', end_error);
6865
6866 end_error:
6867         return literal;
6868 }
6869
6870 /**
6871  * Parses a primary expression.
6872  */
6873 static expression_t *parse_primary_expression(void)
6874 {
6875         switch (token.kind) {
6876         case T_false:                        return parse_boolean_literal(false);
6877         case T_true:                         return parse_boolean_literal(true);
6878         case T_INTEGER:
6879         case T_INTEGER_OCTAL:
6880         case T_INTEGER_HEXADECIMAL:
6881         case T_FLOATINGPOINT:
6882         case T_FLOATINGPOINT_HEXADECIMAL:    return parse_number_literal();
6883         case T_CHARACTER_CONSTANT:           return parse_character_constant();
6884         case T_WIDE_CHARACTER_CONSTANT:      return parse_wide_character_constant();
6885         case T_STRING_LITERAL:
6886         case T_WIDE_STRING_LITERAL:          return parse_string_literal();
6887         case T___FUNCTION__:
6888         case T___func__:                     return parse_function_keyword();
6889         case T___PRETTY_FUNCTION__:          return parse_pretty_function_keyword();
6890         case T___FUNCSIG__:                  return parse_funcsig_keyword();
6891         case T___FUNCDNAME__:                return parse_funcdname_keyword();
6892         case T___builtin_offsetof:           return parse_offsetof();
6893         case T___builtin_va_start:           return parse_va_start();
6894         case T___builtin_va_arg:             return parse_va_arg();
6895         case T___builtin_va_copy:            return parse_va_copy();
6896         case T___builtin_isgreater:
6897         case T___builtin_isgreaterequal:
6898         case T___builtin_isless:
6899         case T___builtin_islessequal:
6900         case T___builtin_islessgreater:
6901         case T___builtin_isunordered:        return parse_compare_builtin();
6902         case T___builtin_constant_p:         return parse_builtin_constant();
6903         case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6904         case T__assume:                      return parse_assume();
6905         case T_ANDAND:
6906                 if (GNU_MODE)
6907                         return parse_label_address();
6908                 break;
6909
6910         case '(':                            return parse_parenthesized_expression();
6911         case T___noop:                       return parse_noop_expression();
6912
6913         /* Gracefully handle type names while parsing expressions. */
6914         case T_COLONCOLON:
6915                 return parse_reference();
6916         case T_IDENTIFIER:
6917                 if (!is_typedef_symbol(token.identifier.symbol)) {
6918                         return parse_reference();
6919                 }
6920                 /* FALLTHROUGH */
6921         DECLARATION_START {
6922                 source_position_t const  pos = *HERE;
6923                 declaration_specifiers_t specifiers;
6924                 parse_declaration_specifiers(&specifiers);
6925                 type_t const *const type = parse_abstract_declarator(specifiers.type);
6926                 errorf(&pos, "encountered type '%T' while parsing expression", type);
6927                 return create_error_expression();
6928         }
6929         }
6930
6931         errorf(HERE, "unexpected token %K, expected an expression", &token);
6932         eat_until_anchor();
6933         return create_error_expression();
6934 }
6935
6936 static expression_t *parse_array_expression(expression_t *left)
6937 {
6938         expression_t              *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6939         array_access_expression_t *const arr  = &expr->array_access;
6940
6941         eat('[');
6942         add_anchor_token(']');
6943
6944         expression_t *const inside = parse_expression();
6945
6946         type_t *const orig_type_left   = left->base.type;
6947         type_t *const orig_type_inside = inside->base.type;
6948
6949         type_t *const type_left   = skip_typeref(orig_type_left);
6950         type_t *const type_inside = skip_typeref(orig_type_inside);
6951
6952         expression_t *ref;
6953         expression_t *idx;
6954         type_t       *idx_type;
6955         type_t       *res_type;
6956         if (is_type_pointer(type_left)) {
6957                 ref      = left;
6958                 idx      = inside;
6959                 idx_type = type_inside;
6960                 res_type = type_left->pointer.points_to;
6961                 goto check_idx;
6962         } else if (is_type_pointer(type_inside)) {
6963                 arr->flipped = true;
6964                 ref      = inside;
6965                 idx      = left;
6966                 idx_type = type_left;
6967                 res_type = type_inside->pointer.points_to;
6968 check_idx:
6969                 res_type = automatic_type_conversion(res_type);
6970                 if (!is_type_integer(idx_type)) {
6971                         errorf(&idx->base.source_position, "array subscript must have integer type");
6972                 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6973                         source_position_t const *const pos = &idx->base.source_position;
6974                         warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6975                 }
6976         } else {
6977                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6978                         errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6979                 }
6980                 res_type = type_error_type;
6981                 ref      = left;
6982                 idx      = inside;
6983         }
6984
6985         arr->array_ref = ref;
6986         arr->index     = idx;
6987         arr->base.type = res_type;
6988
6989         rem_anchor_token(']');
6990         expect(']', end_error);
6991 end_error:
6992         return expr;
6993 }
6994
6995 static bool is_bitfield(const expression_t *expression)
6996 {
6997         return expression->kind == EXPR_SELECT
6998                 && expression->select.compound_entry->compound_member.bitfield;
6999 }
7000
7001 static expression_t *parse_typeprop(expression_kind_t const kind)
7002 {
7003         expression_t  *tp_expression = allocate_expression_zero(kind);
7004         tp_expression->base.type     = type_size_t;
7005
7006         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7007
7008         type_t       *orig_type;
7009         expression_t *expression;
7010         if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7011                 source_position_t const pos = *HERE;
7012                 next_token();
7013                 add_anchor_token(')');
7014                 orig_type = parse_typename();
7015                 rem_anchor_token(')');
7016                 expect(')', end_error);
7017
7018                 if (token.kind == '{') {
7019                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7020                          * starting with a compound literal */
7021                         expression = parse_compound_literal(&pos, orig_type);
7022                         goto typeprop_expression;
7023                 }
7024         } else {
7025                 expression = parse_subexpression(PREC_UNARY);
7026
7027 typeprop_expression:
7028                 if (is_bitfield(expression)) {
7029                         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7030                         errorf(&tp_expression->base.source_position,
7031                                    "operand of %s expression must not be a bitfield", what);
7032                 }
7033
7034                 tp_expression->typeprop.tp_expression = expression;
7035
7036                 orig_type = revert_automatic_type_conversion(expression);
7037                 expression->base.type = orig_type;
7038         }
7039
7040         tp_expression->typeprop.type   = orig_type;
7041         type_t const* const type       = skip_typeref(orig_type);
7042         char   const*       wrong_type = NULL;
7043         if (is_type_incomplete(type)) {
7044                 if (!is_type_void(type) || !GNU_MODE)
7045                         wrong_type = "incomplete";
7046         } else if (type->kind == TYPE_FUNCTION) {
7047                 if (GNU_MODE) {
7048                         /* function types are allowed (and return 1) */
7049                         source_position_t const *const pos  = &tp_expression->base.source_position;
7050                         char              const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7051                         warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7052                 } else {
7053                         wrong_type = "function";
7054                 }
7055         }
7056
7057         if (wrong_type != NULL) {
7058                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7059                 errorf(&tp_expression->base.source_position,
7060                                 "operand of %s expression must not be of %s type '%T'",
7061                                 what, wrong_type, orig_type);
7062         }
7063
7064 end_error:
7065         return tp_expression;
7066 }
7067
7068 static expression_t *parse_sizeof(void)
7069 {
7070         return parse_typeprop(EXPR_SIZEOF);
7071 }
7072
7073 static expression_t *parse_alignof(void)
7074 {
7075         return parse_typeprop(EXPR_ALIGNOF);
7076 }
7077
7078 static expression_t *parse_select_expression(expression_t *addr)
7079 {
7080         assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7081         bool select_left_arrow = (token.kind == T_MINUSGREATER);
7082         source_position_t const pos = *HERE;
7083         next_token();
7084
7085         if (token.kind != T_IDENTIFIER) {
7086                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7087                 return create_error_expression();
7088         }
7089         symbol_t *symbol = token.identifier.symbol;
7090         next_token();
7091
7092         type_t *const orig_type = addr->base.type;
7093         type_t *const type      = skip_typeref(orig_type);
7094
7095         type_t *type_left;
7096         bool    saw_error = false;
7097         if (is_type_pointer(type)) {
7098                 if (!select_left_arrow) {
7099                         errorf(&pos,
7100                                "request for member '%Y' in something not a struct or union, but '%T'",
7101                                symbol, orig_type);
7102                         saw_error = true;
7103                 }
7104                 type_left = skip_typeref(type->pointer.points_to);
7105         } else {
7106                 if (select_left_arrow && is_type_valid(type)) {
7107                         errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7108                         saw_error = true;
7109                 }
7110                 type_left = type;
7111         }
7112
7113         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7114             type_left->kind != TYPE_COMPOUND_UNION) {
7115
7116                 if (is_type_valid(type_left) && !saw_error) {
7117                         errorf(&pos,
7118                                "request for member '%Y' in something not a struct or union, but '%T'",
7119                                symbol, type_left);
7120                 }
7121                 return create_error_expression();
7122         }
7123
7124         compound_t *compound = type_left->compound.compound;
7125         if (!compound->complete) {
7126                 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7127                        symbol, type_left);
7128                 return create_error_expression();
7129         }
7130
7131         type_qualifiers_t  qualifiers = type_left->base.qualifiers;
7132         expression_t      *result     =
7133                 find_create_select(&pos, addr, qualifiers, compound, symbol);
7134
7135         if (result == NULL) {
7136                 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7137                 return create_error_expression();
7138         }
7139
7140         return result;
7141 }
7142
7143 static void check_call_argument(type_t          *expected_type,
7144                                 call_argument_t *argument, unsigned pos)
7145 {
7146         type_t         *expected_type_skip = skip_typeref(expected_type);
7147         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7148         expression_t   *arg_expr           = argument->expression;
7149         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7150
7151         /* handle transparent union gnu extension */
7152         if (is_type_union(expected_type_skip)
7153                         && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7154                 compound_t *union_decl  = expected_type_skip->compound.compound;
7155                 type_t     *best_type   = NULL;
7156                 entity_t   *entry       = union_decl->members.entities;
7157                 for ( ; entry != NULL; entry = entry->base.next) {
7158                         assert(is_declaration(entry));
7159                         type_t *decl_type = entry->declaration.type;
7160                         error = semantic_assign(decl_type, arg_expr);
7161                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7162                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7163                                 continue;
7164
7165                         if (error == ASSIGN_SUCCESS) {
7166                                 best_type = decl_type;
7167                         } else if (best_type == NULL) {
7168                                 best_type = decl_type;
7169                         }
7170                 }
7171
7172                 if (best_type != NULL) {
7173                         expected_type = best_type;
7174                 }
7175         }
7176
7177         error                = semantic_assign(expected_type, arg_expr);
7178         argument->expression = create_implicit_cast(arg_expr, expected_type);
7179
7180         if (error != ASSIGN_SUCCESS) {
7181                 /* report exact scope in error messages (like "in argument 3") */
7182                 char buf[64];
7183                 snprintf(buf, sizeof(buf), "call argument %u", pos);
7184                 report_assign_error(error, expected_type, arg_expr, buf,
7185                                     &arg_expr->base.source_position);
7186         } else {
7187                 type_t *const promoted_type = get_default_promoted_type(arg_type);
7188                 if (!types_compatible(expected_type_skip, promoted_type) &&
7189                     !types_compatible(expected_type_skip, type_void_ptr) &&
7190                     !types_compatible(type_void_ptr,      promoted_type)) {
7191                         /* Deliberately show the skipped types in this warning */
7192                         source_position_t const *const apos = &arg_expr->base.source_position;
7193                         warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7194                 }
7195         }
7196 }
7197
7198 /**
7199  * Handle the semantic restrictions of builtin calls
7200  */
7201 static void handle_builtin_argument_restrictions(call_expression_t *call)
7202 {
7203         entity_t *entity = call->function->reference.entity;
7204         switch (entity->function.btk) {
7205         case BUILTIN_FIRM:
7206                 switch (entity->function.b.firm_builtin_kind) {
7207                 case ir_bk_return_address:
7208                 case ir_bk_frame_address: {
7209                         /* argument must be constant */
7210                         call_argument_t *argument = call->arguments;
7211
7212                         if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7213                                 errorf(&call->base.source_position,
7214                                            "argument of '%Y' must be a constant expression",
7215                                            call->function->reference.entity->base.symbol);
7216                         }
7217                         break;
7218                 }
7219                 case ir_bk_prefetch:
7220                         /* second and third argument must be constant if existent */
7221                         if (call->arguments == NULL)
7222                                 break;
7223                         call_argument_t *rw = call->arguments->next;
7224                         call_argument_t *locality = NULL;
7225
7226                         if (rw != NULL) {
7227                                 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7228                                         errorf(&call->base.source_position,
7229                                                    "second argument of '%Y' must be a constant expression",
7230                                                    call->function->reference.entity->base.symbol);
7231                                 }
7232                                 locality = rw->next;
7233                         }
7234                         if (locality != NULL) {
7235                                 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7236                                         errorf(&call->base.source_position,
7237                                                    "third argument of '%Y' must be a constant expression",
7238                                                    call->function->reference.entity->base.symbol);
7239                                 }
7240                                 locality = rw->next;
7241                         }
7242                         break;
7243                 default:
7244                         break;
7245                 }
7246
7247         case BUILTIN_OBJECT_SIZE:
7248                 if (call->arguments == NULL)
7249                         break;
7250
7251                 call_argument_t *arg = call->arguments->next;
7252                 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7253                         errorf(&call->base.source_position,
7254                                    "second argument of '%Y' must be a constant expression",
7255                                    call->function->reference.entity->base.symbol);
7256                 }
7257                 break;
7258         default:
7259                 break;
7260         }
7261 }
7262
7263 /**
7264  * Parse a call expression, ie. expression '( ... )'.
7265  *
7266  * @param expression  the function address
7267  */
7268 static expression_t *parse_call_expression(expression_t *expression)
7269 {
7270         expression_t      *result = allocate_expression_zero(EXPR_CALL);
7271         call_expression_t *call   = &result->call;
7272         call->function            = expression;
7273
7274         type_t *const orig_type = expression->base.type;
7275         type_t *const type      = skip_typeref(orig_type);
7276
7277         function_type_t *function_type = NULL;
7278         if (is_type_pointer(type)) {
7279                 type_t *const to_type = skip_typeref(type->pointer.points_to);
7280
7281                 if (is_type_function(to_type)) {
7282                         function_type   = &to_type->function;
7283                         call->base.type = function_type->return_type;
7284                 }
7285         }
7286
7287         if (function_type == NULL && is_type_valid(type)) {
7288                 errorf(HERE,
7289                        "called object '%E' (type '%T') is not a pointer to a function",
7290                        expression, orig_type);
7291         }
7292
7293         /* parse arguments */
7294         eat('(');
7295         add_anchor_token(')');
7296         add_anchor_token(',');
7297
7298         if (token.kind != ')') {
7299                 call_argument_t **anchor = &call->arguments;
7300                 do {
7301                         call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7302                         argument->expression = parse_assignment_expression();
7303
7304                         *anchor = argument;
7305                         anchor  = &argument->next;
7306                 } while (next_if(','));
7307         }
7308         rem_anchor_token(',');
7309         rem_anchor_token(')');
7310         expect(')', end_error);
7311
7312         if (function_type == NULL)
7313                 return result;
7314
7315         /* check type and count of call arguments */
7316         function_parameter_t *parameter = function_type->parameters;
7317         call_argument_t      *argument  = call->arguments;
7318         if (!function_type->unspecified_parameters) {
7319                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7320                                 parameter = parameter->next, argument = argument->next) {
7321                         check_call_argument(parameter->type, argument, ++pos);
7322                 }
7323
7324                 if (parameter != NULL) {
7325                         errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7326                 } else if (argument != NULL && !function_type->variadic) {
7327                         errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7328                 }
7329         }
7330
7331         /* do default promotion for other arguments */
7332         for (; argument != NULL; argument = argument->next) {
7333                 type_t *argument_type = argument->expression->base.type;
7334                 if (!is_type_object(skip_typeref(argument_type))) {
7335                         errorf(&argument->expression->base.source_position,
7336                                "call argument '%E' must not be void", argument->expression);
7337                 }
7338
7339                 argument_type = get_default_promoted_type(argument_type);
7340
7341                 argument->expression
7342                         = create_implicit_cast(argument->expression, argument_type);
7343         }
7344
7345         check_format(call);
7346
7347         if (is_type_compound(skip_typeref(function_type->return_type))) {
7348                 source_position_t const *const pos = &expression->base.source_position;
7349                 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7350         }
7351
7352         if (expression->kind == EXPR_REFERENCE) {
7353                 reference_expression_t *reference = &expression->reference;
7354                 if (reference->entity->kind == ENTITY_FUNCTION &&
7355                     reference->entity->function.btk != BUILTIN_NONE)
7356                         handle_builtin_argument_restrictions(call);
7357         }
7358
7359 end_error:
7360         return result;
7361 }
7362
7363 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7364
7365 static bool same_compound_type(const type_t *type1, const type_t *type2)
7366 {
7367         return
7368                 is_type_compound(type1) &&
7369                 type1->kind == type2->kind &&
7370                 type1->compound.compound == type2->compound.compound;
7371 }
7372
7373 static expression_t const *get_reference_address(expression_t const *expr)
7374 {
7375         bool regular_take_address = true;
7376         for (;;) {
7377                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7378                         expr = expr->unary.value;
7379                 } else {
7380                         regular_take_address = false;
7381                 }
7382
7383                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7384                         break;
7385
7386                 expr = expr->unary.value;
7387         }
7388
7389         if (expr->kind != EXPR_REFERENCE)
7390                 return NULL;
7391
7392         /* special case for functions which are automatically converted to a
7393          * pointer to function without an extra TAKE_ADDRESS operation */
7394         if (!regular_take_address &&
7395                         expr->reference.entity->kind != ENTITY_FUNCTION) {
7396                 return NULL;
7397         }
7398
7399         return expr;
7400 }
7401
7402 static void warn_reference_address_as_bool(expression_t const* expr)
7403 {
7404         expr = get_reference_address(expr);
7405         if (expr != NULL) {
7406                 source_position_t const *const pos = &expr->base.source_position;
7407                 entity_t          const *const ent = expr->reference.entity;
7408                 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7409         }
7410 }
7411
7412 static void warn_assignment_in_condition(const expression_t *const expr)
7413 {
7414         if (expr->base.kind != EXPR_BINARY_ASSIGN)
7415                 return;
7416         if (expr->base.parenthesized)
7417                 return;
7418         source_position_t const *const pos = &expr->base.source_position;
7419         warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7420 }
7421
7422 static void semantic_condition(expression_t const *const expr,
7423                                char const *const context)
7424 {
7425         type_t *const type = skip_typeref(expr->base.type);
7426         if (is_type_scalar(type)) {
7427                 warn_reference_address_as_bool(expr);
7428                 warn_assignment_in_condition(expr);
7429         } else if (is_type_valid(type)) {
7430                 errorf(&expr->base.source_position,
7431                                 "%s must have scalar type", context);
7432         }
7433 }
7434
7435 /**
7436  * Parse a conditional expression, ie. 'expression ? ... : ...'.
7437  *
7438  * @param expression  the conditional expression
7439  */
7440 static expression_t *parse_conditional_expression(expression_t *expression)
7441 {
7442         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7443
7444         conditional_expression_t *conditional = &result->conditional;
7445         conditional->condition                = expression;
7446
7447         eat('?');
7448         add_anchor_token(':');
7449
7450         /* §6.5.15:2  The first operand shall have scalar type. */
7451         semantic_condition(expression, "condition of conditional operator");
7452
7453         expression_t *true_expression = expression;
7454         bool          gnu_cond = false;
7455         if (GNU_MODE && token.kind == ':') {
7456                 gnu_cond = true;
7457         } else {
7458                 true_expression = parse_expression();
7459         }
7460         rem_anchor_token(':');
7461         expect(':', end_error);
7462 end_error:;
7463         expression_t *false_expression =
7464                 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7465
7466         type_t *const orig_true_type  = true_expression->base.type;
7467         type_t *const orig_false_type = false_expression->base.type;
7468         type_t *const true_type       = skip_typeref(orig_true_type);
7469         type_t *const false_type      = skip_typeref(orig_false_type);
7470
7471         /* 6.5.15.3 */
7472         source_position_t const *const pos = &conditional->base.source_position;
7473         type_t                        *result_type;
7474         if (is_type_void(true_type) || is_type_void(false_type)) {
7475                 /* ISO/IEC 14882:1998(E) §5.16:2 */
7476                 if (true_expression->kind == EXPR_UNARY_THROW) {
7477                         result_type = false_type;
7478                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7479                         result_type = true_type;
7480                 } else {
7481                         if (!is_type_void(true_type) || !is_type_void(false_type)) {
7482                                 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7483                         }
7484                         result_type = type_void;
7485                 }
7486         } else if (is_type_arithmetic(true_type)
7487                    && is_type_arithmetic(false_type)) {
7488                 result_type = semantic_arithmetic(true_type, false_type);
7489         } else if (same_compound_type(true_type, false_type)) {
7490                 /* just take 1 of the 2 types */
7491                 result_type = true_type;
7492         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7493                 type_t *pointer_type;
7494                 type_t *other_type;
7495                 expression_t *other_expression;
7496                 if (is_type_pointer(true_type) &&
7497                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7498                         pointer_type     = true_type;
7499                         other_type       = false_type;
7500                         other_expression = false_expression;
7501                 } else {
7502                         pointer_type     = false_type;
7503                         other_type       = true_type;
7504                         other_expression = true_expression;
7505                 }
7506
7507                 if (is_null_pointer_constant(other_expression)) {
7508                         result_type = pointer_type;
7509                 } else if (is_type_pointer(other_type)) {
7510                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7511                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
7512
7513                         type_t *to;
7514                         if (is_type_void(to1) || is_type_void(to2)) {
7515                                 to = type_void;
7516                         } else if (types_compatible(get_unqualified_type(to1),
7517                                                     get_unqualified_type(to2))) {
7518                                 to = to1;
7519                         } else {
7520                                 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7521                                 to = type_void;
7522                         }
7523
7524                         type_t *const type =
7525                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7526                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7527                 } else if (is_type_integer(other_type)) {
7528                         warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7529                         result_type = pointer_type;
7530                 } else {
7531                         goto types_incompatible;
7532                 }
7533         } else {
7534 types_incompatible:
7535                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7536                         type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7537                 }
7538                 result_type = type_error_type;
7539         }
7540
7541         conditional->true_expression
7542                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7543         conditional->false_expression
7544                 = create_implicit_cast(false_expression, result_type);
7545         conditional->base.type = result_type;
7546         return result;
7547 }
7548
7549 /**
7550  * Parse an extension expression.
7551  */
7552 static expression_t *parse_extension(void)
7553 {
7554         PUSH_EXTENSION();
7555         expression_t *expression = parse_subexpression(PREC_UNARY);
7556         POP_EXTENSION();
7557         return expression;
7558 }
7559
7560 /**
7561  * Parse a __builtin_classify_type() expression.
7562  */
7563 static expression_t *parse_builtin_classify_type(void)
7564 {
7565         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7566         result->base.type    = type_int;
7567
7568         eat(T___builtin_classify_type);
7569
7570         expect('(', end_error);
7571         add_anchor_token(')');
7572         expression_t *expression = parse_expression();
7573         rem_anchor_token(')');
7574         expect(')', end_error);
7575         result->classify_type.type_expression = expression;
7576
7577         return result;
7578 end_error:
7579         return create_error_expression();
7580 }
7581
7582 /**
7583  * Parse a delete expression
7584  * ISO/IEC 14882:1998(E) §5.3.5
7585  */
7586 static expression_t *parse_delete(void)
7587 {
7588         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7589         result->base.type          = type_void;
7590
7591         eat(T_delete);
7592
7593         if (next_if('[')) {
7594                 result->kind = EXPR_UNARY_DELETE_ARRAY;
7595                 expect(']', end_error);
7596 end_error:;
7597         }
7598
7599         expression_t *const value = parse_subexpression(PREC_CAST);
7600         result->unary.value = value;
7601
7602         type_t *const type = skip_typeref(value->base.type);
7603         if (!is_type_pointer(type)) {
7604                 if (is_type_valid(type)) {
7605                         errorf(&value->base.source_position,
7606                                         "operand of delete must have pointer type");
7607                 }
7608         } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7609                 source_position_t const *const pos = &value->base.source_position;
7610                 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7611         }
7612
7613         return result;
7614 }
7615
7616 /**
7617  * Parse a throw expression
7618  * ISO/IEC 14882:1998(E) §15:1
7619  */
7620 static expression_t *parse_throw(void)
7621 {
7622         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7623         result->base.type          = type_void;
7624
7625         eat(T_throw);
7626
7627         expression_t *value = NULL;
7628         switch (token.kind) {
7629                 EXPRESSION_START {
7630                         value = parse_assignment_expression();
7631                         /* ISO/IEC 14882:1998(E) §15.1:3 */
7632                         type_t *const orig_type = value->base.type;
7633                         type_t *const type      = skip_typeref(orig_type);
7634                         if (is_type_incomplete(type)) {
7635                                 errorf(&value->base.source_position,
7636                                                 "cannot throw object of incomplete type '%T'", orig_type);
7637                         } else if (is_type_pointer(type)) {
7638                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
7639                                 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7640                                         errorf(&value->base.source_position,
7641                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
7642                                 }
7643                         }
7644                 }
7645
7646                 default:
7647                         break;
7648         }
7649         result->unary.value = value;
7650
7651         return result;
7652 }
7653
7654 static bool check_pointer_arithmetic(const source_position_t *source_position,
7655                                      type_t *pointer_type,
7656                                      type_t *orig_pointer_type)
7657 {
7658         type_t *points_to = pointer_type->pointer.points_to;
7659         points_to = skip_typeref(points_to);
7660
7661         if (is_type_incomplete(points_to)) {
7662                 if (!GNU_MODE || !is_type_void(points_to)) {
7663                         errorf(source_position,
7664                                "arithmetic with pointer to incomplete type '%T' not allowed",
7665                                orig_pointer_type);
7666                         return false;
7667                 } else {
7668                         warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7669                 }
7670         } else if (is_type_function(points_to)) {
7671                 if (!GNU_MODE) {
7672                         errorf(source_position,
7673                                "arithmetic with pointer to function type '%T' not allowed",
7674                                orig_pointer_type);
7675                         return false;
7676                 } else {
7677                         warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7678                 }
7679         }
7680         return true;
7681 }
7682
7683 static bool is_lvalue(const expression_t *expression)
7684 {
7685         /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7686         switch (expression->kind) {
7687         case EXPR_ARRAY_ACCESS:
7688         case EXPR_COMPOUND_LITERAL:
7689         case EXPR_REFERENCE:
7690         case EXPR_SELECT:
7691         case EXPR_UNARY_DEREFERENCE:
7692                 return true;
7693
7694         default: {
7695                 type_t *type = skip_typeref(expression->base.type);
7696                 return
7697                         /* ISO/IEC 14882:1998(E) §3.10:3 */
7698                         is_type_reference(type) ||
7699                         /* Claim it is an lvalue, if the type is invalid.  There was a parse
7700                          * error before, which maybe prevented properly recognizing it as
7701                          * lvalue. */
7702                         !is_type_valid(type);
7703         }
7704         }
7705 }
7706
7707 static void semantic_incdec(unary_expression_t *expression)
7708 {
7709         type_t *const orig_type = expression->value->base.type;
7710         type_t *const type      = skip_typeref(orig_type);
7711         if (is_type_pointer(type)) {
7712                 if (!check_pointer_arithmetic(&expression->base.source_position,
7713                                               type, orig_type)) {
7714                         return;
7715                 }
7716         } else if (!is_type_real(type) && is_type_valid(type)) {
7717                 /* TODO: improve error message */
7718                 errorf(&expression->base.source_position,
7719                        "operation needs an arithmetic or pointer type");
7720                 return;
7721         }
7722         if (!is_lvalue(expression->value)) {
7723                 /* TODO: improve error message */
7724                 errorf(&expression->base.source_position, "lvalue required as operand");
7725         }
7726         expression->base.type = orig_type;
7727 }
7728
7729 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7730 {
7731         type_t *const res_type = promote_integer(type);
7732         expr->base.type = res_type;
7733         expr->value     = create_implicit_cast(expr->value, res_type);
7734 }
7735
7736 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7737 {
7738         type_t *const orig_type = expression->value->base.type;
7739         type_t *const type      = skip_typeref(orig_type);
7740         if (!is_type_arithmetic(type)) {
7741                 if (is_type_valid(type)) {
7742                         /* TODO: improve error message */
7743                         errorf(&expression->base.source_position,
7744                                 "operation needs an arithmetic type");
7745                 }
7746                 return;
7747         } else if (is_type_integer(type)) {
7748                 promote_unary_int_expr(expression, type);
7749         } else {
7750                 expression->base.type = orig_type;
7751         }
7752 }
7753
7754 static void semantic_unexpr_plus(unary_expression_t *expression)
7755 {
7756         semantic_unexpr_arithmetic(expression);
7757         source_position_t const *const pos = &expression->base.source_position;
7758         warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7759 }
7760
7761 static void semantic_not(unary_expression_t *expression)
7762 {
7763         /* §6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
7764         semantic_condition(expression->value, "operand of !");
7765         expression->base.type = c_mode & _CXX ? type_bool : type_int;
7766 }
7767
7768 static void semantic_unexpr_integer(unary_expression_t *expression)
7769 {
7770         type_t *const orig_type = expression->value->base.type;
7771         type_t *const type      = skip_typeref(orig_type);
7772         if (!is_type_integer(type)) {
7773                 if (is_type_valid(type)) {
7774                         errorf(&expression->base.source_position,
7775                                "operand of ~ must be of integer type");
7776                 }
7777                 return;
7778         }
7779
7780         promote_unary_int_expr(expression, type);
7781 }
7782
7783 static void semantic_dereference(unary_expression_t *expression)
7784 {
7785         type_t *const orig_type = expression->value->base.type;
7786         type_t *const type      = skip_typeref(orig_type);
7787         if (!is_type_pointer(type)) {
7788                 if (is_type_valid(type)) {
7789                         errorf(&expression->base.source_position,
7790                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7791                 }
7792                 return;
7793         }
7794
7795         type_t *result_type   = type->pointer.points_to;
7796         result_type           = automatic_type_conversion(result_type);
7797         expression->base.type = result_type;
7798 }
7799
7800 /**
7801  * Record that an address is taken (expression represents an lvalue).
7802  *
7803  * @param expression       the expression
7804  * @param may_be_register  if true, the expression might be an register
7805  */
7806 static void set_address_taken(expression_t *expression, bool may_be_register)
7807 {
7808         if (expression->kind != EXPR_REFERENCE)
7809                 return;
7810
7811         entity_t *const entity = expression->reference.entity;
7812
7813         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7814                 return;
7815
7816         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7817                         && !may_be_register) {
7818                 source_position_t const *const pos = &expression->base.source_position;
7819                 errorf(pos, "address of register '%N' requested", entity);
7820         }
7821
7822         if (entity->kind == ENTITY_VARIABLE) {
7823                 entity->variable.address_taken = true;
7824         } else {
7825                 assert(entity->kind == ENTITY_PARAMETER);
7826                 entity->parameter.address_taken = true;
7827         }
7828 }
7829
7830 /**
7831  * Check the semantic of the address taken expression.
7832  */
7833 static void semantic_take_addr(unary_expression_t *expression)
7834 {
7835         expression_t *value = expression->value;
7836         value->base.type    = revert_automatic_type_conversion(value);
7837
7838         type_t *orig_type = value->base.type;
7839         type_t *type      = skip_typeref(orig_type);
7840         if (!is_type_valid(type))
7841                 return;
7842
7843         /* §6.5.3.2 */
7844         if (!is_lvalue(value)) {
7845                 errorf(&expression->base.source_position, "'&' requires an lvalue");
7846         }
7847         if (is_bitfield(value)) {
7848                 errorf(&expression->base.source_position,
7849                        "'&' not allowed on bitfield");
7850         }
7851
7852         set_address_taken(value, false);
7853
7854         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7855 }
7856
7857 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7858 static expression_t *parse_##unexpression_type(void)                         \
7859 {                                                                            \
7860         expression_t *unary_expression                                           \
7861                 = allocate_expression_zero(unexpression_type);                       \
7862         eat(token_kind);                                                         \
7863         unary_expression->unary.value = parse_subexpression(PREC_UNARY);         \
7864                                                                                  \
7865         sfunc(&unary_expression->unary);                                         \
7866                                                                                  \
7867         return unary_expression;                                                 \
7868 }
7869
7870 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7871                                semantic_unexpr_arithmetic)
7872 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7873                                semantic_unexpr_plus)
7874 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7875                                semantic_not)
7876 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7877                                semantic_dereference)
7878 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7879                                semantic_take_addr)
7880 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7881                                semantic_unexpr_integer)
7882 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
7883                                semantic_incdec)
7884 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7885                                semantic_incdec)
7886
7887 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7888                                                sfunc)                         \
7889 static expression_t *parse_##unexpression_type(expression_t *left)            \
7890 {                                                                             \
7891         expression_t *unary_expression                                            \
7892                 = allocate_expression_zero(unexpression_type);                        \
7893         eat(token_kind);                                                          \
7894         unary_expression->unary.value = left;                                     \
7895                                                                                   \
7896         sfunc(&unary_expression->unary);                                          \
7897                                                                               \
7898         return unary_expression;                                                  \
7899 }
7900
7901 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7902                                        EXPR_UNARY_POSTFIX_INCREMENT,
7903                                        semantic_incdec)
7904 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7905                                        EXPR_UNARY_POSTFIX_DECREMENT,
7906                                        semantic_incdec)
7907
7908 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7909 {
7910         /* TODO: handle complex + imaginary types */
7911
7912         type_left  = get_unqualified_type(type_left);
7913         type_right = get_unqualified_type(type_right);
7914
7915         /* §6.3.1.8 Usual arithmetic conversions */
7916         if (type_left == type_long_double || type_right == type_long_double) {
7917                 return type_long_double;
7918         } else if (type_left == type_double || type_right == type_double) {
7919                 return type_double;
7920         } else if (type_left == type_float || type_right == type_float) {
7921                 return type_float;
7922         }
7923
7924         type_left  = promote_integer(type_left);
7925         type_right = promote_integer(type_right);
7926
7927         if (type_left == type_right)
7928                 return type_left;
7929
7930         bool     const signed_left  = is_type_signed(type_left);
7931         bool     const signed_right = is_type_signed(type_right);
7932         unsigned const rank_left    = get_akind_rank(get_akind(type_left));
7933         unsigned const rank_right   = get_akind_rank(get_akind(type_right));
7934
7935         if (signed_left == signed_right)
7936                 return rank_left >= rank_right ? type_left : type_right;
7937
7938         unsigned           s_rank;
7939         unsigned           u_rank;
7940         atomic_type_kind_t s_akind;
7941         atomic_type_kind_t u_akind;
7942         type_t *s_type;
7943         type_t *u_type;
7944         if (signed_left) {
7945                 s_type = type_left;
7946                 u_type = type_right;
7947         } else {
7948                 s_type = type_right;
7949                 u_type = type_left;
7950         }
7951         s_akind = get_akind(s_type);
7952         u_akind = get_akind(u_type);
7953         s_rank  = get_akind_rank(s_akind);
7954         u_rank  = get_akind_rank(u_akind);
7955
7956         if (u_rank >= s_rank)
7957                 return u_type;
7958
7959         if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7960                 return s_type;
7961
7962         switch (s_akind) {
7963         case ATOMIC_TYPE_INT:      return type_unsigned_int;
7964         case ATOMIC_TYPE_LONG:     return type_unsigned_long;
7965         case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7966
7967         default: panic("invalid atomic type");
7968         }
7969 }
7970
7971 /**
7972  * Check the semantic restrictions for a binary expression.
7973  */
7974 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7975 {
7976         expression_t *const left            = expression->left;
7977         expression_t *const right           = expression->right;
7978         type_t       *const orig_type_left  = left->base.type;
7979         type_t       *const orig_type_right = right->base.type;
7980         type_t       *const type_left       = skip_typeref(orig_type_left);
7981         type_t       *const type_right      = skip_typeref(orig_type_right);
7982
7983         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7984                 /* TODO: improve error message */
7985                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7986                         errorf(&expression->base.source_position,
7987                                "operation needs arithmetic types");
7988                 }
7989                 return;
7990         }
7991
7992         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7993         expression->left      = create_implicit_cast(left, arithmetic_type);
7994         expression->right     = create_implicit_cast(right, arithmetic_type);
7995         expression->base.type = arithmetic_type;
7996 }
7997
7998 static void semantic_binexpr_integer(binary_expression_t *const expression)
7999 {
8000         expression_t *const left            = expression->left;
8001         expression_t *const right           = expression->right;
8002         type_t       *const orig_type_left  = left->base.type;
8003         type_t       *const orig_type_right = right->base.type;
8004         type_t       *const type_left       = skip_typeref(orig_type_left);
8005         type_t       *const type_right      = skip_typeref(orig_type_right);
8006
8007         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8008                 /* TODO: improve error message */
8009                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8010                         errorf(&expression->base.source_position,
8011                                "operation needs integer types");
8012                 }
8013                 return;
8014         }
8015
8016         type_t *const result_type = semantic_arithmetic(type_left, type_right);
8017         expression->left      = create_implicit_cast(left, result_type);
8018         expression->right     = create_implicit_cast(right, result_type);
8019         expression->base.type = result_type;
8020 }
8021
8022 static void warn_div_by_zero(binary_expression_t const *const expression)
8023 {
8024         if (!is_type_integer(expression->base.type))
8025                 return;
8026
8027         expression_t const *const right = expression->right;
8028         /* The type of the right operand can be different for /= */
8029         if (is_type_integer(right->base.type)                    &&
8030             is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8031             !fold_constant_to_bool(right)) {
8032                 source_position_t const *const pos = &expression->base.source_position;
8033                 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8034         }
8035 }
8036
8037 /**
8038  * Check the semantic restrictions for a div/mod expression.
8039  */
8040 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8041 {
8042         semantic_binexpr_arithmetic(expression);
8043         warn_div_by_zero(expression);
8044 }
8045
8046 static void warn_addsub_in_shift(const expression_t *const expr)
8047 {
8048         if (expr->base.parenthesized)
8049                 return;
8050
8051         char op;
8052         switch (expr->kind) {
8053                 case EXPR_BINARY_ADD: op = '+'; break;
8054                 case EXPR_BINARY_SUB: op = '-'; break;
8055                 default:              return;
8056         }
8057
8058         source_position_t const *const pos = &expr->base.source_position;
8059         warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8060 }
8061
8062 static bool semantic_shift(binary_expression_t *expression)
8063 {
8064         expression_t *const left            = expression->left;
8065         expression_t *const right           = expression->right;
8066         type_t       *const orig_type_left  = left->base.type;
8067         type_t       *const orig_type_right = right->base.type;
8068         type_t       *      type_left       = skip_typeref(orig_type_left);
8069         type_t       *      type_right      = skip_typeref(orig_type_right);
8070
8071         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8072                 /* TODO: improve error message */
8073                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8074                         errorf(&expression->base.source_position,
8075                                "operands of shift operation must have integer types");
8076                 }
8077                 return false;
8078         }
8079
8080         type_left = promote_integer(type_left);
8081
8082         if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8083                 source_position_t const *const pos   = &right->base.source_position;
8084                 long                     const count = fold_constant_to_int(right);
8085                 if (count < 0) {
8086                         warningf(WARN_OTHER, pos, "shift count must be non-negative");
8087                 } else if ((unsigned long)count >=
8088                                 get_atomic_type_size(type_left->atomic.akind) * 8) {
8089                         warningf(WARN_OTHER, pos, "shift count must be less than type width");
8090                 }
8091         }
8092
8093         type_right        = promote_integer(type_right);
8094         expression->right = create_implicit_cast(right, type_right);
8095
8096         return true;
8097 }
8098
8099 static void semantic_shift_op(binary_expression_t *expression)
8100 {
8101         expression_t *const left  = expression->left;
8102         expression_t *const right = expression->right;
8103
8104         if (!semantic_shift(expression))
8105                 return;
8106
8107         warn_addsub_in_shift(left);
8108         warn_addsub_in_shift(right);
8109
8110         type_t *const orig_type_left = left->base.type;
8111         type_t *      type_left      = skip_typeref(orig_type_left);
8112
8113         type_left             = promote_integer(type_left);
8114         expression->left      = create_implicit_cast(left, type_left);
8115         expression->base.type = type_left;
8116 }
8117
8118 static void semantic_add(binary_expression_t *expression)
8119 {
8120         expression_t *const left            = expression->left;
8121         expression_t *const right           = expression->right;
8122         type_t       *const orig_type_left  = left->base.type;
8123         type_t       *const orig_type_right = right->base.type;
8124         type_t       *const type_left       = skip_typeref(orig_type_left);
8125         type_t       *const type_right      = skip_typeref(orig_type_right);
8126
8127         /* §6.5.6 */
8128         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8129                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8130                 expression->left  = create_implicit_cast(left, arithmetic_type);
8131                 expression->right = create_implicit_cast(right, arithmetic_type);
8132                 expression->base.type = arithmetic_type;
8133         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8134                 check_pointer_arithmetic(&expression->base.source_position,
8135                                          type_left, orig_type_left);
8136                 expression->base.type = type_left;
8137         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8138                 check_pointer_arithmetic(&expression->base.source_position,
8139                                          type_right, orig_type_right);
8140                 expression->base.type = type_right;
8141         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8142                 errorf(&expression->base.source_position,
8143                        "invalid operands to binary + ('%T', '%T')",
8144                        orig_type_left, orig_type_right);
8145         }
8146 }
8147
8148 static void semantic_sub(binary_expression_t *expression)
8149 {
8150         expression_t            *const left            = expression->left;
8151         expression_t            *const right           = expression->right;
8152         type_t                  *const orig_type_left  = left->base.type;
8153         type_t                  *const orig_type_right = right->base.type;
8154         type_t                  *const type_left       = skip_typeref(orig_type_left);
8155         type_t                  *const type_right      = skip_typeref(orig_type_right);
8156         source_position_t const *const pos             = &expression->base.source_position;
8157
8158         /* §5.6.5 */
8159         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8160                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8161                 expression->left        = create_implicit_cast(left, arithmetic_type);
8162                 expression->right       = create_implicit_cast(right, arithmetic_type);
8163                 expression->base.type =  arithmetic_type;
8164         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8165                 check_pointer_arithmetic(&expression->base.source_position,
8166                                          type_left, orig_type_left);
8167                 expression->base.type = type_left;
8168         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8169                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8170                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8171                 if (!types_compatible(unqual_left, unqual_right)) {
8172                         errorf(pos,
8173                                "subtracting pointers to incompatible types '%T' and '%T'",
8174                                orig_type_left, orig_type_right);
8175                 } else if (!is_type_object(unqual_left)) {
8176                         if (!is_type_void(unqual_left)) {
8177                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8178                                        orig_type_left);
8179                         } else {
8180                                 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8181                         }
8182                 }
8183                 expression->base.type = type_ptrdiff_t;
8184         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8185                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8186                        orig_type_left, orig_type_right);
8187         }
8188 }
8189
8190 static void warn_string_literal_address(expression_t const* expr)
8191 {
8192         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8193                 expr = expr->unary.value;
8194                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8195                         return;
8196                 expr = expr->unary.value;
8197         }
8198
8199         if (expr->kind == EXPR_STRING_LITERAL
8200                         || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8201                 source_position_t const *const pos = &expr->base.source_position;
8202                 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8203         }
8204 }
8205
8206 static bool maybe_negative(expression_t const *const expr)
8207 {
8208         switch (is_constant_expression(expr)) {
8209                 case EXPR_CLASS_ERROR:    return false;
8210                 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8211                 default:                  return true;
8212         }
8213 }
8214
8215 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8216 {
8217         warn_string_literal_address(expr);
8218
8219         expression_t const* const ref = get_reference_address(expr);
8220         if (ref != NULL && is_null_pointer_constant(other)) {
8221                 entity_t const *const ent = ref->reference.entity;
8222                 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8223         }
8224
8225         if (!expr->base.parenthesized) {
8226                 switch (expr->base.kind) {
8227                         case EXPR_BINARY_LESS:
8228                         case EXPR_BINARY_GREATER:
8229                         case EXPR_BINARY_LESSEQUAL:
8230                         case EXPR_BINARY_GREATEREQUAL:
8231                         case EXPR_BINARY_NOTEQUAL:
8232                         case EXPR_BINARY_EQUAL:
8233                                 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8234                                 break;
8235                         default:
8236                                 break;
8237                 }
8238         }
8239 }
8240
8241 /**
8242  * Check the semantics of comparison expressions.
8243  *
8244  * @param expression   The expression to check.
8245  */
8246 static void semantic_comparison(binary_expression_t *expression)
8247 {
8248         source_position_t const *const pos   = &expression->base.source_position;
8249         expression_t            *const left  = expression->left;
8250         expression_t            *const right = expression->right;
8251
8252         warn_comparison(pos, left, right);
8253         warn_comparison(pos, right, left);
8254
8255         type_t *orig_type_left  = left->base.type;
8256         type_t *orig_type_right = right->base.type;
8257         type_t *type_left       = skip_typeref(orig_type_left);
8258         type_t *type_right      = skip_typeref(orig_type_right);
8259
8260         /* TODO non-arithmetic types */
8261         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8262                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8263
8264                 /* test for signed vs unsigned compares */
8265                 if (is_type_integer(arithmetic_type)) {
8266                         bool const signed_left  = is_type_signed(type_left);
8267                         bool const signed_right = is_type_signed(type_right);
8268                         if (signed_left != signed_right) {
8269                                 /* FIXME long long needs better const folding magic */
8270                                 /* TODO check whether constant value can be represented by other type */
8271                                 if ((signed_left  && maybe_negative(left)) ||
8272                                                 (signed_right && maybe_negative(right))) {
8273                                         warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8274                                 }
8275                         }
8276                 }
8277
8278                 expression->left        = create_implicit_cast(left, arithmetic_type);
8279                 expression->right       = create_implicit_cast(right, arithmetic_type);
8280                 expression->base.type   = arithmetic_type;
8281                 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8282                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8283                     is_type_float(arithmetic_type)) {
8284                         warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8285                 }
8286         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8287                 /* TODO check compatibility */
8288         } else if (is_type_pointer(type_left)) {
8289                 expression->right = create_implicit_cast(right, type_left);
8290         } else if (is_type_pointer(type_right)) {
8291                 expression->left = create_implicit_cast(left, type_right);
8292         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8293                 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8294         }
8295         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8296 }
8297
8298 /**
8299  * Checks if a compound type has constant fields.
8300  */
8301 static bool has_const_fields(const compound_type_t *type)
8302 {
8303         compound_t *compound = type->compound;
8304         entity_t   *entry    = compound->members.entities;
8305
8306         for (; entry != NULL; entry = entry->base.next) {
8307                 if (!is_declaration(entry))
8308                         continue;
8309
8310                 const type_t *decl_type = skip_typeref(entry->declaration.type);
8311                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8312                         return true;
8313         }
8314
8315         return false;
8316 }
8317
8318 static bool is_valid_assignment_lhs(expression_t const* const left)
8319 {
8320         type_t *const orig_type_left = revert_automatic_type_conversion(left);
8321         type_t *const type_left      = skip_typeref(orig_type_left);
8322
8323         if (!is_lvalue(left)) {
8324                 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8325                        left);
8326                 return false;
8327         }
8328
8329         if (left->kind == EXPR_REFERENCE
8330                         && left->reference.entity->kind == ENTITY_FUNCTION) {
8331                 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8332                 return false;
8333         }
8334
8335         if (is_type_array(type_left)) {
8336                 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8337                 return false;
8338         }
8339         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8340                 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8341                        orig_type_left);
8342                 return false;
8343         }
8344         if (is_type_incomplete(type_left)) {
8345                 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8346                        left, orig_type_left);
8347                 return false;
8348         }
8349         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8350                 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8351                        left, orig_type_left);
8352                 return false;
8353         }
8354
8355         return true;
8356 }
8357
8358 static void semantic_arithmetic_assign(binary_expression_t *expression)
8359 {
8360         expression_t *left            = expression->left;
8361         expression_t *right           = expression->right;
8362         type_t       *orig_type_left  = left->base.type;
8363         type_t       *orig_type_right = right->base.type;
8364
8365         if (!is_valid_assignment_lhs(left))
8366                 return;
8367
8368         type_t *type_left  = skip_typeref(orig_type_left);
8369         type_t *type_right = skip_typeref(orig_type_right);
8370
8371         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8372                 /* TODO: improve error message */
8373                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8374                         errorf(&expression->base.source_position,
8375                                "operation needs arithmetic types");
8376                 }
8377                 return;
8378         }
8379
8380         /* combined instructions are tricky. We can't create an implicit cast on
8381          * the left side, because we need the uncasted form for the store.
8382          * The ast2firm pass has to know that left_type must be right_type
8383          * for the arithmetic operation and create a cast by itself */
8384         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8385         expression->right       = create_implicit_cast(right, arithmetic_type);
8386         expression->base.type   = type_left;
8387 }
8388
8389 static void semantic_divmod_assign(binary_expression_t *expression)
8390 {
8391         semantic_arithmetic_assign(expression);
8392         warn_div_by_zero(expression);
8393 }
8394
8395 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8396 {
8397         expression_t *const left            = expression->left;
8398         expression_t *const right           = expression->right;
8399         type_t       *const orig_type_left  = left->base.type;
8400         type_t       *const orig_type_right = right->base.type;
8401         type_t       *const type_left       = skip_typeref(orig_type_left);
8402         type_t       *const type_right      = skip_typeref(orig_type_right);
8403
8404         if (!is_valid_assignment_lhs(left))
8405                 return;
8406
8407         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8408                 /* combined instructions are tricky. We can't create an implicit cast on
8409                  * the left side, because we need the uncasted form for the store.
8410                  * The ast2firm pass has to know that left_type must be right_type
8411                  * for the arithmetic operation and create a cast by itself */
8412                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8413                 expression->right     = create_implicit_cast(right, arithmetic_type);
8414                 expression->base.type = type_left;
8415         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8416                 check_pointer_arithmetic(&expression->base.source_position,
8417                                          type_left, orig_type_left);
8418                 expression->base.type = type_left;
8419         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8420                 errorf(&expression->base.source_position,
8421                        "incompatible types '%T' and '%T' in assignment",
8422                        orig_type_left, orig_type_right);
8423         }
8424 }
8425
8426 static void semantic_integer_assign(binary_expression_t *expression)
8427 {
8428         expression_t *left            = expression->left;
8429         expression_t *right           = expression->right;
8430         type_t       *orig_type_left  = left->base.type;
8431         type_t       *orig_type_right = right->base.type;
8432
8433         if (!is_valid_assignment_lhs(left))
8434                 return;
8435
8436         type_t *type_left  = skip_typeref(orig_type_left);
8437         type_t *type_right = skip_typeref(orig_type_right);
8438
8439         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8440                 /* TODO: improve error message */
8441                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8442                         errorf(&expression->base.source_position,
8443                                "operation needs integer types");
8444                 }
8445                 return;
8446         }
8447
8448         /* combined instructions are tricky. We can't create an implicit cast on
8449          * the left side, because we need the uncasted form for the store.
8450          * The ast2firm pass has to know that left_type must be right_type
8451          * for the arithmetic operation and create a cast by itself */
8452         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8453         expression->right       = create_implicit_cast(right, arithmetic_type);
8454         expression->base.type   = type_left;
8455 }
8456
8457 static void semantic_shift_assign(binary_expression_t *expression)
8458 {
8459         expression_t *left           = expression->left;
8460
8461         if (!is_valid_assignment_lhs(left))
8462                 return;
8463
8464         if (!semantic_shift(expression))
8465                 return;
8466
8467         expression->base.type = skip_typeref(left->base.type);
8468 }
8469
8470 static void warn_logical_and_within_or(const expression_t *const expr)
8471 {
8472         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8473                 return;
8474         if (expr->base.parenthesized)
8475                 return;
8476         source_position_t const *const pos = &expr->base.source_position;
8477         warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8478 }
8479
8480 /**
8481  * Check the semantic restrictions of a logical expression.
8482  */
8483 static void semantic_logical_op(binary_expression_t *expression)
8484 {
8485         /* §6.5.13:2  Each of the operands shall have scalar type.
8486          * §6.5.14:2  Each of the operands shall have scalar type. */
8487         semantic_condition(expression->left,   "left operand of logical operator");
8488         semantic_condition(expression->right, "right operand of logical operator");
8489         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8490                 warn_logical_and_within_or(expression->left);
8491                 warn_logical_and_within_or(expression->right);
8492         }
8493         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8494 }
8495
8496 /**
8497  * Check the semantic restrictions of a binary assign expression.
8498  */
8499 static void semantic_binexpr_assign(binary_expression_t *expression)
8500 {
8501         expression_t *left           = expression->left;
8502         type_t       *orig_type_left = left->base.type;
8503
8504         if (!is_valid_assignment_lhs(left))
8505                 return;
8506
8507         assign_error_t error = semantic_assign(orig_type_left, expression->right);
8508         report_assign_error(error, orig_type_left, expression->right,
8509                         "assignment", &left->base.source_position);
8510         expression->right = create_implicit_cast(expression->right, orig_type_left);
8511         expression->base.type = orig_type_left;
8512 }
8513
8514 /**
8515  * Determine if the outermost operation (or parts thereof) of the given
8516  * expression has no effect in order to generate a warning about this fact.
8517  * Therefore in some cases this only examines some of the operands of the
8518  * expression (see comments in the function and examples below).
8519  * Examples:
8520  *   f() + 23;    // warning, because + has no effect
8521  *   x || f();    // no warning, because x controls execution of f()
8522  *   x ? y : f(); // warning, because y has no effect
8523  *   (void)x;     // no warning to be able to suppress the warning
8524  * This function can NOT be used for an "expression has definitely no effect"-
8525  * analysis. */
8526 static bool expression_has_effect(const expression_t *const expr)
8527 {
8528         switch (expr->kind) {
8529                 case EXPR_ERROR:                      return true; /* do NOT warn */
8530                 case EXPR_REFERENCE:                  return false;
8531                 case EXPR_ENUM_CONSTANT:              return false;
8532                 case EXPR_LABEL_ADDRESS:              return false;
8533
8534                 /* suppress the warning for microsoft __noop operations */
8535                 case EXPR_LITERAL_MS_NOOP:            return true;
8536                 case EXPR_LITERAL_BOOLEAN:
8537                 case EXPR_LITERAL_CHARACTER:
8538                 case EXPR_LITERAL_WIDE_CHARACTER:
8539                 case EXPR_LITERAL_INTEGER:
8540                 case EXPR_LITERAL_INTEGER_OCTAL:
8541                 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8542                 case EXPR_LITERAL_FLOATINGPOINT:
8543                 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8544                 case EXPR_STRING_LITERAL:             return false;
8545                 case EXPR_WIDE_STRING_LITERAL:        return false;
8546
8547                 case EXPR_CALL: {
8548                         const call_expression_t *const call = &expr->call;
8549                         if (call->function->kind != EXPR_REFERENCE)
8550                                 return true;
8551
8552                         switch (call->function->reference.entity->function.btk) {
8553                                 /* FIXME: which builtins have no effect? */
8554                                 default:                      return true;
8555                         }
8556                 }
8557
8558                 /* Generate the warning if either the left or right hand side of a
8559                  * conditional expression has no effect */
8560                 case EXPR_CONDITIONAL: {
8561                         conditional_expression_t const *const cond = &expr->conditional;
8562                         expression_t             const *const t    = cond->true_expression;
8563                         return
8564                                 (t == NULL || expression_has_effect(t)) &&
8565                                 expression_has_effect(cond->false_expression);
8566                 }
8567
8568                 case EXPR_SELECT:                     return false;
8569                 case EXPR_ARRAY_ACCESS:               return false;
8570                 case EXPR_SIZEOF:                     return false;
8571                 case EXPR_CLASSIFY_TYPE:              return false;
8572                 case EXPR_ALIGNOF:                    return false;
8573
8574                 case EXPR_FUNCNAME:                   return false;
8575                 case EXPR_BUILTIN_CONSTANT_P:         return false;
8576                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8577                 case EXPR_OFFSETOF:                   return false;
8578                 case EXPR_VA_START:                   return true;
8579                 case EXPR_VA_ARG:                     return true;
8580                 case EXPR_VA_COPY:                    return true;
8581                 case EXPR_STATEMENT:                  return true; // TODO
8582                 case EXPR_COMPOUND_LITERAL:           return false;
8583
8584                 case EXPR_UNARY_NEGATE:               return false;
8585                 case EXPR_UNARY_PLUS:                 return false;
8586                 case EXPR_UNARY_BITWISE_NEGATE:       return false;
8587                 case EXPR_UNARY_NOT:                  return false;
8588                 case EXPR_UNARY_DEREFERENCE:          return false;
8589                 case EXPR_UNARY_TAKE_ADDRESS:         return false;
8590                 case EXPR_UNARY_POSTFIX_INCREMENT:    return true;
8591                 case EXPR_UNARY_POSTFIX_DECREMENT:    return true;
8592                 case EXPR_UNARY_PREFIX_INCREMENT:     return true;
8593                 case EXPR_UNARY_PREFIX_DECREMENT:     return true;
8594
8595                 /* Treat void casts as if they have an effect in order to being able to
8596                  * suppress the warning */
8597                 case EXPR_UNARY_CAST: {
8598                         type_t *const type = skip_typeref(expr->base.type);
8599                         return is_type_void(type);
8600                 }
8601
8602                 case EXPR_UNARY_ASSUME:               return true;
8603                 case EXPR_UNARY_DELETE:               return true;
8604                 case EXPR_UNARY_DELETE_ARRAY:         return true;
8605                 case EXPR_UNARY_THROW:                return true;
8606
8607                 case EXPR_BINARY_ADD:                 return false;
8608                 case EXPR_BINARY_SUB:                 return false;
8609                 case EXPR_BINARY_MUL:                 return false;
8610                 case EXPR_BINARY_DIV:                 return false;
8611                 case EXPR_BINARY_MOD:                 return false;
8612                 case EXPR_BINARY_EQUAL:               return false;
8613                 case EXPR_BINARY_NOTEQUAL:            return false;
8614                 case EXPR_BINARY_LESS:                return false;
8615                 case EXPR_BINARY_LESSEQUAL:           return false;
8616                 case EXPR_BINARY_GREATER:             return false;
8617                 case EXPR_BINARY_GREATEREQUAL:        return false;
8618                 case EXPR_BINARY_BITWISE_AND:         return false;
8619                 case EXPR_BINARY_BITWISE_OR:          return false;
8620                 case EXPR_BINARY_BITWISE_XOR:         return false;
8621                 case EXPR_BINARY_SHIFTLEFT:           return false;
8622                 case EXPR_BINARY_SHIFTRIGHT:          return false;
8623                 case EXPR_BINARY_ASSIGN:              return true;
8624                 case EXPR_BINARY_MUL_ASSIGN:          return true;
8625                 case EXPR_BINARY_DIV_ASSIGN:          return true;
8626                 case EXPR_BINARY_MOD_ASSIGN:          return true;
8627                 case EXPR_BINARY_ADD_ASSIGN:          return true;
8628                 case EXPR_BINARY_SUB_ASSIGN:          return true;
8629                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:    return true;
8630                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:   return true;
8631                 case EXPR_BINARY_BITWISE_AND_ASSIGN:  return true;
8632                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:  return true;
8633                 case EXPR_BINARY_BITWISE_OR_ASSIGN:   return true;
8634
8635                 /* Only examine the right hand side of && and ||, because the left hand
8636                  * side already has the effect of controlling the execution of the right
8637                  * hand side */
8638                 case EXPR_BINARY_LOGICAL_AND:
8639                 case EXPR_BINARY_LOGICAL_OR:
8640                 /* Only examine the right hand side of a comma expression, because the left
8641                  * hand side has a separate warning */
8642                 case EXPR_BINARY_COMMA:
8643                         return expression_has_effect(expr->binary.right);
8644
8645                 case EXPR_BINARY_ISGREATER:           return false;
8646                 case EXPR_BINARY_ISGREATEREQUAL:      return false;
8647                 case EXPR_BINARY_ISLESS:              return false;
8648                 case EXPR_BINARY_ISLESSEQUAL:         return false;
8649                 case EXPR_BINARY_ISLESSGREATER:       return false;
8650                 case EXPR_BINARY_ISUNORDERED:         return false;
8651         }
8652
8653         internal_errorf(HERE, "unexpected expression");
8654 }
8655
8656 static void semantic_comma(binary_expression_t *expression)
8657 {
8658         const expression_t *const left = expression->left;
8659         if (!expression_has_effect(left)) {
8660                 source_position_t const *const pos = &left->base.source_position;
8661                 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8662         }
8663         expression->base.type = expression->right->base.type;
8664 }
8665
8666 /**
8667  * @param prec_r precedence of the right operand
8668  */
8669 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8670 static expression_t *parse_##binexpression_type(expression_t *left)          \
8671 {                                                                            \
8672         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
8673         binexpr->binary.left  = left;                                            \
8674         eat(token_kind);                                                         \
8675                                                                              \
8676         expression_t *right = parse_subexpression(prec_r);                       \
8677                                                                              \
8678         binexpr->binary.right = right;                                           \
8679         sfunc(&binexpr->binary);                                                 \
8680                                                                              \
8681         return binexpr;                                                          \
8682 }
8683
8684 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
8685 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
8686 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
8687 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
8688 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
8689 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
8690 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
8691 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
8692 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
8693 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
8694 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
8695 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
8696 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
8697 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_integer)
8698 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_integer)
8699 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_integer)
8700 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
8701 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
8702 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
8703 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
8704 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
8705 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
8706 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
8707 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
8708 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_shift_assign)
8709 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_shift_assign)
8710 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
8711 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_integer_assign)
8712 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
8713 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
8714
8715
8716 static expression_t *parse_subexpression(precedence_t precedence)
8717 {
8718         if (token.kind < 0) {
8719                 return expected_expression_error();
8720         }
8721
8722         expression_parser_function_t *parser
8723                 = &expression_parsers[token.kind];
8724         expression_t                 *left;
8725
8726         if (parser->parser != NULL) {
8727                 left = parser->parser();
8728         } else {
8729                 left = parse_primary_expression();
8730         }
8731         assert(left != NULL);
8732
8733         while (true) {
8734                 if (token.kind < 0) {
8735                         return expected_expression_error();
8736                 }
8737
8738                 parser = &expression_parsers[token.kind];
8739                 if (parser->infix_parser == NULL)
8740                         break;
8741                 if (parser->infix_precedence < precedence)
8742                         break;
8743
8744                 left = parser->infix_parser(left);
8745
8746                 assert(left != NULL);
8747         }
8748
8749         return left;
8750 }
8751
8752 /**
8753  * Parse an expression.
8754  */
8755 static expression_t *parse_expression(void)
8756 {
8757         return parse_subexpression(PREC_EXPRESSION);
8758 }
8759
8760 /**
8761  * Register a parser for a prefix-like operator.
8762  *
8763  * @param parser      the parser function
8764  * @param token_kind  the token type of the prefix token
8765  */
8766 static void register_expression_parser(parse_expression_function parser,
8767                                        int token_kind)
8768 {
8769         expression_parser_function_t *entry = &expression_parsers[token_kind];
8770
8771         if (entry->parser != NULL) {
8772                 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8773                 panic("trying to register multiple expression parsers for a token");
8774         }
8775         entry->parser = parser;
8776 }
8777
8778 /**
8779  * Register a parser for an infix operator with given precedence.
8780  *
8781  * @param parser      the parser function
8782  * @param token_kind  the token type of the infix operator
8783  * @param precedence  the precedence of the operator
8784  */
8785 static void register_infix_parser(parse_expression_infix_function parser,
8786                                   int token_kind, precedence_t precedence)
8787 {
8788         expression_parser_function_t *entry = &expression_parsers[token_kind];
8789
8790         if (entry->infix_parser != NULL) {
8791                 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8792                 panic("trying to register multiple infix expression parsers for a "
8793                       "token");
8794         }
8795         entry->infix_parser     = parser;
8796         entry->infix_precedence = precedence;
8797 }
8798
8799 /**
8800  * Initialize the expression parsers.
8801  */
8802 static void init_expression_parsers(void)
8803 {
8804         memset(&expression_parsers, 0, sizeof(expression_parsers));
8805
8806         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
8807         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
8808         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
8809         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
8810         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
8811         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
8812         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
8813         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
8814         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
8815         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
8816         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
8817         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
8818         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
8819         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
8820         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
8821         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
8822         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
8823         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
8824         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8825         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
8826         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
8827         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
8828         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
8829         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
8830         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
8831         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
8832         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
8833         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
8834         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
8835         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
8836         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
8837         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
8838         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
8839         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
8840         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
8841         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
8842         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
8843
8844         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
8845         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
8846         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
8847         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
8848         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
8849         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
8850         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8851         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8852         register_expression_parser(parse_sizeof,                      T_sizeof);
8853         register_expression_parser(parse_alignof,                     T___alignof__);
8854         register_expression_parser(parse_extension,                   T___extension__);
8855         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
8856         register_expression_parser(parse_delete,                      T_delete);
8857         register_expression_parser(parse_throw,                       T_throw);
8858 }
8859
8860 /**
8861  * Parse a asm statement arguments specification.
8862  */
8863 static asm_argument_t *parse_asm_arguments(bool is_out)
8864 {
8865         asm_argument_t  *result = NULL;
8866         asm_argument_t **anchor = &result;
8867
8868         while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8869                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8870                 memset(argument, 0, sizeof(argument[0]));
8871
8872                 if (next_if('[')) {
8873                         if (token.kind != T_IDENTIFIER) {
8874                                 parse_error_expected("while parsing asm argument",
8875                                                      T_IDENTIFIER, NULL);
8876                                 return NULL;
8877                         }
8878                         argument->symbol = token.identifier.symbol;
8879
8880                         expect(']', end_error);
8881                 }
8882
8883                 argument->constraints = parse_string_literals();
8884                 expect('(', end_error);
8885                 add_anchor_token(')');
8886                 expression_t *expression = parse_expression();
8887                 rem_anchor_token(')');
8888                 if (is_out) {
8889                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
8890                          * change size or type representation (e.g. int -> long is ok, but
8891                          * int -> float is not) */
8892                         if (expression->kind == EXPR_UNARY_CAST) {
8893                                 type_t      *const type = expression->base.type;
8894                                 type_kind_t  const kind = type->kind;
8895                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8896                                         unsigned flags;
8897                                         unsigned size;
8898                                         if (kind == TYPE_ATOMIC) {
8899                                                 atomic_type_kind_t const akind = type->atomic.akind;
8900                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8901                                                 size  = get_atomic_type_size(akind);
8902                                         } else {
8903                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8904                                                 size  = get_type_size(type_void_ptr);
8905                                         }
8906
8907                                         do {
8908                                                 expression_t *const value      = expression->unary.value;
8909                                                 type_t       *const value_type = value->base.type;
8910                                                 type_kind_t   const value_kind = value_type->kind;
8911
8912                                                 unsigned value_flags;
8913                                                 unsigned value_size;
8914                                                 if (value_kind == TYPE_ATOMIC) {
8915                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
8916                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8917                                                         value_size  = get_atomic_type_size(value_akind);
8918                                                 } else if (value_kind == TYPE_POINTER) {
8919                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8920                                                         value_size  = get_type_size(type_void_ptr);
8921                                                 } else {
8922                                                         break;
8923                                                 }
8924
8925                                                 if (value_flags != flags || value_size != size)
8926                                                         break;
8927
8928                                                 expression = value;
8929                                         } while (expression->kind == EXPR_UNARY_CAST);
8930                                 }
8931                         }
8932
8933                         if (!is_lvalue(expression)) {
8934                                 errorf(&expression->base.source_position,
8935                                        "asm output argument is not an lvalue");
8936                         }
8937
8938                         if (argument->constraints.begin[0] == '=')
8939                                 determine_lhs_ent(expression, NULL);
8940                         else
8941                                 mark_vars_read(expression, NULL);
8942                 } else {
8943                         mark_vars_read(expression, NULL);
8944                 }
8945                 argument->expression = expression;
8946                 expect(')', end_error);
8947
8948                 set_address_taken(expression, true);
8949
8950                 *anchor = argument;
8951                 anchor  = &argument->next;
8952
8953                 if (!next_if(','))
8954                         break;
8955         }
8956
8957         return result;
8958 end_error:
8959         return NULL;
8960 }
8961
8962 /**
8963  * Parse a asm statement clobber specification.
8964  */
8965 static asm_clobber_t *parse_asm_clobbers(void)
8966 {
8967         asm_clobber_t *result  = NULL;
8968         asm_clobber_t **anchor = &result;
8969
8970         while (token.kind == T_STRING_LITERAL) {
8971                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8972                 clobber->clobber       = parse_string_literals();
8973
8974                 *anchor = clobber;
8975                 anchor  = &clobber->next;
8976
8977                 if (!next_if(','))
8978                         break;
8979         }
8980
8981         return result;
8982 }
8983
8984 /**
8985  * Parse an asm statement.
8986  */
8987 static statement_t *parse_asm_statement(void)
8988 {
8989         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
8990         asm_statement_t *asm_statement = &statement->asms;
8991
8992         eat(T_asm);
8993
8994         if (next_if(T_volatile))
8995                 asm_statement->is_volatile = true;
8996
8997         expect('(', end_error);
8998         add_anchor_token(')');
8999         if (token.kind != T_STRING_LITERAL) {
9000                 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9001                 goto end_of_asm;
9002         }
9003         asm_statement->asm_text = parse_string_literals();
9004
9005         add_anchor_token(':');
9006         if (!next_if(':')) {
9007                 rem_anchor_token(':');
9008                 goto end_of_asm;
9009         }
9010
9011         asm_statement->outputs = parse_asm_arguments(true);
9012         if (!next_if(':')) {
9013                 rem_anchor_token(':');
9014                 goto end_of_asm;
9015         }
9016
9017         asm_statement->inputs = parse_asm_arguments(false);
9018         if (!next_if(':')) {
9019                 rem_anchor_token(':');
9020                 goto end_of_asm;
9021         }
9022         rem_anchor_token(':');
9023
9024         asm_statement->clobbers = parse_asm_clobbers();
9025
9026 end_of_asm:
9027         rem_anchor_token(')');
9028         expect(')', end_error);
9029         expect(';', end_error);
9030
9031 end_error:
9032         if (asm_statement->outputs == NULL) {
9033                 /* GCC: An 'asm' instruction without any output operands will be treated
9034                  * identically to a volatile 'asm' instruction. */
9035                 asm_statement->is_volatile = true;
9036         }
9037
9038         return statement;
9039 }
9040
9041 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9042 {
9043         statement_t *inner_stmt;
9044         switch (token.kind) {
9045                 case '}':
9046                         errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9047                         inner_stmt = create_error_statement();
9048                         break;
9049
9050                 case ';':
9051                         if (label->kind == STATEMENT_LABEL) {
9052                                 /* Eat an empty statement here, to avoid the warning about an empty
9053                                  * statement after a label.  label:; is commonly used to have a label
9054                                  * before a closing brace. */
9055                                 inner_stmt = create_empty_statement();
9056                                 next_token();
9057                                 break;
9058                         }
9059                         /* FALLTHROUGH */
9060
9061                 default:
9062                         inner_stmt = parse_statement();
9063                         /* ISO/IEC  9899:1999(E) §6.8:1/6.8.2:1  Declarations are no statements */
9064                         /* ISO/IEC 14882:1998(E) §6:1/§6.7       Declarations are statements */
9065                         if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9066                                 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9067                         }
9068                         break;
9069         }
9070         return inner_stmt;
9071 }
9072
9073 /**
9074  * Parse a case statement.
9075  */
9076 static statement_t *parse_case_statement(void)
9077 {
9078         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9079         source_position_t *const pos       = &statement->base.source_position;
9080
9081         eat(T_case);
9082
9083         expression_t *expression = parse_expression();
9084         type_t *expression_type = expression->base.type;
9085         type_t *skipped         = skip_typeref(expression_type);
9086         if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9087                 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9088                        expression, expression_type);
9089         }
9090
9091         type_t *type = expression_type;
9092         if (current_switch != NULL) {
9093                 type_t *switch_type = current_switch->expression->base.type;
9094                 if (is_type_valid(switch_type)) {
9095                         expression = create_implicit_cast(expression, switch_type);
9096                 }
9097         }
9098
9099         statement->case_label.expression = expression;
9100         expression_classification_t const expr_class = is_constant_expression(expression);
9101         if (expr_class != EXPR_CLASS_CONSTANT) {
9102                 if (expr_class != EXPR_CLASS_ERROR) {
9103                         errorf(pos, "case label does not reduce to an integer constant");
9104                 }
9105                 statement->case_label.is_bad = true;
9106         } else {
9107                 long const val = fold_constant_to_int(expression);
9108                 statement->case_label.first_case = val;
9109                 statement->case_label.last_case  = val;
9110         }
9111
9112         if (GNU_MODE) {
9113                 if (next_if(T_DOTDOTDOT)) {
9114                         expression_t *end_range = parse_expression();
9115                         expression_type = expression->base.type;
9116                         skipped         = skip_typeref(expression_type);
9117                         if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9118                                 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9119                                            expression, expression_type);
9120                         }
9121
9122                         end_range = create_implicit_cast(end_range, type);
9123                         statement->case_label.end_range = end_range;
9124                         expression_classification_t const end_class = is_constant_expression(end_range);
9125                         if (end_class != EXPR_CLASS_CONSTANT) {
9126                                 if (end_class != EXPR_CLASS_ERROR) {
9127                                         errorf(pos, "case range does not reduce to an integer constant");
9128                                 }
9129                                 statement->case_label.is_bad = true;
9130                         } else {
9131                                 long const val = fold_constant_to_int(end_range);
9132                                 statement->case_label.last_case = val;
9133
9134                                 if (val < statement->case_label.first_case) {
9135                                         statement->case_label.is_empty_range = true;
9136                                         warningf(WARN_OTHER, pos, "empty range specified");
9137                                 }
9138                         }
9139                 }
9140         }
9141
9142         PUSH_PARENT(statement);
9143
9144         expect(':', end_error);
9145 end_error:
9146
9147         if (current_switch != NULL) {
9148                 if (! statement->case_label.is_bad) {
9149                         /* Check for duplicate case values */
9150                         case_label_statement_t *c = &statement->case_label;
9151                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9152                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9153                                         continue;
9154
9155                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9156                                         continue;
9157
9158                                 errorf(pos, "duplicate case value (previously used %P)",
9159                                        &l->base.source_position);
9160                                 break;
9161                         }
9162                 }
9163                 /* link all cases into the switch statement */
9164                 if (current_switch->last_case == NULL) {
9165                         current_switch->first_case      = &statement->case_label;
9166                 } else {
9167                         current_switch->last_case->next = &statement->case_label;
9168                 }
9169                 current_switch->last_case = &statement->case_label;
9170         } else {
9171                 errorf(pos, "case label not within a switch statement");
9172         }
9173
9174         statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9175
9176         POP_PARENT();
9177         return statement;
9178 }
9179
9180 /**
9181  * Parse a default statement.
9182  */
9183 static statement_t *parse_default_statement(void)
9184 {
9185         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9186
9187         eat(T_default);
9188
9189         PUSH_PARENT(statement);
9190
9191         expect(':', end_error);
9192 end_error:
9193
9194         if (current_switch != NULL) {
9195                 const case_label_statement_t *def_label = current_switch->default_label;
9196                 if (def_label != NULL) {
9197                         errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9198                 } else {
9199                         current_switch->default_label = &statement->case_label;
9200
9201                         /* link all cases into the switch statement */
9202                         if (current_switch->last_case == NULL) {
9203                                 current_switch->first_case      = &statement->case_label;
9204                         } else {
9205                                 current_switch->last_case->next = &statement->case_label;
9206                         }
9207                         current_switch->last_case = &statement->case_label;
9208                 }
9209         } else {
9210                 errorf(&statement->base.source_position,
9211                         "'default' label not within a switch statement");
9212         }
9213
9214         statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9215
9216         POP_PARENT();
9217         return statement;
9218 }
9219
9220 /**
9221  * Parse a label statement.
9222  */
9223 static statement_t *parse_label_statement(void)
9224 {
9225         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9226         label_t     *const label     = get_label();
9227         statement->label.label = label;
9228
9229         PUSH_PARENT(statement);
9230
9231         /* if statement is already set then the label is defined twice,
9232          * otherwise it was just mentioned in a goto/local label declaration so far
9233          */
9234         source_position_t const* const pos = &statement->base.source_position;
9235         if (label->statement != NULL) {
9236                 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9237         } else {
9238                 label->base.source_position = *pos;
9239                 label->statement            = statement;
9240         }
9241
9242         eat(':');
9243
9244         if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9245                 parse_attributes(NULL); // TODO process attributes
9246         }
9247
9248         statement->label.statement = parse_label_inner_statement(statement, "label");
9249
9250         /* remember the labels in a list for later checking */
9251         *label_anchor = &statement->label;
9252         label_anchor  = &statement->label.next;
9253
9254         POP_PARENT();
9255         return statement;
9256 }
9257
9258 static statement_t *parse_inner_statement(void)
9259 {
9260         statement_t *const stmt = parse_statement();
9261         /* ISO/IEC  9899:1999(E) §6.8:1/6.8.2:1  Declarations are no statements */
9262         /* ISO/IEC 14882:1998(E) §6:1/§6.7       Declarations are statements */
9263         if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9264                 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9265         }
9266         return stmt;
9267 }
9268
9269 /**
9270  * Parse an expression in parentheses and mark its variables as read.
9271  */
9272 static expression_t *parse_condition(void)
9273 {
9274         expect('(', end_error0);
9275         add_anchor_token(')');
9276         expression_t *const expr = parse_expression();
9277         mark_vars_read(expr, NULL);
9278         rem_anchor_token(')');
9279         expect(')', end_error1);
9280 end_error1:
9281         return expr;
9282 end_error0:
9283         return create_error_expression();
9284 }
9285
9286 /**
9287  * Parse an if statement.
9288  */
9289 static statement_t *parse_if(void)
9290 {
9291         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9292
9293         eat(T_if);
9294
9295         PUSH_PARENT(statement);
9296
9297         add_anchor_token('{');
9298
9299         expression_t *const expr = parse_condition();
9300         statement->ifs.condition = expr;
9301         /* §6.8.4.1:1  The controlling expression of an if statement shall have
9302          *             scalar type. */
9303         semantic_condition(expr, "condition of 'if'-statment");
9304
9305         rem_anchor_token('{');
9306
9307         add_anchor_token(T_else);
9308         statement_t *const true_stmt = parse_inner_statement();
9309         statement->ifs.true_statement = true_stmt;
9310         rem_anchor_token(T_else);
9311
9312         if (true_stmt->kind == STATEMENT_EMPTY) {
9313                 warningf(WARN_EMPTY_BODY, HERE,
9314                         "suggest braces around empty body in an ‘if’ statement");
9315         }
9316
9317         if (next_if(T_else)) {
9318                 statement->ifs.false_statement = parse_inner_statement();
9319
9320                 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9321                         warningf(WARN_EMPTY_BODY, HERE,
9322                                         "suggest braces around empty body in an ‘if’ statement");
9323                 }
9324         } else if (true_stmt->kind == STATEMENT_IF &&
9325                         true_stmt->ifs.false_statement != NULL) {
9326                 source_position_t const *const pos = &true_stmt->base.source_position;
9327                 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9328         }
9329
9330         POP_PARENT();
9331         return statement;
9332 }
9333
9334 /**
9335  * Check that all enums are handled in a switch.
9336  *
9337  * @param statement  the switch statement to check
9338  */
9339 static void check_enum_cases(const switch_statement_t *statement)
9340 {
9341         if (!is_warn_on(WARN_SWITCH_ENUM))
9342                 return;
9343         const type_t *type = skip_typeref(statement->expression->base.type);
9344         if (! is_type_enum(type))
9345                 return;
9346         const enum_type_t *enumt = &type->enumt;
9347
9348         /* if we have a default, no warnings */
9349         if (statement->default_label != NULL)
9350                 return;
9351
9352         /* FIXME: calculation of value should be done while parsing */
9353         /* TODO: quadratic algorithm here. Change to an n log n one */
9354         long            last_value = -1;
9355         const entity_t *entry      = enumt->enume->base.next;
9356         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9357              entry = entry->base.next) {
9358                 const expression_t *expression = entry->enum_value.value;
9359                 long                value      = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9360                 bool                found      = false;
9361                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9362                         if (l->expression == NULL)
9363                                 continue;
9364                         if (l->first_case <= value && value <= l->last_case) {
9365                                 found = true;
9366                                 break;
9367                         }
9368                 }
9369                 if (!found) {
9370                         source_position_t const *const pos = &statement->base.source_position;
9371                         warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9372                 }
9373                 last_value = value;
9374         }
9375 }
9376
9377 /**
9378  * Parse a switch statement.
9379  */
9380 static statement_t *parse_switch(void)
9381 {
9382         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9383
9384         eat(T_switch);
9385
9386         PUSH_PARENT(statement);
9387
9388         expression_t *const expr = parse_condition();
9389         type_t       *      type = skip_typeref(expr->base.type);
9390         if (is_type_integer(type)) {
9391                 type = promote_integer(type);
9392                 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9393                         warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9394                 }
9395         } else if (is_type_valid(type)) {
9396                 errorf(&expr->base.source_position,
9397                        "switch quantity is not an integer, but '%T'", type);
9398                 type = type_error_type;
9399         }
9400         statement->switchs.expression = create_implicit_cast(expr, type);
9401
9402         switch_statement_t *rem = current_switch;
9403         current_switch          = &statement->switchs;
9404         statement->switchs.body = parse_inner_statement();
9405         current_switch          = rem;
9406
9407         if (statement->switchs.default_label == NULL) {
9408                 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9409         }
9410         check_enum_cases(&statement->switchs);
9411
9412         POP_PARENT();
9413         return statement;
9414 }
9415
9416 static statement_t *parse_loop_body(statement_t *const loop)
9417 {
9418         statement_t *const rem = current_loop;
9419         current_loop = loop;
9420
9421         statement_t *const body = parse_inner_statement();
9422
9423         current_loop = rem;
9424         return body;
9425 }
9426
9427 /**
9428  * Parse a while statement.
9429  */
9430 static statement_t *parse_while(void)
9431 {
9432         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9433
9434         eat(T_while);
9435
9436         PUSH_PARENT(statement);
9437
9438         expression_t *const cond = parse_condition();
9439         statement->whiles.condition = cond;
9440         /* §6.8.5:2    The controlling expression of an iteration statement shall
9441          *             have scalar type. */
9442         semantic_condition(cond, "condition of 'while'-statement");
9443
9444         statement->whiles.body = parse_loop_body(statement);
9445
9446         POP_PARENT();
9447         return statement;
9448 }
9449
9450 /**
9451  * Parse a do statement.
9452  */
9453 static statement_t *parse_do(void)
9454 {
9455         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9456
9457         eat(T_do);
9458
9459         PUSH_PARENT(statement);
9460
9461         add_anchor_token(T_while);
9462         statement->do_while.body = parse_loop_body(statement);
9463         rem_anchor_token(T_while);
9464
9465         expect(T_while, end_error0);
9466 end_error0:;
9467         expression_t *const cond = parse_condition();
9468         statement->do_while.condition = cond;
9469         /* §6.8.5:2    The controlling expression of an iteration statement shall
9470          *             have scalar type. */
9471         semantic_condition(cond, "condition of 'do-while'-statement");
9472         expect(';', end_error1);
9473 end_error1:
9474
9475         POP_PARENT();
9476         return statement;
9477 }
9478
9479 /**
9480  * Parse a for statement.
9481  */
9482 static statement_t *parse_for(void)
9483 {
9484         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9485
9486         eat(T_for);
9487
9488         PUSH_PARENT(statement);
9489         PUSH_SCOPE(&statement->fors.scope);
9490
9491         expect('(', end_error1);
9492         add_anchor_token(')');
9493
9494         PUSH_EXTENSION();
9495
9496         if (next_if(';')) {
9497         } else if (is_declaration_specifier(&token)) {
9498                 parse_declaration(record_entity, DECL_FLAGS_NONE);
9499         } else {
9500                 add_anchor_token(';');
9501                 expression_t *const init = parse_expression();
9502                 statement->fors.initialisation = init;
9503                 mark_vars_read(init, ENT_ANY);
9504                 if (!expression_has_effect(init)) {
9505                         warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9506                 }
9507                 rem_anchor_token(';');
9508                 expect(';', end_error3);
9509 end_error3:;
9510         }
9511
9512         POP_EXTENSION();
9513
9514         if (token.kind != ';') {
9515                 add_anchor_token(';');
9516                 expression_t *const cond = parse_expression();
9517                 statement->fors.condition = cond;
9518                 /* §6.8.5:2    The controlling expression of an iteration statement
9519                  *             shall have scalar type. */
9520                 semantic_condition(cond, "condition of 'for'-statement");
9521                 mark_vars_read(cond, NULL);
9522                 rem_anchor_token(';');
9523         }
9524         expect(';', end_error2);
9525 end_error2:
9526         if (token.kind != ')') {
9527                 expression_t *const step = parse_expression();
9528                 statement->fors.step = step;
9529                 mark_vars_read(step, ENT_ANY);
9530                 if (!expression_has_effect(step)) {
9531                         warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9532                 }
9533         }
9534         rem_anchor_token(')');
9535         expect(')', end_error1);
9536 end_error1:
9537         statement->fors.body = parse_loop_body(statement);
9538
9539         POP_SCOPE();
9540         POP_PARENT();
9541         return statement;
9542 }
9543
9544 /**
9545  * Parse a goto statement.
9546  */
9547 static statement_t *parse_goto(void)
9548 {
9549         statement_t *statement;
9550         if (GNU_MODE && look_ahead(1)->kind == '*') {
9551                 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9552                 eat(T_goto);
9553                 eat('*');
9554
9555                 expression_t *expression = parse_expression();
9556                 mark_vars_read(expression, NULL);
9557
9558                 /* Argh: although documentation says the expression must be of type void*,
9559                  * gcc accepts anything that can be casted into void* without error */
9560                 type_t *type = expression->base.type;
9561
9562                 if (type != type_error_type) {
9563                         if (!is_type_pointer(type) && !is_type_integer(type)) {
9564                                 errorf(&expression->base.source_position,
9565                                         "cannot convert to a pointer type");
9566                         } else if (type != type_void_ptr) {
9567                                 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9568                         }
9569                         expression = create_implicit_cast(expression, type_void_ptr);
9570                 }
9571
9572                 statement->computed_goto.expression = expression;
9573         } else {
9574                 statement = allocate_statement_zero(STATEMENT_GOTO);
9575                 eat(T_goto);
9576                 if (token.kind == T_IDENTIFIER) {
9577                         label_t *const label = get_label();
9578                         label->used            = true;
9579                         statement->gotos.label = label;
9580
9581                         /* remember the goto's in a list for later checking */
9582                         *goto_anchor = &statement->gotos;
9583                         goto_anchor  = &statement->gotos.next;
9584                 } else {
9585                         if (GNU_MODE)
9586                                 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9587                         else
9588                                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9589                         eat_until_anchor();
9590                         statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous)->label;
9591                 }
9592         }
9593
9594         expect(';', end_error);
9595
9596 end_error:
9597         return statement;
9598 }
9599
9600 /**
9601  * Parse a continue statement.
9602  */
9603 static statement_t *parse_continue(void)
9604 {
9605         if (current_loop == NULL) {
9606                 errorf(HERE, "continue statement not within loop");
9607         }
9608
9609         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9610
9611         eat(T_continue);
9612         expect(';', end_error);
9613
9614 end_error:
9615         return statement;
9616 }
9617
9618 /**
9619  * Parse a break statement.
9620  */
9621 static statement_t *parse_break(void)
9622 {
9623         if (current_switch == NULL && current_loop == NULL) {
9624                 errorf(HERE, "break statement not within loop or switch");
9625         }
9626
9627         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9628
9629         eat(T_break);
9630         expect(';', end_error);
9631
9632 end_error:
9633         return statement;
9634 }
9635
9636 /**
9637  * Parse a __leave statement.
9638  */
9639 static statement_t *parse_leave_statement(void)
9640 {
9641         if (current_try == NULL) {
9642                 errorf(HERE, "__leave statement not within __try");
9643         }
9644
9645         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9646
9647         eat(T___leave);
9648         expect(';', end_error);
9649
9650 end_error:
9651         return statement;
9652 }
9653
9654 /**
9655  * Check if a given entity represents a local variable.
9656  */
9657 static bool is_local_variable(const entity_t *entity)
9658 {
9659         if (entity->kind != ENTITY_VARIABLE)
9660                 return false;
9661
9662         switch ((storage_class_tag_t) entity->declaration.storage_class) {
9663         case STORAGE_CLASS_AUTO:
9664         case STORAGE_CLASS_REGISTER: {
9665                 const type_t *type = skip_typeref(entity->declaration.type);
9666                 if (is_type_function(type)) {
9667                         return false;
9668                 } else {
9669                         return true;
9670                 }
9671         }
9672         default:
9673                 return false;
9674         }
9675 }
9676
9677 /**
9678  * Check if a given expression represents a local variable.
9679  */
9680 static bool expression_is_local_variable(const expression_t *expression)
9681 {
9682         if (expression->base.kind != EXPR_REFERENCE) {
9683                 return false;
9684         }
9685         const entity_t *entity = expression->reference.entity;
9686         return is_local_variable(entity);
9687 }
9688
9689 /**
9690  * Check if a given expression represents a local variable and
9691  * return its declaration then, else return NULL.
9692  */
9693 entity_t *expression_is_variable(const expression_t *expression)
9694 {
9695         if (expression->base.kind != EXPR_REFERENCE) {
9696                 return NULL;
9697         }
9698         entity_t *entity = expression->reference.entity;
9699         if (entity->kind != ENTITY_VARIABLE)
9700                 return NULL;
9701
9702         return entity;
9703 }
9704
9705 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9706 {
9707         if (c_mode & _CXX || strict_mode) {
9708                 errorf(pos, msg);
9709         } else {
9710                 warningf(WARN_OTHER, pos, msg);
9711         }
9712 }
9713
9714 /**
9715  * Parse a return statement.
9716  */
9717 static statement_t *parse_return(void)
9718 {
9719         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9720         eat(T_return);
9721
9722         expression_t *return_value = NULL;
9723         if (token.kind != ';') {
9724                 return_value = parse_expression();
9725                 mark_vars_read(return_value, NULL);
9726         }
9727
9728         const type_t *const func_type = skip_typeref(current_function->base.type);
9729         assert(is_type_function(func_type));
9730         type_t *const return_type = skip_typeref(func_type->function.return_type);
9731
9732         source_position_t const *const pos = &statement->base.source_position;
9733         if (return_value != NULL) {
9734                 type_t *return_value_type = skip_typeref(return_value->base.type);
9735
9736                 if (is_type_void(return_type)) {
9737                         if (!is_type_void(return_value_type)) {
9738                                 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9739                                 /* Only warn in C mode, because GCC does the same */
9740                                 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9741                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9742                                 /* Only warn in C mode, because GCC does the same */
9743                                 err_or_warn(pos, "'return' with expression in function returning 'void'");
9744                         }
9745                 } else {
9746                         assign_error_t error = semantic_assign(return_type, return_value);
9747                         report_assign_error(error, return_type, return_value, "'return'",
9748                                             pos);
9749                 }
9750                 return_value = create_implicit_cast(return_value, return_type);
9751                 /* check for returning address of a local var */
9752                 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9753                         const expression_t *expression = return_value->unary.value;
9754                         if (expression_is_local_variable(expression)) {
9755                                 warningf(WARN_OTHER, pos, "function returns address of local variable");
9756                         }
9757                 }
9758         } else if (!is_type_void(return_type)) {
9759                 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9760                 err_or_warn(pos, "'return' without value, in function returning non-void");
9761         }
9762         statement->returns.value = return_value;
9763
9764         expect(';', end_error);
9765
9766 end_error:
9767         return statement;
9768 }
9769
9770 /**
9771  * Parse a declaration statement.
9772  */
9773 static statement_t *parse_declaration_statement(void)
9774 {
9775         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9776
9777         entity_t *before = current_scope->last_entity;
9778         if (GNU_MODE) {
9779                 parse_external_declaration();
9780         } else {
9781                 parse_declaration(record_entity, DECL_FLAGS_NONE);
9782         }
9783
9784         declaration_statement_t *const decl  = &statement->declaration;
9785         entity_t                *const begin =
9786                 before != NULL ? before->base.next : current_scope->entities;
9787         decl->declarations_begin = begin;
9788         decl->declarations_end   = begin != NULL ? current_scope->last_entity : NULL;
9789
9790         return statement;
9791 }
9792
9793 /**
9794  * Parse an expression statement, ie. expr ';'.
9795  */
9796 static statement_t *parse_expression_statement(void)
9797 {
9798         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9799
9800         expression_t *const expr         = parse_expression();
9801         statement->expression.expression = expr;
9802         mark_vars_read(expr, ENT_ANY);
9803
9804         expect(';', end_error);
9805
9806 end_error:
9807         return statement;
9808 }
9809
9810 /**
9811  * Parse a microsoft __try { } __finally { } or
9812  * __try{ } __except() { }
9813  */
9814 static statement_t *parse_ms_try_statment(void)
9815 {
9816         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9817         eat(T___try);
9818
9819         PUSH_PARENT(statement);
9820
9821         ms_try_statement_t *rem = current_try;
9822         current_try = &statement->ms_try;
9823         statement->ms_try.try_statement = parse_compound_statement(false);
9824         current_try = rem;
9825
9826         POP_PARENT();
9827
9828         if (next_if(T___except)) {
9829                 expression_t *const expr = parse_condition();
9830                 type_t       *      type = skip_typeref(expr->base.type);
9831                 if (is_type_integer(type)) {
9832                         type = promote_integer(type);
9833                 } else if (is_type_valid(type)) {
9834                         errorf(&expr->base.source_position,
9835                                "__expect expression is not an integer, but '%T'", type);
9836                         type = type_error_type;
9837                 }
9838                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9839         } else if (!next_if(T__finally)) {
9840                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9841         }
9842         statement->ms_try.final_statement = parse_compound_statement(false);
9843         return statement;
9844 }
9845
9846 static statement_t *parse_empty_statement(void)
9847 {
9848         warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9849         statement_t *const statement = create_empty_statement();
9850         eat(';');
9851         return statement;
9852 }
9853
9854 static statement_t *parse_local_label_declaration(void)
9855 {
9856         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9857
9858         eat(T___label__);
9859
9860         entity_t *begin   = NULL;
9861         entity_t *end     = NULL;
9862         entity_t **anchor = &begin;
9863         do {
9864                 if (token.kind != T_IDENTIFIER) {
9865                         parse_error_expected("while parsing local label declaration",
9866                                 T_IDENTIFIER, NULL);
9867                         goto end_error;
9868                 }
9869                 symbol_t *symbol = token.identifier.symbol;
9870                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9871                 if (entity != NULL && entity->base.parent_scope == current_scope) {
9872                         source_position_t const *const ppos = &entity->base.source_position;
9873                         errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9874                 } else {
9875                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9876                         entity->base.parent_scope    = current_scope;
9877                         entity->base.source_position = token.base.source_position;
9878
9879                         *anchor = entity;
9880                         anchor  = &entity->base.next;
9881                         end     = entity;
9882
9883                         environment_push(entity);
9884                 }
9885                 next_token();
9886         } while (next_if(','));
9887         expect(';', end_error);
9888 end_error:
9889         statement->declaration.declarations_begin = begin;
9890         statement->declaration.declarations_end   = end;
9891         return statement;
9892 }
9893
9894 static void parse_namespace_definition(void)
9895 {
9896         eat(T_namespace);
9897
9898         entity_t *entity = NULL;
9899         symbol_t *symbol = NULL;
9900
9901         if (token.kind == T_IDENTIFIER) {
9902                 symbol = token.identifier.symbol;
9903                 next_token();
9904
9905                 entity = get_entity(symbol, NAMESPACE_NORMAL);
9906                 if (entity != NULL
9907                                 && entity->kind != ENTITY_NAMESPACE
9908                                 && entity->base.parent_scope == current_scope) {
9909                         if (is_entity_valid(entity)) {
9910                                 error_redefined_as_different_kind(&token.base.source_position,
9911                                                 entity, ENTITY_NAMESPACE);
9912                         }
9913                         entity = NULL;
9914                 }
9915         }
9916
9917         if (entity == NULL) {
9918                 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9919                 entity->base.source_position = token.base.source_position;
9920                 entity->base.parent_scope    = current_scope;
9921         }
9922
9923         if (token.kind == '=') {
9924                 /* TODO: parse namespace alias */
9925                 panic("namespace alias definition not supported yet");
9926         }
9927
9928         environment_push(entity);
9929         append_entity(current_scope, entity);
9930
9931         PUSH_SCOPE(&entity->namespacee.members);
9932
9933         entity_t     *old_current_entity = current_entity;
9934         current_entity = entity;
9935
9936         expect('{', end_error);
9937         parse_externals();
9938         expect('}', end_error);
9939
9940 end_error:
9941         assert(current_entity == entity);
9942         current_entity = old_current_entity;
9943         POP_SCOPE();
9944 }
9945
9946 /**
9947  * Parse a statement.
9948  * There's also parse_statement() which additionally checks for
9949  * "statement has no effect" warnings
9950  */
9951 static statement_t *intern_parse_statement(void)
9952 {
9953         /* declaration or statement */
9954         statement_t *statement;
9955         switch (token.kind) {
9956         case T_IDENTIFIER: {
9957                 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9958                 if (la1_type == ':') {
9959                         statement = parse_label_statement();
9960                 } else if (is_typedef_symbol(token.identifier.symbol)) {
9961                         statement = parse_declaration_statement();
9962                 } else {
9963                         /* it's an identifier, the grammar says this must be an
9964                          * expression statement. However it is common that users mistype
9965                          * declaration types, so we guess a bit here to improve robustness
9966                          * for incorrect programs */
9967                         switch (la1_type) {
9968                         case '&':
9969                         case '*':
9970                                 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9971                         default:
9972                                         statement = parse_expression_statement();
9973                                 } else {
9974                         DECLARATION_START
9975                         case T_IDENTIFIER:
9976                                         statement = parse_declaration_statement();
9977                                 }
9978                                 break;
9979                         }
9980                 }
9981                 break;
9982         }
9983
9984         case T___extension__: {
9985                 /* This can be a prefix to a declaration or an expression statement.
9986                  * We simply eat it now and parse the rest with tail recursion. */
9987                 PUSH_EXTENSION();
9988                 statement = intern_parse_statement();
9989                 POP_EXTENSION();
9990                 break;
9991         }
9992
9993         DECLARATION_START
9994                 statement = parse_declaration_statement();
9995                 break;
9996
9997         case T___label__:
9998                 statement = parse_local_label_declaration();
9999                 break;
10000
10001         case ';':         statement = parse_empty_statement();         break;
10002         case '{':         statement = parse_compound_statement(false); break;
10003         case T___leave:   statement = parse_leave_statement();         break;
10004         case T___try:     statement = parse_ms_try_statment();         break;
10005         case T_asm:       statement = parse_asm_statement();           break;
10006         case T_break:     statement = parse_break();                   break;
10007         case T_case:      statement = parse_case_statement();          break;
10008         case T_continue:  statement = parse_continue();                break;
10009         case T_default:   statement = parse_default_statement();       break;
10010         case T_do:        statement = parse_do();                      break;
10011         case T_for:       statement = parse_for();                     break;
10012         case T_goto:      statement = parse_goto();                    break;
10013         case T_if:        statement = parse_if();                      break;
10014         case T_return:    statement = parse_return();                  break;
10015         case T_switch:    statement = parse_switch();                  break;
10016         case T_while:     statement = parse_while();                   break;
10017
10018         EXPRESSION_START
10019                 statement = parse_expression_statement();
10020                 break;
10021
10022         default:
10023                 errorf(HERE, "unexpected token %K while parsing statement", &token);
10024                 statement = create_error_statement();
10025                 eat_until_anchor();
10026                 break;
10027         }
10028
10029         return statement;
10030 }
10031
10032 /**
10033  * parse a statement and emits "statement has no effect" warning if needed
10034  * (This is really a wrapper around intern_parse_statement with check for 1
10035  *  single warning. It is needed, because for statement expressions we have
10036  *  to avoid the warning on the last statement)
10037  */
10038 static statement_t *parse_statement(void)
10039 {
10040         statement_t *statement = intern_parse_statement();
10041
10042         if (statement->kind == STATEMENT_EXPRESSION) {
10043                 expression_t *expression = statement->expression.expression;
10044                 if (!expression_has_effect(expression)) {
10045                         warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10046                 }
10047         }
10048
10049         return statement;
10050 }
10051
10052 /**
10053  * Parse a compound statement.
10054  */
10055 static statement_t *parse_compound_statement(bool inside_expression_statement)
10056 {
10057         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10058
10059         PUSH_PARENT(statement);
10060         PUSH_SCOPE(&statement->compound.scope);
10061
10062         eat('{');
10063         add_anchor_token('}');
10064         /* tokens, which can start a statement */
10065         /* TODO MS, __builtin_FOO */
10066         add_anchor_token('!');
10067         add_anchor_token('&');
10068         add_anchor_token('(');
10069         add_anchor_token('*');
10070         add_anchor_token('+');
10071         add_anchor_token('-');
10072         add_anchor_token(';');
10073         add_anchor_token('{');
10074         add_anchor_token('~');
10075         add_anchor_token(T_CHARACTER_CONSTANT);
10076         add_anchor_token(T_COLONCOLON);
10077         add_anchor_token(T_FLOATINGPOINT);
10078         add_anchor_token(T_IDENTIFIER);
10079         add_anchor_token(T_INTEGER);
10080         add_anchor_token(T_MINUSMINUS);
10081         add_anchor_token(T_PLUSPLUS);
10082         add_anchor_token(T_STRING_LITERAL);
10083         add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10084         add_anchor_token(T_WIDE_STRING_LITERAL);
10085         add_anchor_token(T__Bool);
10086         add_anchor_token(T__Complex);
10087         add_anchor_token(T__Imaginary);
10088         add_anchor_token(T___FUNCTION__);
10089         add_anchor_token(T___PRETTY_FUNCTION__);
10090         add_anchor_token(T___alignof__);
10091         add_anchor_token(T___attribute__);
10092         add_anchor_token(T___builtin_va_start);
10093         add_anchor_token(T___extension__);
10094         add_anchor_token(T___func__);
10095         add_anchor_token(T___imag__);
10096         add_anchor_token(T___label__);
10097         add_anchor_token(T___real__);
10098         add_anchor_token(T___thread);
10099         add_anchor_token(T_asm);
10100         add_anchor_token(T_auto);
10101         add_anchor_token(T_bool);
10102         add_anchor_token(T_break);
10103         add_anchor_token(T_case);
10104         add_anchor_token(T_char);
10105         add_anchor_token(T_class);
10106         add_anchor_token(T_const);
10107         add_anchor_token(T_const_cast);
10108         add_anchor_token(T_continue);
10109         add_anchor_token(T_default);
10110         add_anchor_token(T_delete);
10111         add_anchor_token(T_double);
10112         add_anchor_token(T_do);
10113         add_anchor_token(T_dynamic_cast);
10114         add_anchor_token(T_enum);
10115         add_anchor_token(T_extern);
10116         add_anchor_token(T_false);
10117         add_anchor_token(T_float);
10118         add_anchor_token(T_for);
10119         add_anchor_token(T_goto);
10120         add_anchor_token(T_if);
10121         add_anchor_token(T_inline);
10122         add_anchor_token(T_int);
10123         add_anchor_token(T_long);
10124         add_anchor_token(T_new);
10125         add_anchor_token(T_operator);
10126         add_anchor_token(T_register);
10127         add_anchor_token(T_reinterpret_cast);
10128         add_anchor_token(T_restrict);
10129         add_anchor_token(T_return);
10130         add_anchor_token(T_short);
10131         add_anchor_token(T_signed);
10132         add_anchor_token(T_sizeof);
10133         add_anchor_token(T_static);
10134         add_anchor_token(T_static_cast);
10135         add_anchor_token(T_struct);
10136         add_anchor_token(T_switch);
10137         add_anchor_token(T_template);
10138         add_anchor_token(T_this);
10139         add_anchor_token(T_throw);
10140         add_anchor_token(T_true);
10141         add_anchor_token(T_try);
10142         add_anchor_token(T_typedef);
10143         add_anchor_token(T_typeid);
10144         add_anchor_token(T_typename);
10145         add_anchor_token(T_typeof);
10146         add_anchor_token(T_union);
10147         add_anchor_token(T_unsigned);
10148         add_anchor_token(T_using);
10149         add_anchor_token(T_void);
10150         add_anchor_token(T_volatile);
10151         add_anchor_token(T_wchar_t);
10152         add_anchor_token(T_while);
10153
10154         statement_t **anchor            = &statement->compound.statements;
10155         bool          only_decls_so_far = true;
10156         while (token.kind != '}' && token.kind != T_EOF) {
10157                 statement_t *sub_statement = intern_parse_statement();
10158                 if (sub_statement->kind == STATEMENT_ERROR) {
10159                         break;
10160                 }
10161
10162                 if (sub_statement->kind != STATEMENT_DECLARATION) {
10163                         only_decls_so_far = false;
10164                 } else if (!only_decls_so_far) {
10165                         source_position_t const *const pos = &sub_statement->base.source_position;
10166                         warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10167                 }
10168
10169                 *anchor = sub_statement;
10170                 anchor  = &sub_statement->base.next;
10171         }
10172         expect('}', end_error);
10173 end_error:
10174
10175         /* look over all statements again to produce no effect warnings */
10176         if (is_warn_on(WARN_UNUSED_VALUE)) {
10177                 statement_t *sub_statement = statement->compound.statements;
10178                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10179                         if (sub_statement->kind != STATEMENT_EXPRESSION)
10180                                 continue;
10181                         /* don't emit a warning for the last expression in an expression
10182                          * statement as it has always an effect */
10183                         if (inside_expression_statement && sub_statement->base.next == NULL)
10184                                 continue;
10185
10186                         expression_t *expression = sub_statement->expression.expression;
10187                         if (!expression_has_effect(expression)) {
10188                                 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10189                         }
10190                 }
10191         }
10192
10193         rem_anchor_token(T_while);
10194         rem_anchor_token(T_wchar_t);
10195         rem_anchor_token(T_volatile);
10196         rem_anchor_token(T_void);
10197         rem_anchor_token(T_using);
10198         rem_anchor_token(T_unsigned);
10199         rem_anchor_token(T_union);
10200         rem_anchor_token(T_typeof);
10201         rem_anchor_token(T_typename);
10202         rem_anchor_token(T_typeid);
10203         rem_anchor_token(T_typedef);
10204         rem_anchor_token(T_try);
10205         rem_anchor_token(T_true);
10206         rem_anchor_token(T_throw);
10207         rem_anchor_token(T_this);
10208         rem_anchor_token(T_template);
10209         rem_anchor_token(T_switch);
10210         rem_anchor_token(T_struct);
10211         rem_anchor_token(T_static_cast);
10212         rem_anchor_token(T_static);
10213         rem_anchor_token(T_sizeof);
10214         rem_anchor_token(T_signed);
10215         rem_anchor_token(T_short);
10216         rem_anchor_token(T_return);
10217         rem_anchor_token(T_restrict);
10218         rem_anchor_token(T_reinterpret_cast);
10219         rem_anchor_token(T_register);
10220         rem_anchor_token(T_operator);
10221         rem_anchor_token(T_new);
10222         rem_anchor_token(T_long);
10223         rem_anchor_token(T_int);
10224         rem_anchor_token(T_inline);
10225         rem_anchor_token(T_if);
10226         rem_anchor_token(T_goto);
10227         rem_anchor_token(T_for);
10228         rem_anchor_token(T_float);
10229         rem_anchor_token(T_false);
10230         rem_anchor_token(T_extern);
10231         rem_anchor_token(T_enum);
10232         rem_anchor_token(T_dynamic_cast);
10233         rem_anchor_token(T_do);
10234         rem_anchor_token(T_double);
10235         rem_anchor_token(T_delete);
10236         rem_anchor_token(T_default);
10237         rem_anchor_token(T_continue);
10238         rem_anchor_token(T_const_cast);
10239         rem_anchor_token(T_const);
10240         rem_anchor_token(T_class);
10241         rem_anchor_token(T_char);
10242         rem_anchor_token(T_case);
10243         rem_anchor_token(T_break);
10244         rem_anchor_token(T_bool);
10245         rem_anchor_token(T_auto);
10246         rem_anchor_token(T_asm);
10247         rem_anchor_token(T___thread);
10248         rem_anchor_token(T___real__);
10249         rem_anchor_token(T___label__);
10250         rem_anchor_token(T___imag__);
10251         rem_anchor_token(T___func__);
10252         rem_anchor_token(T___extension__);
10253         rem_anchor_token(T___builtin_va_start);
10254         rem_anchor_token(T___attribute__);
10255         rem_anchor_token(T___alignof__);
10256         rem_anchor_token(T___PRETTY_FUNCTION__);
10257         rem_anchor_token(T___FUNCTION__);
10258         rem_anchor_token(T__Imaginary);
10259         rem_anchor_token(T__Complex);
10260         rem_anchor_token(T__Bool);
10261         rem_anchor_token(T_WIDE_STRING_LITERAL);
10262         rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10263         rem_anchor_token(T_STRING_LITERAL);
10264         rem_anchor_token(T_PLUSPLUS);
10265         rem_anchor_token(T_MINUSMINUS);
10266         rem_anchor_token(T_INTEGER);
10267         rem_anchor_token(T_IDENTIFIER);
10268         rem_anchor_token(T_FLOATINGPOINT);
10269         rem_anchor_token(T_COLONCOLON);
10270         rem_anchor_token(T_CHARACTER_CONSTANT);
10271         rem_anchor_token('~');
10272         rem_anchor_token('{');
10273         rem_anchor_token(';');
10274         rem_anchor_token('-');
10275         rem_anchor_token('+');
10276         rem_anchor_token('*');
10277         rem_anchor_token('(');
10278         rem_anchor_token('&');
10279         rem_anchor_token('!');
10280         rem_anchor_token('}');
10281
10282         POP_SCOPE();
10283         POP_PARENT();
10284         return statement;
10285 }
10286
10287 /**
10288  * Check for unused global static functions and variables
10289  */
10290 static void check_unused_globals(void)
10291 {
10292         if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10293                 return;
10294
10295         for (const entity_t *entity = file_scope->entities; entity != NULL;
10296              entity = entity->base.next) {
10297                 if (!is_declaration(entity))
10298                         continue;
10299
10300                 const declaration_t *declaration = &entity->declaration;
10301                 if (declaration->used                  ||
10302                     declaration->modifiers & DM_UNUSED ||
10303                     declaration->modifiers & DM_USED   ||
10304                     declaration->storage_class != STORAGE_CLASS_STATIC)
10305                         continue;
10306
10307                 warning_t   why;
10308                 char const *s;
10309                 if (entity->kind == ENTITY_FUNCTION) {
10310                         /* inhibit warning for static inline functions */
10311                         if (entity->function.is_inline)
10312                                 continue;
10313
10314                         why = WARN_UNUSED_FUNCTION;
10315                         s   = entity->function.statement != NULL ? "defined" : "declared";
10316                 } else {
10317                         why = WARN_UNUSED_VARIABLE;
10318                         s   = "defined";
10319                 }
10320
10321                 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10322         }
10323 }
10324
10325 static void parse_global_asm(void)
10326 {
10327         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10328
10329         eat(T_asm);
10330         expect('(', end_error);
10331
10332         statement->asms.asm_text = parse_string_literals();
10333         statement->base.next     = unit->global_asm;
10334         unit->global_asm         = statement;
10335
10336         expect(')', end_error);
10337         expect(';', end_error);
10338
10339 end_error:;
10340 }
10341
10342 static void parse_linkage_specification(void)
10343 {
10344         eat(T_extern);
10345
10346         source_position_t const pos     = *HERE;
10347         char const       *const linkage = parse_string_literals().begin;
10348
10349         linkage_kind_t old_linkage = current_linkage;
10350         linkage_kind_t new_linkage;
10351         if (streq(linkage, "C")) {
10352                 new_linkage = LINKAGE_C;
10353         } else if (streq(linkage, "C++")) {
10354                 new_linkage = LINKAGE_CXX;
10355         } else {
10356                 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10357                 new_linkage = LINKAGE_C;
10358         }
10359         current_linkage = new_linkage;
10360
10361         if (next_if('{')) {
10362                 parse_externals();
10363                 expect('}', end_error);
10364         } else {
10365                 parse_external();
10366         }
10367
10368 end_error:
10369         assert(current_linkage == new_linkage);
10370         current_linkage = old_linkage;
10371 }
10372
10373 static void parse_external(void)
10374 {
10375         switch (token.kind) {
10376                 case T_extern:
10377                         if (look_ahead(1)->kind == T_STRING_LITERAL) {
10378                                 parse_linkage_specification();
10379                         } else {
10380                 DECLARATION_START_NO_EXTERN
10381                 case T_IDENTIFIER:
10382                 case T___extension__:
10383                 /* tokens below are for implicit int */
10384                 case '&':  /* & x; -> int& x; (and error later, because C++ has no
10385                               implicit int) */
10386                 case '*':  /* * x; -> int* x; */
10387                 case '(':  /* (x); -> int (x); */
10388                                 PUSH_EXTENSION();
10389                                 parse_external_declaration();
10390                                 POP_EXTENSION();
10391                         }
10392                         return;
10393
10394                 case T_asm:
10395                         parse_global_asm();
10396                         return;
10397
10398                 case T_namespace:
10399                         parse_namespace_definition();
10400                         return;
10401
10402                 case ';':
10403                         if (!strict_mode) {
10404                                 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10405                                 next_token();
10406                                 return;
10407                         }
10408                         /* FALLTHROUGH */
10409
10410                 default:
10411                         errorf(HERE, "stray %K outside of function", &token);
10412                         if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10413                                 eat_until_matching_token(token.kind);
10414                         next_token();
10415                         return;
10416         }
10417 }
10418
10419 static void parse_externals(void)
10420 {
10421         add_anchor_token('}');
10422         add_anchor_token(T_EOF);
10423
10424 #ifndef NDEBUG
10425         /* make a copy of the anchor set, so we can check if it is restored after parsing */
10426         unsigned short token_anchor_copy[T_LAST_TOKEN];
10427         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10428 #endif
10429
10430         while (token.kind != T_EOF && token.kind != '}') {
10431 #ifndef NDEBUG
10432                 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10433                         unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10434                         if (count != 0) {
10435                                 /* the anchor set and its copy differs */
10436                                 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10437                         }
10438                 }
10439                 if (in_gcc_extension) {
10440                         /* an gcc extension scope was not closed */
10441                         internal_errorf(HERE, "Leaked __extension__");
10442                 }
10443 #endif
10444
10445                 parse_external();
10446         }
10447
10448         rem_anchor_token(T_EOF);
10449         rem_anchor_token('}');
10450 }
10451
10452 /**
10453  * Parse a translation unit.
10454  */
10455 static void parse_translation_unit(void)
10456 {
10457         add_anchor_token(T_EOF);
10458
10459         while (true) {
10460                 parse_externals();
10461
10462                 if (token.kind == T_EOF)
10463                         break;
10464
10465                 errorf(HERE, "stray %K outside of function", &token);
10466                 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10467                         eat_until_matching_token(token.kind);
10468                 next_token();
10469         }
10470 }
10471
10472 void set_default_visibility(elf_visibility_tag_t visibility)
10473 {
10474         default_visibility = visibility;
10475 }
10476
10477 /**
10478  * Parse the input.
10479  *
10480  * @return  the translation unit or NULL if errors occurred.
10481  */
10482 void start_parsing(void)
10483 {
10484         environment_stack = NEW_ARR_F(stack_entry_t, 0);
10485         label_stack       = NEW_ARR_F(stack_entry_t, 0);
10486         diagnostic_count  = 0;
10487         error_count       = 0;
10488         warning_count     = 0;
10489
10490         print_to_file(stderr);
10491
10492         assert(unit == NULL);
10493         unit = allocate_ast_zero(sizeof(unit[0]));
10494
10495         assert(file_scope == NULL);
10496         file_scope = &unit->scope;
10497
10498         assert(current_scope == NULL);
10499         scope_push(&unit->scope);
10500
10501         create_gnu_builtins();
10502         if (c_mode & _MS)
10503                 create_microsoft_intrinsics();
10504 }
10505
10506 translation_unit_t *finish_parsing(void)
10507 {
10508         assert(current_scope == &unit->scope);
10509         scope_pop(NULL);
10510
10511         assert(file_scope == &unit->scope);
10512         check_unused_globals();
10513         file_scope = NULL;
10514
10515         DEL_ARR_F(environment_stack);
10516         DEL_ARR_F(label_stack);
10517
10518         translation_unit_t *result = unit;
10519         unit = NULL;
10520         return result;
10521 }
10522
10523 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10524  * are given length one. */
10525 static void complete_incomplete_arrays(void)
10526 {
10527         size_t n = ARR_LEN(incomplete_arrays);
10528         for (size_t i = 0; i != n; ++i) {
10529                 declaration_t *const decl = incomplete_arrays[i];
10530                 type_t        *const type = skip_typeref(decl->type);
10531
10532                 if (!is_type_incomplete(type))
10533                         continue;
10534
10535                 source_position_t const *const pos = &decl->base.source_position;
10536                 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10537
10538                 type_t *const new_type = duplicate_type(type);
10539                 new_type->array.size_constant     = true;
10540                 new_type->array.has_implicit_size = true;
10541                 new_type->array.size              = 1;
10542
10543                 type_t *const result = identify_new_type(new_type);
10544
10545                 decl->type = result;
10546         }
10547 }
10548
10549 void prepare_main_collect2(entity_t *entity)
10550 {
10551         PUSH_SCOPE(&entity->function.statement->compound.scope);
10552
10553         // create call to __main
10554         symbol_t *symbol         = symbol_table_insert("__main");
10555         entity_t *subsubmain_ent
10556                 = create_implicit_function(symbol, &builtin_source_position);
10557
10558         expression_t *ref         = allocate_expression_zero(EXPR_REFERENCE);
10559         type_t       *ftype       = subsubmain_ent->declaration.type;
10560         ref->base.source_position = builtin_source_position;
10561         ref->base.type            = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10562         ref->reference.entity     = subsubmain_ent;
10563
10564         expression_t *call = allocate_expression_zero(EXPR_CALL);
10565         call->base.source_position = builtin_source_position;
10566         call->base.type            = type_void;
10567         call->call.function        = ref;
10568
10569         statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10570         expr_statement->base.source_position  = builtin_source_position;
10571         expr_statement->expression.expression = call;
10572
10573         statement_t *statement = entity->function.statement;
10574         assert(statement->kind == STATEMENT_COMPOUND);
10575         compound_statement_t *compounds = &statement->compound;
10576
10577         expr_statement->base.next = compounds->statements;
10578         compounds->statements     = expr_statement;
10579
10580         POP_SCOPE();
10581 }
10582
10583 void parse(void)
10584 {
10585         lookahead_bufpos = 0;
10586         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10587                 next_token();
10588         }
10589         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10590         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10591         parse_translation_unit();
10592         complete_incomplete_arrays();
10593         DEL_ARR_F(incomplete_arrays);
10594         incomplete_arrays = NULL;
10595 }
10596
10597 /**
10598  * Initialize the parser.
10599  */
10600 void init_parser(void)
10601 {
10602         sym_anonymous = symbol_table_insert("<anonymous>");
10603
10604         memset(token_anchor_set, 0, sizeof(token_anchor_set));
10605
10606         init_expression_parsers();
10607         obstack_init(&temp_obst);
10608 }
10609
10610 /**
10611  * Terminate the parser.
10612  */
10613 void exit_parser(void)
10614 {
10615         obstack_free(&temp_obst, NULL);
10616 }