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