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