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