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