simplify license header similar to libFirm
[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        &&
4075                                                         is_type_valid(prev_type) &&
4076                                                         !pos->is_system_header) {
4077                                                 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4078                                         }
4079                                 } else if (current_function == NULL) {
4080                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
4081                                                         new_storage_class == STORAGE_CLASS_STATIC) {
4082                                                 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4083                                         } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4084                                                 prev_decl->storage_class          = STORAGE_CLASS_NONE;
4085                                                 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4086                                         } else {
4087                                                 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4088                                                 if (c_mode & _CXX)
4089                                                         goto error_redeclaration;
4090                                                 goto warn_redundant_declaration;
4091                                         }
4092                                 } else if (is_type_valid(prev_type)) {
4093                                         if (old_storage_class == new_storage_class) {
4094 error_redeclaration:
4095                                                 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4096                                         } else {
4097                                                 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4098                                         }
4099                                 }
4100                         }
4101
4102                         prev_decl->modifiers |= decl->modifiers;
4103                         if (entity->kind == ENTITY_FUNCTION) {
4104                                 previous_entity->function.is_inline |= entity->function.is_inline;
4105                         }
4106                         return previous_entity;
4107                 }
4108
4109                 warning_t why;
4110                 if (is_warn_on(why = WARN_SHADOW) ||
4111                     (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4112                         char const *const what = get_entity_kind_name(previous_entity->kind);
4113                         warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4114                 }
4115         }
4116
4117         if (entity->kind == ENTITY_FUNCTION) {
4118                 if (is_definition &&
4119                                 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4120                                 !is_main(entity)) {
4121                         if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4122                                 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4123                         } else {
4124                                 goto warn_missing_declaration;
4125                         }
4126                 }
4127         } else if (entity->kind == ENTITY_VARIABLE) {
4128                 if (current_scope                     == file_scope &&
4129                     entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4130                     !entity->declaration.implicit) {
4131 warn_missing_declaration:
4132                         if (is_type_valid(skip_typeref(entity->declaration.type)))
4133                                 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4134                 }
4135         }
4136
4137 finish:
4138         environment_push(entity);
4139         append_entity(current_scope, entity);
4140
4141         return entity;
4142 }
4143
4144 static void parser_error_multiple_definition(entity_t *entity,
4145                                              const position_t *pos)
4146 {
4147         errorf(pos, "redefinition of '%N' (declared %P)", entity, &entity->base.pos);
4148 }
4149
4150 static bool is_declaration_specifier(const token_t *token)
4151 {
4152         switch (token->kind) {
4153                 DECLARATION_START
4154                         return true;
4155                 case T_IDENTIFIER:
4156                         return is_typedef_symbol(token->base.symbol);
4157
4158                 default:
4159                         return false;
4160         }
4161 }
4162
4163 static void parse_init_declarator_rest(entity_t *entity)
4164 {
4165         type_t *orig_type = type_error_type;
4166
4167         if (entity->base.kind == ENTITY_TYPEDEF) {
4168                 position_t const *const pos = &entity->base.pos;
4169                 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4170         } else {
4171                 assert(is_declaration(entity));
4172                 orig_type = entity->declaration.type;
4173         }
4174
4175         type_t *type = skip_typeref(orig_type);
4176
4177         if (entity->kind == ENTITY_VARIABLE
4178                         && entity->variable.initializer != NULL) {
4179                 parser_error_multiple_definition(entity, HERE);
4180         }
4181         eat('=');
4182
4183         declaration_t *const declaration = &entity->declaration;
4184         bool must_be_constant = false;
4185         if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4186             entity->base.parent_scope  == file_scope) {
4187                 must_be_constant = true;
4188         }
4189
4190         if (is_type_function(type)) {
4191                 position_t const *const pos = &entity->base.pos;
4192                 errorf(pos, "'%N' is initialized like a variable", entity);
4193                 orig_type = type_error_type;
4194         }
4195
4196         parse_initializer_env_t env;
4197         env.type             = orig_type;
4198         env.must_be_constant = must_be_constant;
4199         env.entity           = entity;
4200
4201         initializer_t *initializer = parse_initializer(&env);
4202
4203         if (entity->kind == ENTITY_VARIABLE) {
4204                 /* §6.7.5:22  array initializers for arrays with unknown size
4205                  * determine the array type size */
4206                 declaration->type            = env.type;
4207                 entity->variable.initializer = initializer;
4208         }
4209 }
4210
4211 /* parse rest of a declaration without any declarator */
4212 static void parse_anonymous_declaration_rest(
4213                 const declaration_specifiers_t *specifiers)
4214 {
4215         eat(';');
4216         anonymous_entity = NULL;
4217
4218         position_t const *const pos = &specifiers->pos;
4219         if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4220                         specifiers->thread_local) {
4221                 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4222         }
4223
4224         type_t *type = specifiers->type;
4225         switch (type->kind) {
4226                 case TYPE_COMPOUND_STRUCT:
4227                 case TYPE_COMPOUND_UNION: {
4228                         if (type->compound.compound->base.symbol == NULL) {
4229                                 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4230                         }
4231                         break;
4232                 }
4233
4234                 case TYPE_ENUM:
4235                         break;
4236
4237                 default:
4238                         warningf(WARN_OTHER, pos, "empty declaration");
4239                         break;
4240         }
4241 }
4242
4243 static void check_variable_type_complete(entity_t *ent)
4244 {
4245         if (ent->kind != ENTITY_VARIABLE)
4246                 return;
4247
4248         /* §6.7:7  If an identifier for an object is declared with no linkage, the
4249          *         type for the object shall be complete [...] */
4250         declaration_t *decl = &ent->declaration;
4251         if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4252                         decl->storage_class == STORAGE_CLASS_STATIC)
4253                 return;
4254
4255         type_t *const type = skip_typeref(decl->type);
4256         if (!is_type_incomplete(type))
4257                 return;
4258
4259         /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4260          * are given length one. */
4261         if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4262                 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4263                 return;
4264         }
4265
4266         errorf(&ent->base.pos, "variable '%#N' has incomplete type", ent);
4267 }
4268
4269
4270 static void parse_declaration_rest(entity_t *ndeclaration,
4271                 const declaration_specifiers_t *specifiers,
4272                 parsed_declaration_func         finished_declaration,
4273                 declarator_flags_t              flags)
4274 {
4275         add_anchor_token(';');
4276         add_anchor_token(',');
4277         while (true) {
4278                 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4279
4280                 if (token.kind == '=') {
4281                         parse_init_declarator_rest(entity);
4282                 } else if (entity->kind == ENTITY_VARIABLE) {
4283                         /* ISO/IEC 14882:1998(E) §8.5.3:3  The initializer can be omitted
4284                          * [...] where the extern specifier is explicitly used. */
4285                         declaration_t *decl = &entity->declaration;
4286                         if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4287                             is_type_reference(skip_typeref(decl->type))) {
4288                                 position_t const *const pos = &entity->base.pos;
4289                                 errorf(pos, "reference '%#N' must be initialized", entity);
4290                         }
4291                 }
4292
4293                 check_variable_type_complete(entity);
4294
4295                 if (!accept(','))
4296                         break;
4297
4298                 add_anchor_token('=');
4299                 ndeclaration = parse_declarator(specifiers, flags);
4300                 rem_anchor_token('=');
4301         }
4302         rem_anchor_token(',');
4303         rem_anchor_token(';');
4304         expect(';');
4305
4306         anonymous_entity = NULL;
4307 }
4308
4309 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4310 {
4311         symbol_t *symbol = entity->base.symbol;
4312         if (symbol == NULL)
4313                 return entity;
4314
4315         assert(entity->base.namespc == NAMESPACE_NORMAL);
4316         entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4317         if (previous_entity == NULL
4318                         || previous_entity->base.parent_scope != current_scope) {
4319                 errorf(&entity->base.pos, "expected declaration of a function parameter, found '%Y'",
4320                        symbol);
4321                 return entity;
4322         }
4323
4324         if (is_definition) {
4325                 errorf(HERE, "'%N' is initialised", entity);
4326         }
4327
4328         return record_entity(entity, false);
4329 }
4330
4331 static void parse_declaration(parsed_declaration_func finished_declaration,
4332                               declarator_flags_t      flags)
4333 {
4334         add_anchor_token(';');
4335         declaration_specifiers_t specifiers;
4336         parse_declaration_specifiers(&specifiers);
4337         rem_anchor_token(';');
4338
4339         if (token.kind == ';') {
4340                 parse_anonymous_declaration_rest(&specifiers);
4341         } else {
4342                 entity_t *entity = parse_declarator(&specifiers, flags);
4343                 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4344         }
4345 }
4346
4347 /* §6.5.2.2:6 */
4348 static type_t *get_default_promoted_type(type_t *orig_type)
4349 {
4350         type_t *result = orig_type;
4351
4352         type_t *type = skip_typeref(orig_type);
4353         if (is_type_integer(type)) {
4354                 result = promote_integer(type);
4355         } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4356                 result = type_double;
4357         }
4358
4359         return result;
4360 }
4361
4362 static void parse_kr_declaration_list(entity_t *entity)
4363 {
4364         if (entity->kind != ENTITY_FUNCTION)
4365                 return;
4366
4367         type_t *type = skip_typeref(entity->declaration.type);
4368         assert(is_type_function(type));
4369         if (!type->function.kr_style_parameters)
4370                 return;
4371
4372         add_anchor_token('{');
4373
4374         PUSH_SCOPE(&entity->function.parameters);
4375
4376         entity_t *parameter = entity->function.parameters.entities;
4377         for ( ; parameter != NULL; parameter = parameter->base.next) {
4378                 assert(parameter->base.parent_scope == NULL);
4379                 parameter->base.parent_scope = current_scope;
4380                 environment_push(parameter);
4381         }
4382
4383         /* parse declaration list */
4384         for (;;) {
4385                 switch (token.kind) {
4386                         DECLARATION_START
4387                         /* This covers symbols, which are no type, too, and results in
4388                          * better error messages.  The typical cases are misspelled type
4389                          * names and missing includes. */
4390                         case T_IDENTIFIER:
4391                                 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4392                                 break;
4393                         default:
4394                                 goto decl_list_end;
4395                 }
4396         }
4397 decl_list_end:
4398
4399         POP_SCOPE();
4400
4401         /* update function type */
4402         type_t *new_type = duplicate_type(type);
4403
4404         function_parameter_t  *parameters = NULL;
4405         function_parameter_t **anchor     = &parameters;
4406
4407         /* did we have an earlier prototype? */
4408         entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4409         if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4410                 proto_type = NULL;
4411
4412         function_parameter_t *proto_parameter = NULL;
4413         if (proto_type != NULL) {
4414                 type_t *proto_type_type = proto_type->declaration.type;
4415                 proto_parameter         = proto_type_type->function.parameters;
4416                 /* If a K&R function definition has a variadic prototype earlier, then
4417                  * make the function definition variadic, too. This should conform to
4418                  * §6.7.5.3:15 and §6.9.1:8. */
4419                 new_type->function.variadic = proto_type_type->function.variadic;
4420         } else {
4421                 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4422                  * prototype */
4423                 new_type->function.unspecified_parameters = true;
4424         }
4425
4426         bool need_incompatible_warning = false;
4427         parameter = entity->function.parameters.entities;
4428         for (; parameter != NULL; parameter = parameter->base.next,
4429                         proto_parameter =
4430                                 proto_parameter == NULL ? NULL : proto_parameter->next) {
4431                 if (parameter->kind != ENTITY_PARAMETER)
4432                         continue;
4433
4434                 type_t *parameter_type = parameter->declaration.type;
4435                 if (parameter_type == NULL) {
4436                         position_t const* const pos = &parameter->base.pos;
4437                         if (strict_mode) {
4438                                 errorf(pos, "no type specified for function '%N'", parameter);
4439                                 parameter_type = type_error_type;
4440                         } else {
4441                                 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4442                                 parameter_type = type_int;
4443                         }
4444                         parameter->declaration.type = parameter_type;
4445                 }
4446
4447                 semantic_parameter_incomplete(parameter);
4448
4449                 /* we need the default promoted types for the function type */
4450                 type_t *not_promoted = parameter_type;
4451                 parameter_type       = get_default_promoted_type(parameter_type);
4452
4453                 /* gcc special: if the type of the prototype matches the unpromoted
4454                  * type don't promote */
4455                 if (!strict_mode && proto_parameter != NULL) {
4456                         type_t *proto_p_type = skip_typeref(proto_parameter->type);
4457                         type_t *promo_skip   = skip_typeref(parameter_type);
4458                         type_t *param_skip   = skip_typeref(not_promoted);
4459                         if (!types_compatible(proto_p_type, promo_skip)
4460                                 && types_compatible(proto_p_type, param_skip)) {
4461                                 /* don't promote */
4462                                 need_incompatible_warning = true;
4463                                 parameter_type = not_promoted;
4464                         }
4465                 }
4466                 function_parameter_t *const function_parameter
4467                         = allocate_parameter(parameter_type);
4468
4469                 *anchor = function_parameter;
4470                 anchor  = &function_parameter->next;
4471         }
4472
4473         new_type->function.parameters = parameters;
4474         new_type = identify_new_type(new_type);
4475
4476         if (need_incompatible_warning) {
4477                 symbol_t   const *const sym  = entity->base.symbol;
4478                 position_t const *const pos  = &entity->base.pos;
4479                 position_t const *const ppos = &proto_type->base.pos;
4480                 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4481         }
4482         entity->declaration.type = new_type;
4483
4484         rem_anchor_token('{');
4485 }
4486
4487 static bool first_err = true;
4488
4489 /**
4490  * When called with first_err set, prints the name of the current function,
4491  * else does noting.
4492  */
4493 static void print_in_function(void)
4494 {
4495         if (first_err) {
4496                 first_err = false;
4497                 char const *const file = current_function->base.base.pos.input_name;
4498                 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4499         }
4500 }
4501
4502 /**
4503  * Check if all labels are defined in the current function.
4504  * Check if all labels are used in the current function.
4505  */
4506 static void check_labels(void)
4507 {
4508         for (const goto_statement_t *goto_statement = goto_first;
4509             goto_statement != NULL;
4510             goto_statement = goto_statement->next) {
4511                 label_t *label = goto_statement->label;
4512                 if (label->base.pos.input_name == NULL) {
4513                         print_in_function();
4514                         position_t const *const pos = &goto_statement->base.pos;
4515                         errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4516                  }
4517         }
4518
4519         if (is_warn_on(WARN_UNUSED_LABEL)) {
4520                 for (const label_statement_t *label_statement = label_first;
4521                          label_statement != NULL;
4522                          label_statement = label_statement->next) {
4523                         label_t *label = label_statement->label;
4524
4525                         if (! label->used) {
4526                                 print_in_function();
4527                                 position_t const *const pos = &label_statement->base.pos;
4528                                 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4529                         }
4530                 }
4531         }
4532 }
4533
4534 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4535 {
4536         entity_t const *const end = last != NULL ? last->base.next : NULL;
4537         for (; entity != end; entity = entity->base.next) {
4538                 if (!is_declaration(entity))
4539                         continue;
4540
4541                 declaration_t *declaration = &entity->declaration;
4542                 if (declaration->implicit)
4543                         continue;
4544
4545                 if (!declaration->used) {
4546                         print_in_function();
4547                         warningf(why, &entity->base.pos, "'%N' is unused", entity);
4548                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4549                         print_in_function();
4550                         warningf(why, &entity->base.pos, "'%N' is never read", entity);
4551                 }
4552         }
4553 }
4554
4555 static void check_unused_variables(statement_t *const stmt, void *const env)
4556 {
4557         (void)env;
4558
4559         switch (stmt->kind) {
4560                 case STATEMENT_DECLARATION: {
4561                         declaration_statement_t const *const decls = &stmt->declaration;
4562                         warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4563                         return;
4564                 }
4565
4566                 case STATEMENT_FOR:
4567                         warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4568                         return;
4569
4570                 default:
4571                         return;
4572         }
4573 }
4574
4575 /**
4576  * Check declarations of current_function for unused entities.
4577  */
4578 static void check_declarations(void)
4579 {
4580         if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4581                 const scope_t *scope = &current_function->parameters;
4582                 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4583         }
4584         if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4585                 walk_statements(current_function->body, check_unused_variables, NULL);
4586         }
4587 }
4588
4589 static int determine_truth(expression_t const* const cond)
4590 {
4591         return
4592                 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4593                 fold_constant_to_bool(cond)                         ? 1 :
4594                 -1;
4595 }
4596
4597 static void check_reachable(statement_t *);
4598 static bool reaches_end;
4599
4600 static bool expression_returns(expression_t const *const expr)
4601 {
4602         switch (expr->kind) {
4603                 case EXPR_CALL: {
4604                         expression_t const *const func = expr->call.function;
4605                         type_t       const *const type = skip_typeref(func->base.type);
4606                         if (type->kind == TYPE_POINTER) {
4607                                 type_t const *const points_to
4608                                         = skip_typeref(type->pointer.points_to);
4609                                 if (points_to->kind == TYPE_FUNCTION
4610                                     && points_to->function.modifiers & DM_NORETURN)
4611                                         return false;
4612                         }
4613
4614                         if (!expression_returns(func))
4615                                 return false;
4616
4617                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4618                                 if (!expression_returns(arg->expression))
4619                                         return false;
4620                         }
4621
4622                         return true;
4623                 }
4624
4625                 case EXPR_REFERENCE:
4626                 case EXPR_ENUM_CONSTANT:
4627                 case EXPR_LITERAL_CASES:
4628                 case EXPR_LITERAL_CHARACTER:
4629                 case EXPR_STRING_LITERAL:
4630                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4631                 case EXPR_LABEL_ADDRESS:
4632                 case EXPR_CLASSIFY_TYPE:
4633                 case EXPR_SIZEOF: // TODO handle obscure VLA case
4634                 case EXPR_ALIGNOF:
4635                 case EXPR_FUNCNAME:
4636                 case EXPR_BUILTIN_CONSTANT_P:
4637                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4638                 case EXPR_OFFSETOF:
4639                 case EXPR_ERROR:
4640                         return true;
4641
4642                 case EXPR_STATEMENT: {
4643                         bool old_reaches_end = reaches_end;
4644                         reaches_end = false;
4645                         check_reachable(expr->statement.statement);
4646                         bool returns = reaches_end;
4647                         reaches_end = old_reaches_end;
4648                         return returns;
4649                 }
4650
4651                 case EXPR_CONDITIONAL:
4652                         // TODO handle constant expression
4653
4654                         if (!expression_returns(expr->conditional.condition))
4655                                 return false;
4656
4657                         if (expr->conditional.true_expression != NULL
4658                                         && expression_returns(expr->conditional.true_expression))
4659                                 return true;
4660
4661                         return expression_returns(expr->conditional.false_expression);
4662
4663                 case EXPR_SELECT:
4664                         return expression_returns(expr->select.compound);
4665
4666                 case EXPR_ARRAY_ACCESS:
4667                         return
4668                                 expression_returns(expr->array_access.array_ref) &&
4669                                 expression_returns(expr->array_access.index);
4670
4671                 case EXPR_VA_START:
4672                         return expression_returns(expr->va_starte.ap);
4673
4674                 case EXPR_VA_ARG:
4675                         return expression_returns(expr->va_arge.ap);
4676
4677                 case EXPR_VA_COPY:
4678                         return expression_returns(expr->va_copye.src);
4679
4680                 case EXPR_UNARY_CASES_MANDATORY:
4681                         return expression_returns(expr->unary.value);
4682
4683                 case EXPR_UNARY_THROW:
4684                         return false;
4685
4686                 case EXPR_BINARY_CASES:
4687                         // TODO handle constant lhs of && and ||
4688                         return
4689                                 expression_returns(expr->binary.left) &&
4690                                 expression_returns(expr->binary.right);
4691         }
4692
4693         panic("unhandled expression");
4694 }
4695
4696 static bool initializer_returns(initializer_t const *const init)
4697 {
4698         switch (init->kind) {
4699                 case INITIALIZER_VALUE:
4700                         return expression_returns(init->value.value);
4701
4702                 case INITIALIZER_LIST: {
4703                         initializer_t * const*       i       = init->list.initializers;
4704                         initializer_t * const* const end     = i + init->list.len;
4705                         bool                         returns = true;
4706                         for (; i != end; ++i) {
4707                                 if (!initializer_returns(*i))
4708                                         returns = false;
4709                         }
4710                         return returns;
4711                 }
4712
4713                 case INITIALIZER_STRING:
4714                 case INITIALIZER_DESIGNATOR: // designators have no payload
4715                         return true;
4716         }
4717         panic("unhandled initializer");
4718 }
4719
4720 static bool noreturn_candidate;
4721
4722 static void check_reachable(statement_t *const stmt)
4723 {
4724         if (stmt->base.reachable)
4725                 return;
4726         if (stmt->kind != STATEMENT_DO_WHILE)
4727                 stmt->base.reachable = true;
4728
4729         statement_t *last = stmt;
4730         statement_t *next;
4731         switch (stmt->kind) {
4732                 case STATEMENT_ERROR:
4733                 case STATEMENT_EMPTY:
4734                 case STATEMENT_ASM:
4735                         next = stmt->base.next;
4736                         break;
4737
4738                 case STATEMENT_DECLARATION: {
4739                         declaration_statement_t const *const decl = &stmt->declaration;
4740                         entity_t                const *      ent  = decl->declarations_begin;
4741                         entity_t                const *const last_decl = decl->declarations_end;
4742                         if (ent != NULL) {
4743                                 for (;; ent = ent->base.next) {
4744                                         if (ent->kind                 == ENTITY_VARIABLE &&
4745                                             ent->variable.initializer != NULL            &&
4746                                             !initializer_returns(ent->variable.initializer)) {
4747                                                 return;
4748                                         }
4749                                         if (ent == last_decl)
4750                                                 break;
4751                                 }
4752                         }
4753                         next = stmt->base.next;
4754                         break;
4755                 }
4756
4757                 case STATEMENT_COMPOUND:
4758                         next = stmt->compound.statements;
4759                         if (next == NULL)
4760                                 next = stmt->base.next;
4761                         break;
4762
4763                 case STATEMENT_RETURN: {
4764                         expression_t const *const val = stmt->returns.value;
4765                         if (val == NULL || expression_returns(val))
4766                                 noreturn_candidate = false;
4767                         return;
4768                 }
4769
4770                 case STATEMENT_IF: {
4771                         if_statement_t const *const ifs  = &stmt->ifs;
4772                         expression_t   const *const cond = ifs->condition;
4773
4774                         if (!expression_returns(cond))
4775                                 return;
4776
4777                         int const val = determine_truth(cond);
4778
4779                         if (val >= 0)
4780                                 check_reachable(ifs->true_statement);
4781
4782                         if (val > 0)
4783                                 return;
4784
4785                         if (ifs->false_statement != NULL) {
4786                                 check_reachable(ifs->false_statement);
4787                                 return;
4788                         }
4789
4790                         next = stmt->base.next;
4791                         break;
4792                 }
4793
4794                 case STATEMENT_SWITCH: {
4795                         switch_statement_t const *const switchs = &stmt->switchs;
4796                         expression_t       const *const expr    = switchs->expression;
4797
4798                         if (!expression_returns(expr))
4799                                 return;
4800
4801                         if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4802                                 ir_tarval              *const val      = fold_constant_to_tarval(expr);
4803                                 case_label_statement_t *      defaults = NULL;
4804                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4805                                         if (i->expression == NULL) {
4806                                                 defaults = i;
4807                                                 continue;
4808                                         }
4809
4810                                         if (i->first_case == val || i->last_case == val ||
4811                                                 ((tarval_cmp(i->first_case, val) & ir_relation_less_equal)
4812                                             && (tarval_cmp(val, i->last_case) & ir_relation_less_equal))) {
4813                                                 check_reachable((statement_t*)i);
4814                                                 return;
4815                                         }
4816                                 }
4817
4818                                 if (defaults != NULL) {
4819                                         check_reachable((statement_t*)defaults);
4820                                         return;
4821                                 }
4822                         } else {
4823                                 bool has_default = false;
4824                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4825                                         if (i->expression == NULL)
4826                                                 has_default = true;
4827
4828                                         check_reachable((statement_t*)i);
4829                                 }
4830
4831                                 if (has_default)
4832                                         return;
4833                         }
4834
4835                         next = stmt->base.next;
4836                         break;
4837                 }
4838
4839                 case STATEMENT_EXPRESSION: {
4840                         /* Check for noreturn function call */
4841                         expression_t const *const expr = stmt->expression.expression;
4842                         if (!expression_returns(expr))
4843                                 return;
4844
4845                         next = stmt->base.next;
4846                         break;
4847                 }
4848
4849                 case STATEMENT_CONTINUE:
4850                         for (statement_t *parent = stmt;;) {
4851                                 parent = parent->base.parent;
4852                                 if (parent == NULL) /* continue not within loop */
4853                                         return;
4854
4855                                 next = parent;
4856                                 switch (parent->kind) {
4857                                         case STATEMENT_DO_WHILE: goto continue_do_while;
4858                                         case STATEMENT_FOR:      goto continue_for;
4859
4860                                         default: break;
4861                                 }
4862                         }
4863
4864                 case STATEMENT_BREAK:
4865                         for (statement_t *parent = stmt;;) {
4866                                 parent = parent->base.parent;
4867                                 if (parent == NULL) /* break not within loop/switch */
4868                                         return;
4869
4870                                 switch (parent->kind) {
4871                                         case STATEMENT_SWITCH:
4872                                         case STATEMENT_DO_WHILE:
4873                                         case STATEMENT_FOR:
4874                                                 last = parent;
4875                                                 next = parent->base.next;
4876                                                 goto found_break_parent;
4877
4878                                         default: break;
4879                                 }
4880                         }
4881 found_break_parent:
4882                         break;
4883
4884                 case STATEMENT_COMPUTED_GOTO: {
4885                         if (!expression_returns(stmt->computed_goto.expression))
4886                                 return;
4887
4888                         statement_t *parent = stmt->base.parent;
4889                         if (parent == NULL) /* top level goto */
4890                                 return;
4891                         next = parent;
4892                         break;
4893                 }
4894
4895                 case STATEMENT_GOTO:
4896                         next = stmt->gotos.label->statement;
4897                         if (next == NULL) /* missing label */
4898                                 return;
4899                         break;
4900
4901                 case STATEMENT_LABEL:
4902                         next = stmt->label.statement;
4903                         break;
4904
4905                 case STATEMENT_CASE_LABEL:
4906                         next = stmt->case_label.statement;
4907                         break;
4908
4909                 case STATEMENT_DO_WHILE:
4910                         next = stmt->do_while.body;
4911                         break;
4912
4913                 case STATEMENT_FOR: {
4914                         for_statement_t *const fors = &stmt->fors;
4915
4916                         if (fors->condition_reachable)
4917                                 return;
4918                         fors->condition_reachable = true;
4919
4920                         expression_t const *const cond = fors->condition;
4921
4922                         int val;
4923                         if (cond == NULL) {
4924                                 val = 1;
4925                         } else if (expression_returns(cond)) {
4926                                 val = determine_truth(cond);
4927                         } else {
4928                                 return;
4929                         }
4930
4931                         if (val >= 0)
4932                                 check_reachable(fors->body);
4933
4934                         if (val > 0)
4935                                 return;
4936
4937                         next = stmt->base.next;
4938                         break;
4939                 }
4940
4941                 case STATEMENT_MS_TRY: {
4942                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
4943                         check_reachable(ms_try->try_statement);
4944                         next = ms_try->final_statement;
4945                         break;
4946                 }
4947
4948                 case STATEMENT_LEAVE: {
4949                         statement_t *parent = stmt;
4950                         for (;;) {
4951                                 parent = parent->base.parent;
4952                                 if (parent == NULL) /* __leave not within __try */
4953                                         return;
4954
4955                                 if (parent->kind == STATEMENT_MS_TRY) {
4956                                         last = parent;
4957                                         next = parent->ms_try.final_statement;
4958                                         break;
4959                                 }
4960                         }
4961                         break;
4962                 }
4963
4964                 default:
4965                         panic("invalid statement kind");
4966         }
4967
4968         while (next == NULL) {
4969                 next = last->base.parent;
4970                 if (next == NULL) {
4971                         noreturn_candidate = false;
4972
4973                         type_t *const type = skip_typeref(current_function->base.type);
4974                         assert(is_type_function(type));
4975                         type_t *const ret  = skip_typeref(type->function.return_type);
4976                         if (!is_type_void(ret) &&
4977                             is_type_valid(ret) &&
4978                             !is_main(current_entity)) {
4979                                 position_t const *const pos = &stmt->base.pos;
4980                                 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4981                         }
4982                         return;
4983                 }
4984
4985                 switch (next->kind) {
4986                         case STATEMENT_ERROR:
4987                         case STATEMENT_EMPTY:
4988                         case STATEMENT_DECLARATION:
4989                         case STATEMENT_EXPRESSION:
4990                         case STATEMENT_ASM:
4991                         case STATEMENT_RETURN:
4992                         case STATEMENT_CONTINUE:
4993                         case STATEMENT_BREAK:
4994                         case STATEMENT_COMPUTED_GOTO:
4995                         case STATEMENT_GOTO:
4996                         case STATEMENT_LEAVE:
4997                                 panic("invalid control flow in function");
4998
4999                         case STATEMENT_COMPOUND:
5000                                 if (next->compound.stmt_expr) {
5001                                         reaches_end = true;
5002                                         return;
5003                                 }
5004                                 /* FALLTHROUGH */
5005                         case STATEMENT_IF:
5006                         case STATEMENT_SWITCH:
5007                         case STATEMENT_LABEL:
5008                         case STATEMENT_CASE_LABEL:
5009                                 last = next;
5010                                 next = next->base.next;
5011                                 break;
5012
5013                         case STATEMENT_DO_WHILE: {
5014 continue_do_while:
5015                                 if (next->base.reachable)
5016                                         return;
5017                                 next->base.reachable = true;
5018
5019                                 do_while_statement_t const *const dw   = &next->do_while;
5020                                 expression_t         const *const cond = dw->condition;
5021
5022                                 if (!expression_returns(cond))
5023                                         return;
5024
5025                                 int const val = determine_truth(cond);
5026
5027                                 if (val >= 0)
5028                                         check_reachable(dw->body);
5029
5030                                 if (val > 0)
5031                                         return;
5032
5033                                 last = next;
5034                                 next = next->base.next;
5035                                 break;
5036                         }
5037
5038                         case STATEMENT_FOR: {
5039 continue_for:;
5040                                 for_statement_t *const fors = &next->fors;
5041
5042                                 fors->step_reachable = true;
5043
5044                                 if (fors->condition_reachable)
5045                                         return;
5046                                 fors->condition_reachable = true;
5047
5048                                 expression_t const *const cond = fors->condition;
5049
5050                                 int val;
5051                                 if (cond == NULL) {
5052                                         val = 1;
5053                                 } else if (expression_returns(cond)) {
5054                                         val = determine_truth(cond);
5055                                 } else {
5056                                         return;
5057                                 }
5058
5059                                 if (val >= 0)
5060                                         check_reachable(fors->body);
5061
5062                                 if (val > 0)
5063                                         return;
5064
5065                                 last = next;
5066                                 next = next->base.next;
5067                                 break;
5068                         }
5069
5070                         case STATEMENT_MS_TRY:
5071                                 last = next;
5072                                 next = next->ms_try.final_statement;
5073                                 break;
5074                 }
5075         }
5076
5077         check_reachable(next);
5078 }
5079
5080 static void check_unreachable(statement_t* const stmt, void *const env)
5081 {
5082         (void)env;
5083
5084         switch (stmt->kind) {
5085                 case STATEMENT_DO_WHILE:
5086                         if (!stmt->base.reachable) {
5087                                 expression_t const *const cond = stmt->do_while.condition;
5088                                 if (determine_truth(cond) >= 0) {
5089                                         position_t const *const pos = &cond->base.pos;
5090                                         warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5091                                 }
5092                         }
5093                         return;
5094
5095                 case STATEMENT_FOR: {
5096                         for_statement_t const* const fors = &stmt->fors;
5097
5098                         // if init and step are unreachable, cond is unreachable, too
5099                         if (!stmt->base.reachable && !fors->step_reachable) {
5100                                 goto warn_unreachable;
5101                         } else {
5102                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
5103                                         position_t const *const pos = &fors->initialisation->base.pos;
5104                                         warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5105                                 }
5106
5107                                 if (!fors->condition_reachable && fors->condition != NULL) {
5108                                         position_t const *const pos = &fors->condition->base.pos;
5109                                         warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5110                                 }
5111
5112                                 if (!fors->step_reachable && fors->step != NULL) {
5113                                         position_t const *const pos = &fors->step->base.pos;
5114                                         warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5115                                 }
5116                         }
5117                         return;
5118                 }
5119
5120                 case STATEMENT_COMPOUND:
5121                         if (stmt->compound.statements != NULL)
5122                                 return;
5123                         goto warn_unreachable;
5124
5125                 case STATEMENT_DECLARATION: {
5126                         /* Only warn if there is at least one declarator with an initializer.
5127                          * This typically occurs in switch statements. */
5128                         declaration_statement_t const *const decl = &stmt->declaration;
5129                         entity_t                const *      ent  = decl->declarations_begin;
5130                         entity_t                const *const last = decl->declarations_end;
5131                         if (ent != NULL) {
5132                                 for (;; ent = ent->base.next) {
5133                                         if (ent->kind                 == ENTITY_VARIABLE &&
5134                                                         ent->variable.initializer != NULL) {
5135                                                 goto warn_unreachable;
5136                                         }
5137                                         if (ent == last)
5138                                                 return;
5139                                 }
5140                         }
5141                 }
5142
5143                 default:
5144 warn_unreachable:
5145                         if (!stmt->base.reachable) {
5146                                 position_t const *const pos = &stmt->base.pos;
5147                                 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5148                         }
5149                         return;
5150         }
5151 }
5152
5153 static bool is_main(entity_t *entity)
5154 {
5155         static symbol_t *sym_main = NULL;
5156         if (sym_main == NULL) {
5157                 sym_main = symbol_table_insert("main");
5158         }
5159
5160         if (entity->base.symbol != sym_main)
5161                 return false;
5162         /* must be in outermost scope */
5163         if (entity->base.parent_scope != file_scope)
5164                 return false;
5165
5166         return true;
5167 }
5168
5169 static void prepare_main_collect2(entity_t*);
5170
5171 static void parse_external_declaration(void)
5172 {
5173         /* function-definitions and declarations both start with declaration
5174          * specifiers */
5175         add_anchor_token(';');
5176         declaration_specifiers_t specifiers;
5177         parse_declaration_specifiers(&specifiers);
5178         rem_anchor_token(';');
5179
5180         /* must be a declaration */
5181         if (token.kind == ';') {
5182                 parse_anonymous_declaration_rest(&specifiers);
5183                 return;
5184         }
5185
5186         add_anchor_token(',');
5187         add_anchor_token('=');
5188         add_anchor_token(';');
5189         add_anchor_token('{');
5190
5191         /* declarator is common to both function-definitions and declarations */
5192         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5193
5194         rem_anchor_token('{');
5195         rem_anchor_token(';');
5196         rem_anchor_token('=');
5197         rem_anchor_token(',');
5198
5199         /* must be a declaration */
5200         switch (token.kind) {
5201                 case ',':
5202                 case ';':
5203                 case '=':
5204                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5205                                         DECL_FLAGS_NONE);
5206                         return;
5207         }
5208
5209         /* must be a function definition */
5210         parse_kr_declaration_list(ndeclaration);
5211
5212         if (token.kind != '{') {
5213                 parse_error_expected("while parsing function definition", '{', NULL);
5214                 eat_until_matching_token(';');
5215                 return;
5216         }
5217
5218         assert(is_declaration(ndeclaration));
5219         type_t *const orig_type = ndeclaration->declaration.type;
5220         type_t *      type      = skip_typeref(orig_type);
5221
5222         if (!is_type_function(type)) {
5223                 if (is_type_valid(type)) {
5224                         errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5225                 }
5226                 eat_block();
5227                 return;
5228         }
5229
5230         position_t const *const pos = &ndeclaration->base.pos;
5231         if (is_typeref(orig_type)) {
5232                 /* §6.9.1:2 */
5233                 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5234         }
5235
5236         if (is_type_compound(skip_typeref(type->function.return_type))) {
5237                 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5238         }
5239         if (type->function.unspecified_parameters) {
5240                 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5241         } else {
5242                 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5243         }
5244
5245         /* §6.7.5.3:14 a function definition with () means no
5246          * parameters (and not unspecified parameters) */
5247         if (type->function.unspecified_parameters &&
5248                         type->function.parameters == NULL) {
5249                 type_t *copy                          = duplicate_type(type);
5250                 copy->function.unspecified_parameters = false;
5251                 type                                  = identify_new_type(copy);
5252
5253                 ndeclaration->declaration.type = type;
5254         }
5255
5256         entity_t *const entity = record_entity(ndeclaration, true);
5257         assert(entity->kind == ENTITY_FUNCTION);
5258         assert(ndeclaration->kind == ENTITY_FUNCTION);
5259
5260         function_t *const function = &entity->function;
5261         if (ndeclaration != entity) {
5262                 function->parameters = ndeclaration->function.parameters;
5263         }
5264
5265         PUSH_SCOPE(&function->parameters);
5266
5267         entity_t *parameter = function->parameters.entities;
5268         for (; parameter != NULL; parameter = parameter->base.next) {
5269                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5270                         parameter->base.parent_scope = current_scope;
5271                 }
5272                 assert(parameter->base.parent_scope == NULL
5273                                 || parameter->base.parent_scope == current_scope);
5274                 parameter->base.parent_scope = current_scope;
5275                 if (parameter->base.symbol == NULL) {
5276                         errorf(&parameter->base.pos, "parameter name omitted");
5277                         continue;
5278                 }
5279                 environment_push(parameter);
5280         }
5281
5282         if (function->body != NULL) {
5283                 parser_error_multiple_definition(entity, HERE);
5284                 eat_block();
5285         } else {
5286                 /* parse function body */
5287                 int         label_stack_top      = label_top();
5288                 function_t *old_current_function = current_function;
5289                 current_function                 = function;
5290                 PUSH_CURRENT_ENTITY(entity);
5291                 PUSH_PARENT(NULL);
5292
5293                 goto_first   = NULL;
5294                 goto_anchor  = &goto_first;
5295                 label_first  = NULL;
5296                 label_anchor = &label_first;
5297
5298                 statement_t *const body = parse_compound_statement(false);
5299                 function->body = body;
5300                 first_err = true;
5301                 check_labels();
5302                 check_declarations();
5303                 if (is_warn_on(WARN_RETURN_TYPE)      ||
5304                     is_warn_on(WARN_UNREACHABLE_CODE) ||
5305                     (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5306                         noreturn_candidate = true;
5307                         check_reachable(body);
5308                         if (is_warn_on(WARN_UNREACHABLE_CODE))
5309                                 walk_statements(body, check_unreachable, NULL);
5310                         if (noreturn_candidate &&
5311                             !(function->base.modifiers & DM_NORETURN)) {
5312                                 position_t const *const pos = &body->base.pos;
5313                                 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5314                         }
5315                 }
5316
5317                 if (is_main(entity)) {
5318                         /* Force main to C linkage. */
5319                         type_t *const type = entity->declaration.type;
5320                         assert(is_type_function(type));
5321                         if (type->function.linkage != LINKAGE_C) {
5322                                 type_t *new_type           = duplicate_type(type);
5323                                 new_type->function.linkage = LINKAGE_C;
5324                                 entity->declaration.type   = identify_new_type(new_type);
5325                         }
5326
5327                         if (enable_main_collect2_hack)
5328                                 prepare_main_collect2(entity);
5329                 }
5330
5331                 POP_CURRENT_ENTITY();
5332                 POP_PARENT();
5333                 assert(current_function == function);
5334                 current_function = old_current_function;
5335                 label_pop_to(label_stack_top);
5336         }
5337
5338         POP_SCOPE();
5339 }
5340
5341 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5342 {
5343         entity_t *iter = compound->members.entities;
5344         for (; iter != NULL; iter = iter->base.next) {
5345                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5346                         continue;
5347
5348                 if (iter->base.symbol == symbol) {
5349                         return iter;
5350                 } else if (iter->base.symbol == NULL) {
5351                         /* search in anonymous structs and unions */
5352                         type_t *type = skip_typeref(iter->declaration.type);
5353                         if (is_type_compound(type)) {
5354                                 if (find_compound_entry(type->compound.compound, symbol)
5355                                                 != NULL)
5356                                         return iter;
5357                         }
5358                         continue;
5359                 }
5360         }
5361
5362         return NULL;
5363 }
5364
5365 static void check_deprecated(const position_t *pos, const entity_t *entity)
5366 {
5367         if (!is_declaration(entity))
5368                 return;
5369         if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5370                 return;
5371
5372         position_t const *const epos = &entity->base.pos;
5373         char       const *const msg  = get_deprecated_string(entity->declaration.attributes);
5374         if (msg != NULL) {
5375                 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5376         } else {
5377                 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P)", entity, epos);
5378         }
5379 }
5380
5381
5382 static expression_t *create_select(const position_t *pos, expression_t *addr,
5383                                    type_qualifiers_t qualifiers,
5384                                                                    entity_t *entry)
5385 {
5386         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5387
5388         check_deprecated(pos, entry);
5389
5390         expression_t *select          = allocate_expression_zero(EXPR_SELECT);
5391         select->select.compound       = addr;
5392         select->select.compound_entry = entry;
5393
5394         type_t *entry_type = entry->declaration.type;
5395         type_t *res_type   = get_qualified_type(entry_type, qualifiers);
5396
5397         /* bitfields need special treatment */
5398         if (entry->compound_member.bitfield) {
5399                 unsigned bit_size = entry->compound_member.bit_size;
5400                 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5401                 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5402                         res_type = type_int;
5403                 }
5404         }
5405
5406         /* we always do the auto-type conversions; the & and sizeof parser contains
5407          * code to revert this! */
5408         select->base.type = automatic_type_conversion(res_type);
5409
5410
5411         return select;
5412 }
5413
5414 /**
5415  * Find entry with symbol in compound. Search anonymous structs and unions and
5416  * creates implicit select expressions for them.
5417  * Returns the adress for the innermost compound.
5418  */
5419 static expression_t *find_create_select(const position_t *pos,
5420                                         expression_t *addr,
5421                                         type_qualifiers_t qualifiers,
5422                                         compound_t *compound, symbol_t *symbol)
5423 {
5424         entity_t *iter = compound->members.entities;
5425         for (; iter != NULL; iter = iter->base.next) {
5426                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5427                         continue;
5428
5429                 symbol_t *iter_symbol = iter->base.symbol;
5430                 if (iter_symbol == NULL) {
5431                         type_t *type = iter->declaration.type;
5432                         if (!is_type_compound(type))
5433                                 continue;
5434
5435                         compound_t *sub_compound = type->compound.compound;
5436
5437                         if (find_compound_entry(sub_compound, symbol) == NULL)
5438                                 continue;
5439
5440                         expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5441                         sub_addr->base.pos      = *pos;
5442                         sub_addr->base.implicit = true;
5443                         return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5444                                                   symbol);
5445                 }
5446
5447                 if (iter_symbol == symbol) {
5448                         return create_select(pos, addr, qualifiers, iter);
5449                 }
5450         }
5451
5452         return NULL;
5453 }
5454
5455 static void parse_bitfield_member(entity_t *entity)
5456 {
5457         eat(':');
5458
5459         expression_t *size = parse_constant_expression();
5460         long          size_long;
5461
5462         assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5463         type_t *type = entity->declaration.type;
5464         if (!is_type_integer(skip_typeref(type))) {
5465                 errorf(HERE, "bitfield base type '%T' is not an integer type",
5466                            type);
5467         }
5468
5469         if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5470                 /* error already reported by parse_constant_expression */
5471                 size_long = get_type_size(type) * 8;
5472         } else {
5473                 size_long = fold_constant_to_int(size);
5474
5475                 const symbol_t *symbol = entity->base.symbol;
5476                 const symbol_t *user_symbol
5477                         = symbol == NULL ? sym_anonymous : symbol;
5478                 unsigned bit_size = get_type_size(type) * 8;
5479                 if (size_long < 0) {
5480                         errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5481                 } else if (size_long == 0 && symbol != NULL) {
5482                         errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5483                 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5484                         errorf(HERE, "width of bitfield '%Y' exceeds its type",
5485                                    user_symbol);
5486                 } else {
5487                         /* hope that people don't invent crazy types with more bits
5488                          * than our struct can hold */
5489                         assert(size_long <
5490                                    (1 << sizeof(entity->compound_member.bit_size)*8));
5491                 }
5492         }
5493
5494         entity->compound_member.bitfield = true;
5495         entity->compound_member.bit_size = (unsigned char)size_long;
5496 }
5497
5498 static void parse_compound_declarators(compound_t *compound,
5499                 const declaration_specifiers_t *specifiers)
5500 {
5501         add_anchor_token(';');
5502         add_anchor_token(',');
5503         do {
5504                 entity_t *entity;
5505
5506                 if (token.kind == ':') {
5507                         /* anonymous bitfield */
5508                         type_t *type = specifiers->type;
5509                         entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5510                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5511                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
5512                         entity->declaration.type                   = type;
5513
5514                         parse_bitfield_member(entity);
5515
5516                         attribute_t  *attributes = parse_attributes(NULL);
5517                         attribute_t **anchor     = &attributes;
5518                         while (*anchor != NULL)
5519                                 anchor = &(*anchor)->next;
5520                         *anchor = specifiers->attributes;
5521                         if (attributes != NULL) {
5522                                 handle_entity_attributes(attributes, entity);
5523                         }
5524                         entity->declaration.attributes = attributes;
5525
5526                         append_entity(&compound->members, entity);
5527                 } else {
5528                         entity = parse_declarator(specifiers,
5529                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5530                         position_t const *const pos = &entity->base.pos;
5531                         if (entity->kind == ENTITY_TYPEDEF) {
5532                                 errorf(pos, "typedef not allowed as compound member");
5533                         } else {
5534                                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5535
5536                                 /* make sure we don't define a symbol multiple times */
5537                                 symbol_t *symbol = entity->base.symbol;
5538                                 if (symbol != NULL) {
5539                                         entity_t *prev = find_compound_entry(compound, symbol);
5540                                         if (prev != NULL) {
5541                                                 position_t const *const ppos = &prev->base.pos;
5542                                                 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5543                                         }
5544                                 }
5545
5546                                 if (token.kind == ':') {
5547                                         parse_bitfield_member(entity);
5548
5549                                         attribute_t *attributes = parse_attributes(NULL);
5550                                         handle_entity_attributes(attributes, entity);
5551                                 } else {
5552                                         type_t *orig_type = entity->declaration.type;
5553                                         type_t *type      = skip_typeref(orig_type);
5554                                         if (is_type_function(type)) {
5555                                                 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5556                                         } else if (is_type_incomplete(type)) {
5557                                                 /* §6.7.2.1:16 flexible array member */
5558                                                 if (!is_type_array(type)       ||
5559                                                                 token.kind          != ';' ||
5560                                                                 look_ahead(1)->kind != '}') {
5561                                                         errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5562                                                 } else if (compound->members.entities == NULL) {
5563                                                         errorf(pos, "flexible array member in otherwise empty struct");
5564                                                 }
5565                                         }
5566                                 }
5567
5568                                 append_entity(&compound->members, entity);
5569                         }
5570                 }
5571         } while (accept(','));
5572         rem_anchor_token(',');
5573         rem_anchor_token(';');
5574         expect(';');
5575
5576         anonymous_entity = NULL;
5577 }
5578
5579 static void parse_compound_type_entries(compound_t *compound)
5580 {
5581         eat('{');
5582         add_anchor_token('}');
5583
5584         for (;;) {
5585                 switch (token.kind) {
5586                         DECLARATION_START
5587                         case T___extension__:
5588                         case T_IDENTIFIER: {
5589                                 PUSH_EXTENSION();
5590                                 declaration_specifiers_t specifiers;
5591                                 parse_declaration_specifiers(&specifiers);
5592                                 parse_compound_declarators(compound, &specifiers);
5593                                 POP_EXTENSION();
5594                                 break;
5595                         }
5596
5597                         default:
5598                                 rem_anchor_token('}');
5599                                 expect('}');
5600                                 /* §6.7.2.1:7 */
5601                                 compound->complete = true;
5602                                 return;
5603                 }
5604         }
5605 }
5606
5607 static type_t *parse_typename(void)
5608 {
5609         declaration_specifiers_t specifiers;
5610         parse_declaration_specifiers(&specifiers);
5611         if (specifiers.storage_class != STORAGE_CLASS_NONE
5612                         || specifiers.thread_local) {
5613                 /* TODO: improve error message, user does probably not know what a
5614                  * storage class is...
5615                  */
5616                 errorf(&specifiers.pos, "typename must not have a storage class");
5617         }
5618
5619         type_t *result = parse_abstract_declarator(specifiers.type);
5620
5621         return result;
5622 }
5623
5624
5625
5626
5627 typedef expression_t* (*parse_expression_function)(void);
5628 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5629
5630 typedef struct expression_parser_function_t expression_parser_function_t;
5631 struct expression_parser_function_t {
5632         parse_expression_function        parser;
5633         precedence_t                     infix_precedence;
5634         parse_expression_infix_function  infix_parser;
5635 };
5636
5637 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5638
5639 static type_t *get_string_type(string_encoding_t const enc)
5640 {
5641         bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5642         switch (enc) {
5643         case STRING_ENCODING_CHAR:
5644         case STRING_ENCODING_UTF8:   return warn ? type_const_char_ptr     : type_char_ptr;
5645         case STRING_ENCODING_CHAR16: return warn ? type_char16_t_const_ptr : type_char16_t_ptr;
5646         case STRING_ENCODING_CHAR32: return warn ? type_char32_t_const_ptr : type_char32_t_ptr;
5647         case STRING_ENCODING_WIDE:   return warn ? type_const_wchar_t_ptr  : type_wchar_t_ptr;
5648         }
5649         panic("invalid string encoding");
5650 }
5651
5652 /**
5653  * Parse a string constant.
5654  */
5655 static expression_t *parse_string_literal(void)
5656 {
5657         expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5658         expr->string_literal.value = concat_string_literals();
5659         expr->base.type            = get_string_type(expr->string_literal.value.encoding);
5660         return expr;
5661 }
5662
5663 /**
5664  * Parse a boolean constant.
5665  */
5666 static expression_t *parse_boolean_literal(bool value)
5667 {
5668         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5669         literal->base.type           = type_bool;
5670         literal->literal.value.begin = value ? "true" : "false";
5671         literal->literal.value.size  = value ? 4 : 5;
5672
5673         eat(value ? T_true : T_false);
5674         return literal;
5675 }
5676
5677 static void warn_traditional_suffix(char const *const suffix)
5678 {
5679         warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5680 }
5681
5682 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5683 {
5684         unsigned     spec = SPECIFIER_NONE;
5685         char const  *c    = suffix;
5686         while (*c != '\0') {
5687                 specifiers_t add;
5688                 switch (*c) {
5689                 case 'L':
5690                 case 'l':
5691                         add = SPECIFIER_LONG;
5692                         if (*c == c[1]) {
5693                                 add |= SPECIFIER_LONG_LONG;
5694                                 ++c;
5695                         }
5696                         break;
5697                 case 'u':
5698                 case 'U':
5699                         add = SPECIFIER_UNSIGNED;
5700                         break;
5701                 case 'i':
5702                 case 'I':
5703                 case 'j':
5704                 case 'J':
5705                         if (!GNU_MODE)
5706                                 goto error;
5707                         add = SPECIFIER_COMPLEX;
5708                         break;
5709
5710                 default:
5711                         goto error;
5712                 }
5713                 ++c;
5714                 if (spec & add)
5715                         goto error;
5716                 spec |= add;
5717         }
5718
5719         if (*c == '\0') {
5720                 type_t *type;
5721                 switch (spec & ~SPECIFIER_COMPLEX) {
5722                 case SPECIFIER_NONE:                                            type = type_int;                break;
5723                 case                      SPECIFIER_LONG:                       type = type_long;               break;
5724                 case                      SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long;          break;
5725                 case SPECIFIER_UNSIGNED:                                        type = type_unsigned_int;       break;
5726                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:                       type = type_unsigned_long;      break;
5727                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5728                 default: panic("inconsistent suffix");
5729                 }
5730                 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5731                         warn_traditional_suffix(suffix);
5732                 }
5733                 if (spec & SPECIFIER_COMPLEX) {
5734                         assert(type->kind == TYPE_ATOMIC);
5735                         type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5736                 }
5737                 expr->base.type = type;
5738                 /* Integer type depends on the size of the number and the size
5739                  * representable by the types. The backend/codegeneration has to
5740                  * determine that. */
5741                 determine_literal_type(&expr->literal);
5742         } else {
5743 error:
5744                 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5745         }
5746 }
5747
5748 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5749 {
5750         type_t     *type;
5751         char const *c          = suffix;
5752         bool        is_complex = false;
5753 next:
5754         switch (*c) {
5755         case 'F':
5756         case 'f': type = type_float;       ++c; break;
5757         case 'L':
5758         case 'l': type = type_long_double; ++c; break;
5759         case 'i':
5760         case 'I':
5761         case 'j':
5762         case 'J':
5763                 if (!GNU_MODE)
5764                         break;
5765                 is_complex = true;
5766                 ++c;
5767                 goto next;
5768         default:  type = type_double;           break;
5769         }
5770
5771         if (*c == '\0') {
5772                 if (is_complex) {
5773                         assert(type->kind == TYPE_ATOMIC);
5774                         type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5775                 }
5776
5777                 expr->base.type = type;
5778                 if (suffix[0] != '\0') {
5779                         warn_traditional_suffix(suffix);
5780                 }
5781         } else {
5782                 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5783         }
5784 }
5785
5786 static expression_t *parse_number_literal(void)
5787 {
5788         string_t const *const str      = &token.literal.string;
5789         char     const *      i        = str->begin;
5790         unsigned              digits   = 0;
5791         bool                  is_float = false;
5792
5793         /* Parse base prefix. */
5794         unsigned base;
5795         if (*i == '0') {
5796                 switch (*++i) {
5797                 case 'B': case 'b': base =  2; ++i;               break;
5798                 case 'X': case 'x': base = 16; ++i;               break;
5799                 default:            base =  8; digits |= 1U << 0; break;
5800                 }
5801         } else {
5802                 base = 10;
5803         }
5804
5805         /* Parse mantissa. */
5806         for (;; ++i) {
5807                 unsigned digit;
5808                 switch (*i) {
5809                 case '.':
5810                         if (is_float) {
5811                                 errorf(HERE, "multiple decimal points in %K", &token);
5812                                 i = 0;
5813                                 goto done;
5814                         }
5815                         is_float = true;
5816                         if (base == 8)
5817                                 base = 10;
5818                         continue;
5819
5820                 case '0':           digit =  0; break;
5821                 case '1':           digit =  1; break;
5822                 case '2':           digit =  2; break;
5823                 case '3':           digit =  3; break;
5824                 case '4':           digit =  4; break;
5825                 case '5':           digit =  5; break;
5826                 case '6':           digit =  6; break;
5827                 case '7':           digit =  7; break;
5828                 case '8':           digit =  8; break;
5829                 case '9':           digit =  9; break;
5830                 case 'A': case 'a': digit = 10; break;
5831                 case 'B': case 'b': digit = 11; break;
5832                 case 'C': case 'c': digit = 12; break;
5833                 case 'D': case 'd': digit = 13; break;
5834                 case 'E': case 'e': digit = 14; break;
5835                 case 'F': case 'f': digit = 15; break;
5836
5837                 default: goto done_mantissa;
5838                 }
5839
5840                 if (digit >= 10 && base != 16)
5841                         goto done_mantissa;
5842
5843                 digits |= 1U << digit;
5844         }
5845 done_mantissa:
5846
5847         /* Parse exponent. */
5848         switch (base) {
5849         case 2:
5850                 if (is_float)
5851                         errorf(HERE, "binary floating %K not allowed", &token);
5852                 break;
5853
5854         case  8:
5855         case 10:
5856                 if (*i == 'E' || *i == 'e') {
5857                         base = 10;
5858                         goto parse_exponent;
5859                 }
5860                 break;
5861
5862         case 16:
5863                 if (*i == 'P' || *i == 'p') {
5864 parse_exponent:
5865                         ++i;
5866                         is_float = true;
5867
5868                         if (*i == '-' || *i == '+')
5869                                 ++i;
5870
5871                         if (isdigit(*i)) {
5872                                 do {
5873                                         ++i;
5874                                 } while (isdigit(*i));
5875                         } else {
5876                                 errorf(HERE, "exponent of %K has no digits", &token);
5877                         }
5878                 } else if (is_float) {
5879                         errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5880                         i = 0;
5881                 }
5882                 break;
5883
5884         default:
5885                 panic("invalid base");
5886         }
5887
5888 done:;
5889         expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5890         expr->literal.value = *str;
5891
5892         if (i) {
5893                 if (digits == 0) {
5894                         errorf(HERE, "%K has no digits", &token);
5895                 } else if (digits & ~((1U << base) - 1)) {
5896                         errorf(HERE, "invalid digit in %K", &token);
5897                 } else {
5898                         expr->literal.suffix = i;
5899                         if (is_float) {
5900                                 check_floatingpoint_suffix(expr, i);
5901                         } else {
5902                                 check_integer_suffix(expr, i);
5903                         }
5904                 }
5905         }
5906
5907         eat(T_NUMBER);
5908         return expr;
5909 }
5910
5911 /**
5912  * Parse a character constant.
5913  */
5914 static expression_t *parse_character_constant(void)
5915 {
5916         expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5917         literal->string_literal.value = token.literal.string;
5918
5919         size_t const size = get_string_len(&token.literal.string);
5920         switch (token.literal.string.encoding) {
5921         case STRING_ENCODING_CHAR:
5922         case STRING_ENCODING_UTF8:
5923                 literal->base.type = c_mode & _CXX ? type_char : type_int;
5924                 if (size > 1) {
5925                         if (!GNU_MODE && !(c_mode & _C99)) {
5926                                 errorf(HERE, "more than 1 character in character constant");
5927                         } else {
5928                                 literal->base.type = type_int;
5929                                 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5930                         }
5931                 }
5932                 break;
5933
5934         case STRING_ENCODING_CHAR16: literal->base.type = type_char16_t; goto warn_multi;
5935         case STRING_ENCODING_CHAR32: literal->base.type = type_char32_t; goto warn_multi;
5936         case STRING_ENCODING_WIDE:   literal->base.type = type_wchar_t;  goto warn_multi;
5937 warn_multi:
5938                 if (size > 1) {
5939                         warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5940                 }
5941                 break;
5942         }
5943
5944         eat(T_CHARACTER_CONSTANT);
5945         return literal;
5946 }
5947
5948 static entity_t *create_implicit_function(symbol_t *symbol, position_t const *const pos)
5949 {
5950         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
5951         ntype->function.return_type            = type_int;
5952         ntype->function.unspecified_parameters = true;
5953         ntype->function.linkage                = LINKAGE_C;
5954         type_t *type                           = identify_new_type(ntype);
5955
5956         entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5957         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
5958         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5959         entity->declaration.type                   = type;
5960         entity->declaration.implicit               = true;
5961
5962         if (current_scope != NULL)
5963                 record_entity(entity, false);
5964
5965         return entity;
5966 }
5967
5968 /**
5969  * Performs automatic type cast as described in §6.3.2.1.
5970  *
5971  * @param orig_type  the original type
5972  */
5973 static type_t *automatic_type_conversion(type_t *orig_type)
5974 {
5975         type_t *type = skip_typeref(orig_type);
5976         if (is_type_array(type)) {
5977                 array_type_t *array_type   = &type->array;
5978                 type_t       *element_type = array_type->element_type;
5979                 unsigned      qualifiers   = array_type->base.qualifiers;
5980
5981                 return make_pointer_type(element_type, qualifiers);
5982         }
5983
5984         if (is_type_function(type)) {
5985                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5986         }
5987
5988         return orig_type;
5989 }
5990
5991 /**
5992  * reverts the automatic casts of array to pointer types and function
5993  * to function-pointer types as defined §6.3.2.1
5994  */
5995 type_t *revert_automatic_type_conversion(const expression_t *expression)
5996 {
5997         switch (expression->kind) {
5998         case EXPR_REFERENCE: {
5999                 entity_t *entity = expression->reference.entity;
6000                 if (is_declaration(entity)) {
6001                         return entity->declaration.type;
6002                 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6003                         return entity->enum_value.enum_type;
6004                 } else {
6005                         panic("no declaration or enum in reference");
6006                 }
6007         }
6008
6009         case EXPR_SELECT: {
6010                 entity_t *entity = expression->select.compound_entry;
6011                 assert(is_declaration(entity));
6012                 type_t   *type   = entity->declaration.type;
6013                 return get_qualified_type(type, expression->base.type->base.qualifiers);
6014         }
6015
6016         case EXPR_UNARY_DEREFERENCE: {
6017                 const expression_t *const value = expression->unary.value;
6018                 type_t             *const type  = skip_typeref(value->base.type);
6019                 if (!is_type_pointer(type))
6020                         return type_error_type;
6021                 return type->pointer.points_to;
6022         }
6023
6024         case EXPR_ARRAY_ACCESS: {
6025                 const expression_t *array_ref = expression->array_access.array_ref;
6026                 type_t             *type_left = skip_typeref(array_ref->base.type);
6027                 if (!is_type_pointer(type_left))
6028                         return type_error_type;
6029                 return type_left->pointer.points_to;
6030         }
6031
6032         case EXPR_STRING_LITERAL: {
6033                 size_t  const size = get_string_len(&expression->string_literal.value) + 1;
6034                 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6035                 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6036         }
6037
6038         case EXPR_COMPOUND_LITERAL:
6039                 return expression->compound_literal.type;
6040
6041         default:
6042                 break;
6043         }
6044         return expression->base.type;
6045 }
6046
6047 /**
6048  * Find an entity matching a symbol in a scope.
6049  * Uses current scope if scope is NULL
6050  */
6051 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6052                                namespace_tag_t namespc)
6053 {
6054         if (scope == NULL) {
6055                 return get_entity(symbol, namespc);
6056         }
6057
6058         /* we should optimize here, if scope grows above a certain size we should
6059            construct a hashmap here... */
6060         entity_t *entity = scope->entities;
6061         for ( ; entity != NULL; entity = entity->base.next) {
6062                 if (entity->base.symbol == symbol
6063                     && (namespace_tag_t)entity->base.namespc == namespc)
6064                         break;
6065         }
6066
6067         return entity;
6068 }
6069
6070 static entity_t *parse_qualified_identifier(void)
6071 {
6072         /* namespace containing the symbol */
6073         symbol_t      *symbol;
6074         position_t     pos;
6075         const scope_t *lookup_scope = NULL;
6076
6077         if (accept(T_COLONCOLON))
6078                 lookup_scope = &unit->scope;
6079
6080         entity_t *entity;
6081         while (true) {
6082                 symbol = expect_identifier("while parsing identifier", &pos);
6083                 if (!symbol)
6084                         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6085
6086                 /* lookup entity */
6087                 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6088
6089                 if (!accept(T_COLONCOLON))
6090                         break;
6091
6092                 switch (entity->kind) {
6093                 case ENTITY_NAMESPACE:
6094                         lookup_scope = &entity->namespacee.members;
6095                         break;
6096                 case ENTITY_STRUCT:
6097                 case ENTITY_UNION:
6098                 case ENTITY_CLASS:
6099                         lookup_scope = &entity->compound.members;
6100                         break;
6101                 default:
6102                         errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6103                                symbol, get_entity_kind_name(entity->kind));
6104
6105                         /* skip further qualifications */
6106                         while (accept(T_IDENTIFIER) && accept(T_COLONCOLON)) {}
6107
6108                         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6109                 }
6110         }
6111
6112         if (entity == NULL) {
6113                 if (!strict_mode && token.kind == '(') {
6114                         /* an implicitly declared function */
6115                         entity = create_implicit_function(symbol, &pos);
6116                         warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6117                 } else {
6118                         errorf(&pos, "unknown identifier '%Y' found.", symbol);
6119                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
6120                 }
6121         }
6122
6123         return entity;
6124 }
6125
6126 static expression_t *parse_reference(void)
6127 {
6128         position_t const pos    = *HERE;
6129         entity_t  *const entity = parse_qualified_identifier();
6130
6131         type_t *orig_type;
6132         if (is_declaration(entity)) {
6133                 orig_type = entity->declaration.type;
6134         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6135                 orig_type = entity->enum_value.enum_type;
6136         } else {
6137                 panic("expected declaration or enum value in reference");
6138         }
6139
6140         /* we always do the auto-type conversions; the & and sizeof parser contains
6141          * code to revert this! */
6142         type_t *type = automatic_type_conversion(orig_type);
6143
6144         expression_kind_t kind = EXPR_REFERENCE;
6145         if (entity->kind == ENTITY_ENUM_VALUE)
6146                 kind = EXPR_ENUM_CONSTANT;
6147
6148         expression_t *expression     = allocate_expression_zero(kind);
6149         expression->base.pos         = pos;
6150         expression->base.type        = type;
6151         expression->reference.entity = entity;
6152
6153         /* this declaration is used */
6154         if (is_declaration(entity)) {
6155                 entity->declaration.used = true;
6156         }
6157
6158         if (entity->base.parent_scope != file_scope
6159                 && (current_function != NULL
6160                         && entity->base.parent_scope->depth < current_function->parameters.depth)
6161                 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6162                 /* access of a variable from an outer function */
6163                 entity->variable.address_taken = true;
6164                 current_function->need_closure = true;
6165         }
6166
6167         check_deprecated(&pos, entity);
6168
6169         return expression;
6170 }
6171
6172 static bool semantic_cast(expression_t *cast)
6173 {
6174         expression_t     *expression      = cast->unary.value;
6175         type_t           *orig_dest_type  = cast->base.type;
6176         type_t           *orig_type_right = expression->base.type;
6177         type_t     const *dst_type        = skip_typeref(orig_dest_type);
6178         type_t     const *src_type        = skip_typeref(orig_type_right);
6179         position_t const *pos             = &cast->base.pos;
6180
6181         /* §6.5.4 A (void) cast is explicitly permitted, more for documentation
6182          * than for utility. */
6183         if (is_type_void(dst_type))
6184                 return true;
6185
6186         /* only integer and pointer can be casted to pointer */
6187         if (is_type_pointer(dst_type)  &&
6188             !is_type_pointer(src_type) &&
6189             !is_type_integer(src_type) &&
6190             is_type_valid(src_type)) {
6191                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6192                 return false;
6193         }
6194
6195         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6196                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6197                 return false;
6198         }
6199
6200         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6201                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6202                 return false;
6203         }
6204
6205         if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6206                 type_t *src = skip_typeref(src_type->pointer.points_to);
6207                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6208                 unsigned missing_qualifiers =
6209                         src->base.qualifiers & ~dst->base.qualifiers;
6210                 if (missing_qualifiers != 0) {
6211                         warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6212                 }
6213         }
6214         return true;
6215 }
6216
6217 static void semantic_complex_extract(unary_expression_t *extract)
6218 {
6219         type_t *orig_value_type = extract->value->base.type;
6220         type_t *value_type      = skip_typeref(orig_value_type);
6221         if (!is_type_valid(value_type)) {
6222                 extract->base.type = type_error_type;
6223                 return;
6224         }
6225
6226         type_t *type = value_type;
6227         if (!is_type_complex(type)) {
6228                 if (!is_type_arithmetic(type)) {
6229                         errorf(&extract->base.pos,
6230                                    "%s requires an argument with complex or arithmetic type, got '%T'",
6231                                    extract->base.kind == EXPR_UNARY_IMAG ? "__imag__" : "__real__",
6232                                    orig_value_type);
6233                         extract->base.type = type_error_type;
6234                         return;
6235                 }
6236                 atomic_type_kind_t const akind = get_arithmetic_akind(type);
6237                 type = make_complex_type(akind, TYPE_QUALIFIER_NONE);
6238                 extract->value = create_implicit_cast(extract->value, type);
6239         }
6240         assert(type->kind == TYPE_COMPLEX);
6241         type = make_atomic_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
6242         extract->base.type = type;
6243 }
6244
6245 static expression_t *parse_compound_literal(position_t const *const pos,
6246                                             type_t *type)
6247 {
6248         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6249         expression->base.pos = *pos;
6250         bool global_scope = current_scope == file_scope;
6251
6252         parse_initializer_env_t env;
6253         env.type             = type;
6254         env.entity           = NULL;
6255         env.must_be_constant = global_scope;
6256         initializer_t *initializer = parse_initializer(&env);
6257         type = env.type;
6258
6259         expression->base.type                     = automatic_type_conversion(type);
6260         expression->compound_literal.initializer  = initializer;
6261         expression->compound_literal.type         = type;
6262         expression->compound_literal.global_scope = global_scope;
6263
6264         return expression;
6265 }
6266
6267 /**
6268  * Parse a cast expression.
6269  */
6270 static expression_t *parse_cast(void)
6271 {
6272         position_t const pos = *HERE;
6273
6274         eat('(');
6275         add_anchor_token(')');
6276
6277         type_t *type = parse_typename();
6278
6279         rem_anchor_token(')');
6280         expect(')');
6281
6282         if (token.kind == '{') {
6283                 return parse_compound_literal(&pos, type);
6284         }
6285
6286         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6287         cast->base.pos     = pos;
6288
6289         expression_t *value = parse_subexpression(PREC_CAST);
6290         cast->base.type   = type;
6291         cast->unary.value = value;
6292
6293         if (!semantic_cast(cast)) {
6294                 cast->base.type = type_error_type;
6295         }
6296
6297         return cast;
6298 }
6299
6300 static expression_t *parse_complex_extract_expression(expression_kind_t const kind)
6301 {
6302         expression_t *extract = allocate_expression_zero(kind);
6303         next_token();
6304
6305         extract->unary.value = parse_subexpression(PREC_CAST);
6306         semantic_complex_extract(&extract->unary);
6307         return extract;
6308 }
6309
6310 /**
6311  * Parse a statement expression.
6312  */
6313 static expression_t *parse_statement_expression(void)
6314 {
6315         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6316
6317         eat('(');
6318         add_anchor_token(')');
6319
6320         statement_t *statement          = parse_compound_statement(true);
6321         statement->compound.stmt_expr   = true;
6322         expression->statement.statement = statement;
6323
6324         /* find last statement and use its type */
6325         type_t *type = type_void;
6326         const statement_t *stmt = statement->compound.statements;
6327         if (stmt != NULL) {
6328                 while (stmt->base.next != NULL)
6329                         stmt = stmt->base.next;
6330
6331                 if (stmt->kind == STATEMENT_EXPRESSION) {
6332                         type = stmt->expression.expression->base.type;
6333                 }
6334         } else {
6335                 position_t const *const pos = &expression->base.pos;
6336                 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6337         }
6338         expression->base.type = type;
6339
6340         rem_anchor_token(')');
6341         expect(')');
6342         return expression;
6343 }
6344
6345 /**
6346  * Parse a parenthesized expression.
6347  */
6348 static expression_t *parse_parenthesized_expression(void)
6349 {
6350         token_t const* const la1 = look_ahead(1);
6351         switch (la1->kind) {
6352         case '{':
6353                 /* gcc extension: a statement expression */
6354                 return parse_statement_expression();
6355
6356         case T_IDENTIFIER:
6357                 if (is_typedef_symbol(la1->base.symbol)) {
6358         DECLARATION_START
6359                         return parse_cast();
6360                 }
6361         }
6362
6363         eat('(');
6364         add_anchor_token(')');
6365         expression_t *result = parse_expression();
6366         result->base.parenthesized = true;
6367         rem_anchor_token(')');
6368         expect(')');
6369
6370         return result;
6371 }
6372
6373 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6374 {
6375         if (current_function == NULL) {
6376                 errorf(HERE, "%K used outside of a function", &token);
6377         }
6378
6379         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6380         expression->base.type     = type_char_ptr;
6381         expression->funcname.kind = kind;
6382
6383         next_token();
6384
6385         return expression;
6386 }
6387
6388 static designator_t *parse_designator(void)
6389 {
6390         designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6391         result->symbol = expect_identifier("while parsing member designator", &result->pos);
6392         if (!result->symbol)
6393                 return NULL;
6394
6395         designator_t *last_designator = result;
6396         while (true) {
6397                 if (accept('.')) {
6398                         designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6399                         designator->symbol = expect_identifier("while parsing member designator", &designator->pos);
6400                         if (!designator->symbol)
6401                                 return NULL;
6402
6403                         last_designator->next = designator;
6404                         last_designator       = designator;
6405                         continue;
6406                 }
6407                 if (accept('[')) {
6408                         add_anchor_token(']');
6409                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6410                         designator->pos          = *HERE;
6411                         designator->array_index  = parse_expression();
6412                         rem_anchor_token(']');
6413                         expect(']');
6414
6415                         last_designator->next = designator;
6416                         last_designator       = designator;
6417                         continue;
6418                 }
6419                 break;
6420         }
6421
6422         return result;
6423 }
6424
6425 /**
6426  * Parse the __builtin_offsetof() expression.
6427  */
6428 static expression_t *parse_offsetof(void)
6429 {
6430         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6431         expression->base.type    = type_size_t;
6432
6433         eat(T___builtin_offsetof);
6434
6435         add_anchor_token(')');
6436         add_anchor_token(',');
6437         expect('(');
6438         type_t *type = parse_typename();
6439         rem_anchor_token(',');
6440         expect(',');
6441         designator_t *designator = parse_designator();
6442         rem_anchor_token(')');
6443         expect(')');
6444
6445         expression->offsetofe.type       = type;
6446         expression->offsetofe.designator = designator;
6447
6448         type_path_t path;
6449         memset(&path, 0, sizeof(path));
6450         path.top_type = type;
6451         path.path     = NEW_ARR_F(type_path_entry_t, 0);
6452
6453         descend_into_subtype(&path);
6454
6455         if (!walk_designator(&path, designator, true)) {
6456                 return create_error_expression();
6457         }
6458
6459         DEL_ARR_F(path.path);
6460
6461         return expression;
6462 }
6463
6464 static bool is_last_parameter(expression_t *const param)
6465 {
6466         if (param->kind == EXPR_REFERENCE) {
6467                 entity_t *const entity = param->reference.entity;
6468                 if (entity->kind == ENTITY_PARAMETER &&
6469                     !entity->base.next               &&
6470                     entity->base.parent_scope == &current_function->parameters) {
6471                         return true;
6472                 }
6473         }
6474
6475         if (!is_type_valid(skip_typeref(param->base.type)))
6476                 return true;
6477
6478         return false;
6479 }
6480
6481 /**
6482  * Parses a __builtin_va_start() expression.
6483  */
6484 static expression_t *parse_va_start(void)
6485 {
6486         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6487
6488         eat(T___builtin_va_start);
6489
6490         add_anchor_token(')');
6491         add_anchor_token(',');
6492         expect('(');
6493         expression->va_starte.ap = parse_assignment_expression();
6494         rem_anchor_token(',');
6495         expect(',');
6496         expression_t *const param = parse_assignment_expression();
6497         expression->va_starte.parameter = param;
6498         rem_anchor_token(')');
6499         expect(')');
6500
6501         if (!current_function) {
6502                 errorf(&expression->base.pos, "'va_start' used outside of function");
6503         } else if (!current_function->base.type->function.variadic) {
6504                 errorf(&expression->base.pos, "'va_start' used in non-variadic function");
6505         } else if (!is_last_parameter(param)) {
6506                 errorf(&param->base.pos, "second argument of 'va_start' must be last parameter of the current function");
6507         }
6508
6509         return expression;
6510 }
6511
6512 /**
6513  * Parses a __builtin_va_arg() expression.
6514  */
6515 static expression_t *parse_va_arg(void)
6516 {
6517         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6518
6519         eat(T___builtin_va_arg);
6520
6521         add_anchor_token(')');
6522         add_anchor_token(',');
6523         expect('(');
6524         call_argument_t ap;
6525         ap.expression = parse_assignment_expression();
6526         expression->va_arge.ap = ap.expression;
6527         check_call_argument(type_valist, &ap, 1);
6528
6529         rem_anchor_token(',');
6530         expect(',');
6531         expression->base.type = parse_typename();
6532         rem_anchor_token(')');
6533         expect(')');
6534
6535         return expression;
6536 }
6537
6538 /**
6539  * Parses a __builtin_va_copy() expression.
6540  */
6541 static expression_t *parse_va_copy(void)
6542 {
6543         expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6544
6545         eat(T___builtin_va_copy);
6546
6547         add_anchor_token(')');
6548         add_anchor_token(',');
6549         expect('(');
6550         expression_t *dst = parse_assignment_expression();
6551         assign_error_t error = semantic_assign(type_valist, dst);
6552         report_assign_error(error, type_valist, dst, "call argument 1",
6553                             &dst->base.pos);
6554         expression->va_copye.dst = dst;
6555
6556         rem_anchor_token(',');
6557         expect(',');
6558
6559         call_argument_t src;
6560         src.expression = parse_assignment_expression();
6561         check_call_argument(type_valist, &src, 2);
6562         expression->va_copye.src = src.expression;
6563         rem_anchor_token(')');
6564         expect(')');
6565
6566         return expression;
6567 }
6568
6569 /**
6570  * Parses a __builtin_constant_p() expression.
6571  */
6572 static expression_t *parse_builtin_constant(void)
6573 {
6574         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6575
6576         eat(T___builtin_constant_p);
6577
6578         add_anchor_token(')');
6579         expect('(');
6580         expression->builtin_constant.value = parse_expression();
6581         rem_anchor_token(')');
6582         expect(')');
6583         expression->base.type = type_int;
6584
6585         return expression;
6586 }
6587
6588 /**
6589  * Parses a __builtin_types_compatible_p() expression.
6590  */
6591 static expression_t *parse_builtin_types_compatible(void)
6592 {
6593         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6594
6595         eat(T___builtin_types_compatible_p);
6596
6597         add_anchor_token(')');
6598         add_anchor_token(',');
6599         expect('(');
6600         expression->builtin_types_compatible.left = parse_typename();
6601         rem_anchor_token(',');
6602         expect(',');
6603         expression->builtin_types_compatible.right = parse_typename();
6604         rem_anchor_token(')');
6605         expect(')');
6606         expression->base.type = type_int;
6607
6608         return expression;
6609 }
6610
6611 /**
6612  * Parses a __builtin_is_*() compare expression.
6613  */
6614 static expression_t *parse_compare_builtin(void)
6615 {
6616         expression_kind_t kind;
6617         switch (token.kind) {
6618         case T___builtin_isgreater:      kind = EXPR_BINARY_ISGREATER;      break;
6619         case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6620         case T___builtin_isless:         kind = EXPR_BINARY_ISLESS;         break;
6621         case T___builtin_islessequal:    kind = EXPR_BINARY_ISLESSEQUAL;    break;
6622         case T___builtin_islessgreater:  kind = EXPR_BINARY_ISLESSGREATER;  break;
6623         case T___builtin_isunordered:    kind = EXPR_BINARY_ISUNORDERED;    break;
6624         default: internal_errorf(HERE, "invalid compare builtin found");
6625         }
6626         expression_t *const expression = allocate_expression_zero(kind);
6627         next_token();
6628
6629         add_anchor_token(')');
6630         add_anchor_token(',');
6631         expect('(');
6632         expression->binary.left = parse_assignment_expression();
6633         rem_anchor_token(',');
6634         expect(',');
6635         expression->binary.right = parse_assignment_expression();
6636         rem_anchor_token(')');
6637         expect(')');
6638
6639         type_t *const orig_type_left  = expression->binary.left->base.type;
6640         type_t *const orig_type_right = expression->binary.right->base.type;
6641
6642         type_t *const type_left  = skip_typeref(orig_type_left);
6643         type_t *const type_right = skip_typeref(orig_type_right);
6644         if (!is_type_float(type_left) && !is_type_float(type_right)) {
6645                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6646                         type_error_incompatible("invalid operands in comparison",
6647                                 &expression->base.pos, orig_type_left, orig_type_right);
6648                 }
6649         } else {
6650                 semantic_comparison(&expression->binary, true);
6651         }
6652
6653         return expression;
6654 }
6655
6656 /**
6657  * Parses a MS assume() expression.
6658  */
6659 static expression_t *parse_assume(void)
6660 {
6661         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6662
6663         eat(T__assume);
6664
6665         add_anchor_token(')');
6666         expect('(');
6667         expression->unary.value = parse_expression();
6668         rem_anchor_token(')');
6669         expect(')');
6670
6671         expression->base.type = type_void;
6672         return expression;
6673 }
6674
6675 /**
6676  * Return the label for the current symbol or create a new one.
6677  */
6678 static label_t *get_label(char const *const context)
6679 {
6680         assert(current_function != NULL);
6681
6682         symbol_t *const sym = expect_identifier(context, NULL);
6683         if (!sym)
6684                 return NULL;
6685
6686         entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6687         /* If we find a local label, we already created the declaration. */
6688         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6689                 if (label->base.parent_scope != current_scope) {
6690                         assert(label->base.parent_scope->depth < current_scope->depth);
6691                         current_function->goto_to_outer = true;
6692                 }
6693         } else if (label == NULL || label->base.parent_scope != &current_function->parameters) {
6694                 /* There is no matching label in the same function, so create a new one. */
6695                 position_t const nowhere = { NULL, 0, 0, false };
6696                 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6697                 label_push(label);
6698         }
6699
6700         return &label->label;
6701 }
6702
6703 /**
6704  * Parses a GNU && label address expression.
6705  */
6706 static expression_t *parse_label_address(void)
6707 {
6708         position_t const pos = *HERE;
6709         eat(T_ANDAND);
6710
6711         label_t *const label = get_label("while parsing label address");
6712         if (!label)
6713                 return create_error_expression();
6714
6715         label->used          = true;
6716         label->address_taken = true;
6717
6718         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6719         expression->base.pos     = pos;
6720
6721         /* label address is treated as a void pointer */
6722         expression->base.type           = type_void_ptr;
6723         expression->label_address.label = label;
6724         return expression;
6725 }
6726
6727 /**
6728  * Parse a microsoft __noop expression.
6729  */
6730 static expression_t *parse_noop_expression(void)
6731 {
6732         /* the result is a (int)0 */
6733         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6734         literal->base.type           = type_int;
6735         literal->literal.value.begin = "__noop";
6736         literal->literal.value.size  = 6;
6737
6738         eat(T___noop);
6739
6740         if (token.kind == '(') {
6741                 /* parse arguments */
6742                 eat('(');
6743                 add_anchor_token(')');
6744                 add_anchor_token(',');
6745
6746                 if (token.kind != ')') do {
6747                         (void)parse_assignment_expression();
6748                 } while (accept(','));
6749
6750                 rem_anchor_token(',');
6751                 rem_anchor_token(')');
6752         }
6753         expect(')');
6754
6755         return literal;
6756 }
6757
6758 /**
6759  * Parses a primary expression.
6760  */
6761 static expression_t *parse_primary_expression(void)
6762 {
6763         switch (token.kind) {
6764         case T_false:                        return parse_boolean_literal(false);
6765         case T_true:                         return parse_boolean_literal(true);
6766         case T_NUMBER:                       return parse_number_literal();
6767         case T_CHARACTER_CONSTANT:           return parse_character_constant();
6768         case T_STRING_LITERAL:               return parse_string_literal();
6769         case T___func__:                     return parse_function_keyword(FUNCNAME_FUNCTION);
6770         case T___PRETTY_FUNCTION__:          return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6771         case T___FUNCSIG__:                  return parse_function_keyword(FUNCNAME_FUNCSIG);
6772         case T___FUNCDNAME__:                return parse_function_keyword(FUNCNAME_FUNCDNAME);
6773         case T___builtin_offsetof:           return parse_offsetof();
6774         case T___builtin_va_start:           return parse_va_start();
6775         case T___builtin_va_arg:             return parse_va_arg();
6776         case T___builtin_va_copy:            return parse_va_copy();
6777         case T___builtin_isgreater:
6778         case T___builtin_isgreaterequal:
6779         case T___builtin_isless:
6780         case T___builtin_islessequal:
6781         case T___builtin_islessgreater:
6782         case T___builtin_isunordered:        return parse_compare_builtin();
6783         case T___builtin_constant_p:         return parse_builtin_constant();
6784         case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6785         case T__assume:                      return parse_assume();
6786         case T_ANDAND:
6787                 if (GNU_MODE)
6788                         return parse_label_address();
6789                 break;
6790
6791         case '(':                            return parse_parenthesized_expression();
6792         case T___noop:                       return parse_noop_expression();
6793         case T___imag__:                     return parse_complex_extract_expression(EXPR_UNARY_IMAG);
6794         case T___real__:                     return parse_complex_extract_expression(EXPR_UNARY_REAL);
6795
6796         /* Gracefully handle type names while parsing expressions. */
6797         case T_COLONCOLON:
6798                 return parse_reference();
6799         case T_IDENTIFIER:
6800                 if (!is_typedef_symbol(token.base.symbol)) {
6801                         return parse_reference();
6802                 }
6803                 /* FALLTHROUGH */
6804         DECLARATION_START {
6805                 position_t const pos = *HERE;
6806                 declaration_specifiers_t specifiers;
6807                 parse_declaration_specifiers(&specifiers);
6808                 type_t const *const type = parse_abstract_declarator(specifiers.type);
6809                 errorf(&pos, "encountered type '%T' while parsing expression", type);
6810                 return create_error_expression();
6811         }
6812         }
6813
6814         errorf(HERE, "unexpected token %K, expected an expression", &token);
6815         eat_until_anchor();
6816         return create_error_expression();
6817 }
6818
6819 static expression_t *parse_array_expression(expression_t *left)
6820 {
6821         expression_t              *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6822         array_access_expression_t *const arr  = &expr->array_access;
6823
6824         eat('[');
6825         add_anchor_token(']');
6826
6827         expression_t *const inside = parse_expression();
6828
6829         type_t *const orig_type_left   = left->base.type;
6830         type_t *const orig_type_inside = inside->base.type;
6831
6832         type_t *const type_left   = skip_typeref(orig_type_left);
6833         type_t *const type_inside = skip_typeref(orig_type_inside);
6834
6835         expression_t *ref;
6836         expression_t *idx;
6837         type_t       *idx_type;
6838         type_t       *res_type;
6839         if (is_type_pointer(type_left)) {
6840                 ref      = left;
6841                 idx      = inside;
6842                 idx_type = type_inside;
6843                 res_type = type_left->pointer.points_to;
6844                 goto check_idx;
6845         } else if (is_type_pointer(type_inside)) {
6846                 arr->flipped = true;
6847                 ref      = inside;
6848                 idx      = left;
6849                 idx_type = type_left;
6850                 res_type = type_inside->pointer.points_to;
6851 check_idx:
6852                 res_type = automatic_type_conversion(res_type);
6853                 if (!is_type_integer(idx_type)) {
6854                         if (is_type_valid(idx_type))
6855                                 errorf(&idx->base.pos, "array subscript must have integer type");
6856                 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6857                         position_t const *const pos = &idx->base.pos;
6858                         warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6859                 }
6860         } else {
6861                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6862                         errorf(&expr->base.pos, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6863                 }
6864                 res_type = type_error_type;
6865                 ref      = left;
6866                 idx      = inside;
6867         }
6868
6869         arr->array_ref = ref;
6870         arr->index     = idx;
6871         arr->base.type = res_type;
6872
6873         rem_anchor_token(']');
6874         expect(']');
6875         return expr;
6876 }
6877
6878 static bool is_bitfield(const expression_t *expression)
6879 {
6880         return expression->kind == EXPR_SELECT
6881                 && expression->select.compound_entry->compound_member.bitfield;
6882 }
6883
6884 static expression_t *parse_typeprop(expression_kind_t const kind)
6885 {
6886         expression_t  *tp_expression = allocate_expression_zero(kind);
6887         tp_expression->base.type     = type_size_t;
6888
6889         eat(kind == EXPR_SIZEOF ? T_sizeof : T__Alignof);
6890
6891         type_t       *orig_type;
6892         expression_t *expression;
6893         if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6894                 position_t const pos = *HERE;
6895                 eat('(');
6896                 add_anchor_token(')');
6897                 orig_type = parse_typename();
6898                 rem_anchor_token(')');
6899                 expect(')');
6900
6901                 if (token.kind == '{') {
6902                         /* It was not sizeof(type) after all.  It is sizeof of an expression
6903                          * starting with a compound literal */
6904                         expression = parse_compound_literal(&pos, orig_type);
6905                         goto typeprop_expression;
6906                 }
6907         } else {
6908                 expression = parse_subexpression(PREC_UNARY);
6909
6910 typeprop_expression:
6911                 if (is_bitfield(expression)) {
6912                         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6913                         errorf(&tp_expression->base.pos,
6914                                    "operand of %s expression must not be a bitfield", what);
6915                 }
6916
6917                 tp_expression->typeprop.tp_expression = expression;
6918
6919                 orig_type = revert_automatic_type_conversion(expression);
6920                 expression->base.type = orig_type;
6921         }
6922
6923         tp_expression->typeprop.type   = orig_type;
6924         type_t const* const type       = skip_typeref(orig_type);
6925         char   const*       wrong_type = NULL;
6926         if (is_type_incomplete(type)) {
6927                 if (!is_type_void(type) || !GNU_MODE)
6928                         wrong_type = "incomplete";
6929         } else if (type->kind == TYPE_FUNCTION) {
6930                 if (GNU_MODE) {
6931                         /* function types are allowed (and return 1) */
6932                         position_t const *const pos  = &tp_expression->base.pos;
6933                         char       const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6934                         warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6935                 } else {
6936                         wrong_type = "function";
6937                 }
6938         }
6939
6940         if (wrong_type != NULL) {
6941                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6942                 errorf(&tp_expression->base.pos,
6943                                 "operand of %s expression must not be of %s type '%T'",
6944                                 what, wrong_type, orig_type);
6945         }
6946
6947         return tp_expression;
6948 }
6949
6950 static expression_t *parse_sizeof(void)
6951 {
6952         return parse_typeprop(EXPR_SIZEOF);
6953 }
6954
6955 static expression_t *parse_alignof(void)
6956 {
6957         return parse_typeprop(EXPR_ALIGNOF);
6958 }
6959
6960 static expression_t *parse_select_expression(expression_t *addr)
6961 {
6962         assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6963         bool select_left_arrow = (token.kind == T_MINUSGREATER);
6964         position_t const pos = *HERE;
6965         next_token();
6966
6967         symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6968         if (!symbol)
6969                 return create_error_expression();
6970
6971         type_t *const orig_type = addr->base.type;
6972         type_t *const type      = skip_typeref(orig_type);
6973
6974         type_t *type_left;
6975         bool    saw_error = false;
6976         if (is_type_pointer(type)) {
6977                 if (!select_left_arrow) {
6978                         errorf(&pos,
6979                                "request for member '%Y' in something not a struct or union, but '%T'",
6980                                symbol, orig_type);
6981                         saw_error = true;
6982                 }
6983                 type_left = skip_typeref(type->pointer.points_to);
6984         } else {
6985                 if (select_left_arrow && is_type_valid(type)) {
6986                         errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6987                         saw_error = true;
6988                 }
6989                 type_left = type;
6990         }
6991
6992         if (!is_type_compound(type_left)) {
6993                 if (is_type_valid(type_left) && !saw_error) {
6994                         errorf(&pos,
6995                                "request for member '%Y' in something not a struct or union, but '%T'",
6996                                symbol, type_left);
6997                 }
6998                 return create_error_expression();
6999         }
7000
7001         compound_t *compound = type_left->compound.compound;
7002         if (!compound->complete) {
7003                 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7004                        symbol, type_left);
7005                 return create_error_expression();
7006         }
7007
7008         type_qualifiers_t  qualifiers = type_left->base.qualifiers;
7009         expression_t      *result     =
7010                 find_create_select(&pos, addr, qualifiers, compound, symbol);
7011
7012         if (result == NULL) {
7013                 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7014                 return create_error_expression();
7015         }
7016
7017         return result;
7018 }
7019
7020 static void check_call_argument(type_t          *expected_type,
7021                                 call_argument_t *argument, unsigned pos)
7022 {
7023         type_t         *expected_type_skip = skip_typeref(expected_type);
7024         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7025         expression_t   *arg_expr           = argument->expression;
7026         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7027
7028         /* handle transparent union gnu extension */
7029         if (is_type_union(expected_type_skip)
7030                         && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7031                 compound_t *union_decl  = expected_type_skip->compound.compound;
7032                 type_t     *best_type   = NULL;
7033                 entity_t   *entry       = union_decl->members.entities;
7034                 for ( ; entry != NULL; entry = entry->base.next) {
7035                         assert(is_declaration(entry));
7036                         type_t *decl_type = entry->declaration.type;
7037                         error = semantic_assign(decl_type, arg_expr);
7038                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7039                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7040                                 continue;
7041
7042                         if (error == ASSIGN_SUCCESS) {
7043                                 best_type = decl_type;
7044                         } else if (best_type == NULL) {
7045                                 best_type = decl_type;
7046                         }
7047                 }
7048
7049                 if (best_type != NULL) {
7050                         expected_type = best_type;
7051                 }
7052         }
7053
7054         error                = semantic_assign(expected_type, arg_expr);
7055         argument->expression = create_implicit_cast(arg_expr, expected_type);
7056
7057         if (error != ASSIGN_SUCCESS) {
7058                 /* report exact scope in error messages (like "in argument 3") */
7059                 char buf[64];
7060                 snprintf(buf, sizeof(buf), "call argument %u", pos);
7061                 report_assign_error(error, expected_type, arg_expr, buf,
7062                                     &arg_expr->base.pos);
7063         } else {
7064                 type_t *const promoted_type = get_default_promoted_type(arg_type);
7065                 if (!types_compatible(expected_type_skip, promoted_type) &&
7066                     !types_compatible(expected_type_skip, type_void_ptr) &&
7067                     !types_compatible(type_void_ptr,      promoted_type)) {
7068                         /* Deliberately show the skipped types in this warning */
7069                         position_t const *const apos = &arg_expr->base.pos;
7070                         warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7071                 }
7072         }
7073 }
7074
7075 /**
7076  * Handle the semantic restrictions of builtin calls
7077  */
7078 static void handle_builtin_argument_restrictions(call_expression_t *call)
7079 {
7080         entity_t *entity = call->function->reference.entity;
7081         switch (entity->function.btk) {
7082         case BUILTIN_FIRM:
7083                 switch (entity->function.b.firm_builtin_kind) {
7084                 case ir_bk_return_address:
7085                 case ir_bk_frame_address: {
7086                         /* argument must be constant */
7087                         call_argument_t *argument = call->arguments;
7088
7089                         if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7090                                 errorf(&call->base.pos,
7091                                            "argument of '%Y' must be a constant expression",
7092                                            call->function->reference.entity->base.symbol);
7093                         }
7094                         break;
7095                 }
7096                 case ir_bk_prefetch:
7097                         /* second and third argument must be constant if existent */
7098                         if (call->arguments == NULL)
7099                                 break;
7100                         call_argument_t *rw = call->arguments->next;
7101                         call_argument_t *locality = NULL;
7102
7103                         if (rw != NULL) {
7104                                 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7105                                         errorf(&call->base.pos,
7106                                                    "second argument of '%Y' must be a constant expression",
7107                                                    call->function->reference.entity->base.symbol);
7108                                 }
7109                                 locality = rw->next;
7110                         }
7111                         if (locality != NULL) {
7112                                 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7113                                         errorf(&call->base.pos,
7114                                                    "third argument of '%Y' must be a constant expression",
7115                                                    call->function->reference.entity->base.symbol);
7116                                 }
7117                         }
7118                         break;
7119                 default:
7120                         break;
7121                 }
7122
7123         case BUILTIN_OBJECT_SIZE:
7124                 if (call->arguments == NULL)
7125                         break;
7126
7127                 call_argument_t *arg = call->arguments->next;
7128                 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7129                         errorf(&call->base.pos,
7130                                    "second argument of '%Y' must be a constant expression",
7131                                    call->function->reference.entity->base.symbol);
7132                 }
7133                 break;
7134         default:
7135                 break;
7136         }
7137 }
7138
7139 /**
7140  * Parse a call expression, i.e. expression '( ... )'.
7141  *
7142  * @param expression  the function address
7143  */
7144 static expression_t *parse_call_expression(expression_t *expression)
7145 {
7146         expression_t      *result = allocate_expression_zero(EXPR_CALL);
7147         call_expression_t *call   = &result->call;
7148         call->function            = expression;
7149
7150         type_t *const orig_type = expression->base.type;
7151         type_t *const type      = skip_typeref(orig_type);
7152
7153         function_type_t *function_type = NULL;
7154         if (is_type_pointer(type)) {
7155                 type_t *const to_type = skip_typeref(type->pointer.points_to);
7156
7157                 if (is_type_function(to_type)) {
7158                         function_type   = &to_type->function;
7159                         call->base.type = function_type->return_type;
7160                 }
7161         }
7162
7163         if (function_type == NULL && is_type_valid(type)) {
7164                 errorf(HERE,
7165                        "called object '%E' (type '%T') is not a pointer to a function",
7166                        expression, orig_type);
7167         }
7168
7169         /* parse arguments */
7170         eat('(');
7171         add_anchor_token(')');
7172         add_anchor_token(',');
7173
7174         if (token.kind != ')') {
7175                 call_argument_t **anchor = &call->arguments;
7176                 do {
7177                         call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7178                         argument->expression = parse_assignment_expression();
7179
7180                         *anchor = argument;
7181                         anchor  = &argument->next;
7182                 } while (accept(','));
7183         }
7184         rem_anchor_token(',');
7185         rem_anchor_token(')');
7186         expect(')');
7187
7188         if (function_type == NULL)
7189                 return result;
7190
7191         /* check type and count of call arguments */
7192         function_parameter_t *parameter = function_type->parameters;
7193         call_argument_t      *argument  = call->arguments;
7194         if (!function_type->unspecified_parameters) {
7195                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7196                                 parameter = parameter->next, argument = argument->next) {
7197                         check_call_argument(parameter->type, argument, ++pos);
7198                 }
7199
7200                 if (parameter != NULL) {
7201                         errorf(&expression->base.pos, "too few arguments to function '%E'",
7202                                expression);
7203                 } else if (argument != NULL && !function_type->variadic) {
7204                         errorf(&argument->expression->base.pos,
7205                                "too many arguments to function '%E'", expression);
7206                 }
7207         }
7208
7209         /* do default promotion for other arguments */
7210         for (; argument != NULL; argument = argument->next) {
7211                 type_t *argument_type = argument->expression->base.type;
7212                 if (!is_type_object(skip_typeref(argument_type))) {
7213                         errorf(&argument->expression->base.pos,
7214                                "call argument '%E' must not be void", argument->expression);
7215                 }
7216
7217                 argument_type = get_default_promoted_type(argument_type);
7218
7219                 argument->expression
7220                         = create_implicit_cast(argument->expression, argument_type);
7221         }
7222
7223         check_format(call);
7224
7225         if (is_type_compound(skip_typeref(function_type->return_type))) {
7226                 position_t const *const pos = &expression->base.pos;
7227                 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7228         }
7229
7230         if (expression->kind == EXPR_REFERENCE) {
7231                 reference_expression_t *reference = &expression->reference;
7232                 if (reference->entity->kind == ENTITY_FUNCTION &&
7233                     reference->entity->function.btk != BUILTIN_NONE)
7234                         handle_builtin_argument_restrictions(call);
7235         }
7236
7237         return result;
7238 }
7239
7240 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7241
7242 static bool same_compound_type(const type_t *type1, const type_t *type2)
7243 {
7244         return
7245                 is_type_compound(type1) &&
7246                 type1->kind == type2->kind &&
7247                 type1->compound.compound == type2->compound.compound;
7248 }
7249
7250 static expression_t const *get_reference_address(expression_t const *expr)
7251 {
7252         bool regular_take_address = true;
7253         for (;;) {
7254                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7255                         expr = expr->unary.value;
7256                 } else {
7257                         regular_take_address = false;
7258                 }
7259
7260                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7261                         break;
7262
7263                 expr = expr->unary.value;
7264         }
7265
7266         if (expr->kind != EXPR_REFERENCE)
7267                 return NULL;
7268
7269         /* special case for functions which are automatically converted to a
7270          * pointer to function without an extra TAKE_ADDRESS operation */
7271         if (!regular_take_address &&
7272                         expr->reference.entity->kind != ENTITY_FUNCTION) {
7273                 return NULL;
7274         }
7275
7276         return expr;
7277 }
7278
7279 static void warn_reference_address_as_bool(expression_t const* expr)
7280 {
7281         expr = get_reference_address(expr);
7282         if (expr != NULL) {
7283                 position_t const *const pos = &expr->base.pos;
7284                 entity_t   const *const ent = expr->reference.entity;
7285                 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7286         }
7287 }
7288
7289 static void warn_assignment_in_condition(const expression_t *const expr)
7290 {
7291         if (expr->base.kind != EXPR_BINARY_ASSIGN)
7292                 return;
7293         if (expr->base.parenthesized)
7294                 return;
7295         position_t const *const pos = &expr->base.pos;
7296         warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7297 }
7298
7299 static void semantic_condition(expression_t const *const expr,
7300                                char const *const context)
7301 {
7302         type_t *const type = skip_typeref(expr->base.type);
7303         if (is_type_scalar(type)) {
7304                 warn_reference_address_as_bool(expr);
7305                 warn_assignment_in_condition(expr);
7306         } else if (is_type_valid(type)) {
7307                 errorf(&expr->base.pos, "%s must have scalar type", context);
7308         }
7309 }
7310
7311 /**
7312  * Parse a conditional expression, i.e. 'expression ? ... : ...'.
7313  *
7314  * @param expression  the conditional expression
7315  */
7316 static expression_t *parse_conditional_expression(expression_t *expression)
7317 {
7318         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7319
7320         conditional_expression_t *conditional = &result->conditional;
7321         conditional->condition                = expression;
7322
7323         eat('?');
7324         add_anchor_token(':');
7325
7326         /* §6.5.15:2  The first operand shall have scalar type. */
7327         semantic_condition(expression, "condition of conditional operator");
7328
7329         expression_t *true_expression = expression;
7330         bool          gnu_cond = false;
7331         if (GNU_MODE && token.kind == ':') {
7332                 gnu_cond = true;
7333         } else {
7334                 true_expression = parse_expression();
7335         }
7336         rem_anchor_token(':');
7337         expect(':');
7338         expression_t *false_expression =
7339                 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7340
7341         type_t *const orig_true_type  = true_expression->base.type;
7342         type_t *const orig_false_type = false_expression->base.type;
7343         type_t *const true_type       = skip_typeref(orig_true_type);
7344         type_t *const false_type      = skip_typeref(orig_false_type);
7345
7346         /* 6.5.15.3 */
7347         position_t const *const pos = &conditional->base.pos;
7348         type_t                 *result_type;
7349         if (is_type_void(true_type) || is_type_void(false_type)) {
7350                 /* ISO/IEC 14882:1998(E) §5.16:2 */
7351                 if (true_expression->kind == EXPR_UNARY_THROW) {
7352                         result_type = false_type;
7353                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7354                         result_type = true_type;
7355                 } else {
7356                         if (!is_type_void(true_type) || !is_type_void(false_type)) {
7357                                 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7358                         }
7359                         result_type = type_void;
7360                 }
7361         } else if (is_type_arithmetic(true_type)
7362                    && is_type_arithmetic(false_type)) {
7363                 result_type = semantic_arithmetic(true_type, false_type);
7364         } else if (same_compound_type(true_type, false_type)) {
7365                 /* just take 1 of the 2 types */
7366                 result_type = true_type;
7367         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7368                 type_t *pointer_type;
7369                 type_t *other_type;
7370                 expression_t *other_expression;
7371                 if (is_type_pointer(true_type) &&
7372                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7373                         pointer_type     = true_type;
7374                         other_type       = false_type;
7375                         other_expression = false_expression;
7376                 } else {
7377                         pointer_type     = false_type;
7378                         other_type       = true_type;
7379                         other_expression = true_expression;
7380                 }
7381
7382                 if (is_null_pointer_constant(other_expression)) {
7383                         result_type = pointer_type;
7384                 } else if (is_type_pointer(other_type)) {
7385                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7386                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
7387
7388                         type_t *to;
7389                         if (is_type_void(to1) || is_type_void(to2)) {
7390                                 to = type_void;
7391                         } else if (types_compatible(get_unqualified_type(to1),
7392                                                     get_unqualified_type(to2))) {
7393                                 to = to1;
7394                         } else {
7395                                 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7396                                 to = type_void;
7397                         }
7398
7399                         type_t *const type =
7400                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7401                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7402                 } else if (is_type_integer(other_type)) {
7403                         warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7404                         result_type = pointer_type;
7405                 } else {
7406                         goto types_incompatible;
7407                 }
7408         } else {
7409 types_incompatible:
7410                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7411                         type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7412                 }
7413                 result_type = type_error_type;
7414         }
7415
7416         conditional->true_expression
7417                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7418         conditional->false_expression
7419                 = create_implicit_cast(false_expression, result_type);
7420         conditional->base.type = result_type;
7421         return result;
7422 }
7423
7424 /**
7425  * Parse an extension expression.
7426  */
7427 static expression_t *parse_extension(void)
7428 {
7429         PUSH_EXTENSION();
7430         expression_t *expression = parse_subexpression(PREC_UNARY);
7431         POP_EXTENSION();
7432         return expression;
7433 }
7434
7435 /**
7436  * Parse a __builtin_classify_type() expression.
7437  */
7438 static expression_t *parse_builtin_classify_type(void)
7439 {
7440         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7441         result->base.type    = type_int;
7442
7443         eat(T___builtin_classify_type);
7444
7445         add_anchor_token(')');
7446         expect('(');
7447         expression_t *expression = parse_expression();
7448         rem_anchor_token(')');
7449         expect(')');
7450         result->classify_type.type_expression = expression;
7451
7452         return result;
7453 }
7454
7455 /**
7456  * Parse a delete expression
7457  * ISO/IEC 14882:1998(E) §5.3.5
7458  */
7459 static expression_t *parse_delete(void)
7460 {
7461         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7462         result->base.type          = type_void;
7463
7464         eat(T_delete);
7465
7466         if (accept('[')) {
7467                 result->kind = EXPR_UNARY_DELETE_ARRAY;
7468                 expect(']');
7469         }
7470
7471         expression_t *const value = parse_subexpression(PREC_CAST);
7472         result->unary.value = value;
7473
7474         type_t *const type = skip_typeref(value->base.type);
7475         if (!is_type_pointer(type)) {
7476                 if (is_type_valid(type)) {
7477                         errorf(&value->base.pos,
7478                                         "operand of delete must have pointer type");
7479                 }
7480         } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7481                 position_t const *const pos = &value->base.pos;
7482                 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7483         }
7484
7485         return result;
7486 }
7487
7488 /**
7489  * Parse a throw expression
7490  * ISO/IEC 14882:1998(E) §15:1
7491  */
7492 static expression_t *parse_throw(void)
7493 {
7494         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7495         result->base.type          = type_void;
7496
7497         eat(T_throw);
7498
7499         expression_t *value = NULL;
7500         switch (token.kind) {
7501                 EXPRESSION_START {
7502                         value = parse_assignment_expression();
7503                         /* ISO/IEC 14882:1998(E) §15.1:3 */
7504                         type_t *const orig_type = value->base.type;
7505                         type_t *const type      = skip_typeref(orig_type);
7506                         if (is_type_incomplete(type)) {
7507                                 errorf(&value->base.pos,
7508                                                 "cannot throw object of incomplete type '%T'", orig_type);
7509                         } else if (is_type_pointer(type)) {
7510                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
7511                                 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7512                                         errorf(&value->base.pos,
7513                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
7514                                 }
7515                         }
7516                 }
7517
7518                 default:
7519                         break;
7520         }
7521         result->unary.value = value;
7522
7523         return result;
7524 }
7525
7526 static bool check_pointer_arithmetic(const position_t *pos,
7527                                      type_t *pointer_type,
7528                                      type_t *orig_pointer_type)
7529 {
7530         type_t *points_to = pointer_type->pointer.points_to;
7531         points_to = skip_typeref(points_to);
7532
7533         if (is_type_incomplete(points_to)) {
7534                 if (!GNU_MODE || !is_type_void(points_to)) {
7535                         errorf(pos,
7536                                "arithmetic with pointer to incomplete type '%T' not allowed",
7537                                orig_pointer_type);
7538                         return false;
7539                 } else {
7540                         warningf(WARN_POINTER_ARITH, pos, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7541                 }
7542         } else if (is_type_function(points_to)) {
7543                 if (!GNU_MODE) {
7544                         errorf(pos,
7545                                "arithmetic with pointer to function type '%T' not allowed",
7546                                orig_pointer_type);
7547                         return false;
7548                 } else {
7549                         warningf(WARN_POINTER_ARITH, pos,
7550                                  "pointer to a function '%T' used in arithmetic",
7551                                  orig_pointer_type);
7552                 }
7553         }
7554         return true;
7555 }
7556
7557 static bool is_lvalue(const expression_t *expression)
7558 {
7559         /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7560         switch (expression->kind) {
7561         case EXPR_ARRAY_ACCESS:
7562         case EXPR_COMPOUND_LITERAL:
7563         case EXPR_REFERENCE:
7564         case EXPR_SELECT:
7565         case EXPR_UNARY_DEREFERENCE:
7566                 return true;
7567
7568         default: {
7569                 type_t *type = skip_typeref(expression->base.type);
7570                 return
7571                         /* ISO/IEC 14882:1998(E) §3.10:3 */
7572                         is_type_reference(type) ||
7573                         /* Claim it is an lvalue, if the type is invalid.  There was a parse
7574                          * error before, which maybe prevented properly recognizing it as
7575                          * lvalue. */
7576                         !is_type_valid(type);
7577         }
7578         }
7579 }
7580
7581 static void semantic_incdec(unary_expression_t *expression)
7582 {
7583         type_t *orig_type = expression->value->base.type;
7584         type_t *type      = skip_typeref(orig_type);
7585         if (is_type_pointer(type)) {
7586                 if (!check_pointer_arithmetic(&expression->base.pos, type, orig_type)) {
7587                         return;
7588                 }
7589         } else if (!is_type_real(type) &&
7590                    (!GNU_MODE || !is_type_complex(type)) && is_type_valid(type)) {
7591                 /* TODO: improve error message */
7592                 errorf(&expression->base.pos,
7593                        "operation needs an arithmetic or pointer type");
7594                 orig_type = type = type_error_type;
7595         }
7596         if (!is_lvalue(expression->value)) {
7597                 /* TODO: improve error message */
7598                 errorf(&expression->base.pos, "lvalue required as operand");
7599         }
7600         expression->base.type = orig_type;
7601 }
7602
7603 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7604 {
7605         atomic_type_kind_t akind = get_arithmetic_akind(type);
7606         type_t *res_type;
7607         if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT)) {
7608                 if (type->kind == TYPE_COMPLEX)
7609                         res_type = make_complex_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
7610                 else
7611                         res_type = type_int;
7612         } else {
7613                 res_type = type;
7614         }
7615         expr->base.type = res_type;
7616         expr->value     = create_implicit_cast(expr->value, res_type);
7617 }
7618
7619 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7620 {
7621         type_t *const orig_type = expression->value->base.type;
7622         type_t *const type      = skip_typeref(orig_type);
7623         if (!is_type_arithmetic(type)) {
7624                 if (is_type_valid(type)) {
7625                         position_t const *const pos = &expression->base.pos;
7626                         errorf(pos, "operand of unary expression must have arithmetic type, but is '%T'", orig_type);
7627                 }
7628                 return;
7629         } else if (is_type_integer(type)) {
7630                 promote_unary_int_expr(expression, type);
7631         } else {
7632                 expression->base.type = orig_type;
7633         }
7634 }
7635
7636 static void semantic_unexpr_plus(unary_expression_t *expression)
7637 {
7638         semantic_unexpr_arithmetic(expression);
7639         position_t const *const pos = &expression->base.pos;
7640         warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7641 }
7642
7643 static void semantic_not(unary_expression_t *expression)
7644 {
7645         /* §6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
7646         semantic_condition(expression->value, "operand of !");
7647         expression->base.type = c_mode & _CXX ? type_bool : type_int;
7648 }
7649
7650 static void semantic_complement(unary_expression_t *expression)
7651 {
7652         type_t *const orig_type = expression->value->base.type;
7653         type_t *const type      = skip_typeref(orig_type);
7654         if (!is_type_integer(type) && (!GNU_MODE || !is_type_complex(type))) {
7655                 if (is_type_valid(type)) {
7656                         errorf(&expression->base.pos, "operand of ~ must be of integer type");
7657                 }
7658                 return;
7659         }
7660
7661         if (is_type_integer(type)) {
7662                 promote_unary_int_expr(expression, type);
7663         } else {
7664                 expression->base.type = orig_type;
7665         }
7666 }
7667
7668 static void semantic_dereference(unary_expression_t *expression)
7669 {
7670         type_t *const orig_type = expression->value->base.type;
7671         type_t *const type      = skip_typeref(orig_type);
7672         if (!is_type_pointer(type)) {
7673                 if (is_type_valid(type)) {
7674                         errorf(&expression->base.pos,
7675                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7676                 }
7677                 return;
7678         }
7679
7680         type_t *result_type   = type->pointer.points_to;
7681         result_type           = automatic_type_conversion(result_type);
7682         expression->base.type = result_type;
7683 }
7684
7685 /**
7686  * Record that an address is taken (expression represents an lvalue).
7687  *
7688  * @param expression       the expression
7689  * @param may_be_register  if true, the expression might be an register
7690  */
7691 static void set_address_taken(expression_t *expression, bool may_be_register)
7692 {
7693         if (expression->kind != EXPR_REFERENCE)
7694                 return;
7695
7696         entity_t *const entity = expression->reference.entity;
7697
7698         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7699                 return;
7700
7701         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7702                         && !may_be_register) {
7703                 position_t const *const pos = &expression->base.pos;
7704                 errorf(pos, "address of register '%N' requested", entity);
7705         }
7706
7707         entity->variable.address_taken = true;
7708 }
7709
7710 /**
7711  * Check the semantic of the address taken expression.
7712  */
7713 static void semantic_take_addr(unary_expression_t *expression)
7714 {
7715         expression_t *value = expression->value;
7716         value->base.type    = revert_automatic_type_conversion(value);
7717
7718         type_t *orig_type = value->base.type;
7719         type_t *type      = skip_typeref(orig_type);
7720         if (!is_type_valid(type))
7721                 return;
7722
7723         /* §6.5.3.2 */
7724         if (!is_lvalue(value)) {
7725                 errorf(&expression->base.pos, "'&' requires an lvalue");
7726         }
7727         if (is_bitfield(value)) {
7728                 errorf(&expression->base.pos, "'&' not allowed on bitfield");
7729         }
7730
7731         set_address_taken(value, false);
7732
7733         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7734 }
7735
7736 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7737 static expression_t *parse_##unexpression_type(void)                         \
7738 {                                                                            \
7739         expression_t *unary_expression                                           \
7740                 = allocate_expression_zero(unexpression_type);                       \
7741         eat(token_kind);                                                         \
7742         unary_expression->unary.value = parse_subexpression(PREC_UNARY);         \
7743                                                                                  \
7744         sfunc(&unary_expression->unary);                                         \
7745                                                                                  \
7746         return unary_expression;                                                 \
7747 }
7748
7749 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7750                                semantic_unexpr_arithmetic)
7751 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7752                                semantic_unexpr_plus)
7753 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7754                                semantic_not)
7755 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7756                                semantic_dereference)
7757 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7758                                semantic_take_addr)
7759 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_COMPLEMENT,
7760                                semantic_complement)
7761 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
7762                                semantic_incdec)
7763 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7764                                semantic_incdec)
7765
7766 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7767                                                sfunc)                         \
7768 static expression_t *parse_##unexpression_type(expression_t *left)            \
7769 {                                                                             \
7770         expression_t *unary_expression                                            \
7771                 = allocate_expression_zero(unexpression_type);                        \
7772         eat(token_kind);                                                          \
7773         unary_expression->unary.value = left;                                     \
7774                                                                                   \
7775         sfunc(&unary_expression->unary);                                          \
7776                                                                               \
7777         return unary_expression;                                                  \
7778 }
7779
7780 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7781                                        EXPR_UNARY_POSTFIX_INCREMENT,
7782                                        semantic_incdec)
7783 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7784                                        EXPR_UNARY_POSTFIX_DECREMENT,
7785                                        semantic_incdec)
7786
7787 static atomic_type_kind_t semantic_arithmetic_(atomic_type_kind_t kind_left,
7788                                                atomic_type_kind_t kind_right)
7789 {
7790         /* §6.3.1.8 Usual arithmetic conversions */
7791         if (kind_left == ATOMIC_TYPE_LONG_DOUBLE
7792          || kind_right == ATOMIC_TYPE_LONG_DOUBLE) {
7793                 return ATOMIC_TYPE_LONG_DOUBLE;
7794         } else if (kind_left == ATOMIC_TYPE_DOUBLE
7795                 || kind_right == ATOMIC_TYPE_DOUBLE) {
7796             return ATOMIC_TYPE_DOUBLE;
7797         } else if (kind_left == ATOMIC_TYPE_FLOAT
7798                 || kind_right == ATOMIC_TYPE_FLOAT) {
7799                 return ATOMIC_TYPE_FLOAT;
7800         }
7801
7802         unsigned       rank_left  = get_akind_rank(kind_left);
7803         unsigned       rank_right = get_akind_rank(kind_right);
7804         unsigned const rank_int   = get_akind_rank(ATOMIC_TYPE_INT);
7805         if (rank_left < rank_int) {
7806                 kind_left = ATOMIC_TYPE_INT;
7807                 rank_left = rank_int;
7808         }
7809         if (rank_right < rank_int) {
7810                 kind_right = ATOMIC_TYPE_INT;
7811                 rank_right = rank_int;
7812         }
7813         if (kind_left == kind_right)
7814                 return kind_left;
7815
7816         bool const signed_left  = is_akind_signed(kind_left);
7817         bool const signed_right = is_akind_signed(kind_right);
7818         if (signed_left == signed_right)
7819                 return rank_left >= rank_right ? kind_left : kind_right;
7820
7821         unsigned           s_rank;
7822         unsigned           u_rank;
7823         atomic_type_kind_t s_kind;
7824         atomic_type_kind_t u_kind;
7825         if (signed_left) {
7826                 s_kind = kind_left;
7827                 s_rank = rank_left;
7828                 u_kind = kind_right;
7829                 u_rank = rank_right;
7830         } else {
7831                 s_kind = kind_right;
7832                 s_rank = rank_right;
7833                 u_kind = kind_left;
7834                 u_rank = rank_left;
7835         }
7836         if (u_rank >= s_rank)
7837                 return u_kind;
7838         if (get_atomic_type_size(s_kind) > get_atomic_type_size(u_kind))
7839                 return s_kind;
7840
7841         switch (s_kind) {
7842         case ATOMIC_TYPE_INT:      return ATOMIC_TYPE_UINT;
7843         case ATOMIC_TYPE_LONG:     return ATOMIC_TYPE_ULONG;
7844         case ATOMIC_TYPE_LONGLONG: return ATOMIC_TYPE_ULONGLONG;
7845         default: panic("invalid atomic type");
7846         }
7847 }
7848
7849 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7850 {
7851         atomic_type_kind_t kind_left  = get_arithmetic_akind(type_left);
7852         atomic_type_kind_t kind_right = get_arithmetic_akind(type_right);
7853         atomic_type_kind_t kind_res   = semantic_arithmetic_(kind_left, kind_right);
7854
7855         if (type_left->kind == TYPE_COMPLEX || type_right->kind == TYPE_COMPLEX) {
7856                 return make_complex_type(kind_res, TYPE_QUALIFIER_NONE);
7857         }
7858         return make_atomic_type(kind_res, TYPE_QUALIFIER_NONE);
7859 }
7860
7861 /**
7862  * Check the semantic restrictions for a binary expression.
7863  */
7864 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7865 {
7866         expression_t *const left            = expression->left;
7867         expression_t *const right           = expression->right;
7868         type_t       *const orig_type_left  = left->base.type;
7869         type_t       *const orig_type_right = right->base.type;
7870         type_t       *const type_left       = skip_typeref(orig_type_left);
7871         type_t       *const type_right      = skip_typeref(orig_type_right);
7872
7873         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7874                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7875                         position_t const *const pos = &expression->base.pos;
7876                         errorf(pos, "operands of binary expression must have arithmetic types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7877                 }
7878                 return;
7879         }
7880
7881         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7882         expression->left      = create_implicit_cast(left, arithmetic_type);
7883         expression->right     = create_implicit_cast(right, arithmetic_type);
7884         expression->base.type = arithmetic_type;
7885 }
7886
7887 static void semantic_binexpr_integer(binary_expression_t *const expression)
7888 {
7889         expression_t *const left            = expression->left;
7890         expression_t *const right           = expression->right;
7891         type_t       *const orig_type_left  = left->base.type;
7892         type_t       *const orig_type_right = right->base.type;
7893         type_t       *const type_left       = skip_typeref(orig_type_left);
7894         type_t       *const type_right      = skip_typeref(orig_type_right);
7895
7896         if (!is_type_integer(type_left) || !is_type_integer(type_right)
7897           || is_type_complex(type_left) || is_type_complex(type_right)) {
7898                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7899                         position_t const *const pos = &expression->base.pos;
7900                         errorf(pos, "operands of binary expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7901                 }
7902                 return;
7903         }
7904
7905         type_t *const result_type = semantic_arithmetic(type_left, type_right);
7906         expression->left      = create_implicit_cast(left, result_type);
7907         expression->right     = create_implicit_cast(right, result_type);
7908         expression->base.type = result_type;
7909 }
7910
7911 static void warn_div_by_zero(binary_expression_t const *const expression)
7912 {
7913         if (!is_type_integer(expression->base.type))
7914                 return;
7915
7916         expression_t const *const right = expression->right;
7917         /* The type of the right operand can be different for /= */
7918         if (is_type_integer(skip_typeref(right->base.type))      &&
7919             is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7920             !fold_constant_to_bool(right)) {
7921                 position_t const *const pos = &expression->base.pos;
7922                 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7923         }
7924 }
7925
7926 /**
7927  * Check the semantic restrictions for a div expression.
7928  */
7929 static void semantic_div(binary_expression_t *expression)
7930 {
7931         semantic_binexpr_arithmetic(expression);
7932         warn_div_by_zero(expression);
7933 }
7934
7935 /**
7936  * Check the semantic restrictions for a mod expression.
7937  */
7938 static void semantic_mod(binary_expression_t *expression)
7939 {
7940         semantic_binexpr_integer(expression);
7941         warn_div_by_zero(expression);
7942 }
7943
7944 static void warn_addsub_in_shift(const expression_t *const expr)
7945 {
7946         if (expr->base.parenthesized)
7947                 return;
7948
7949         char op;
7950         switch (expr->kind) {
7951                 case EXPR_BINARY_ADD: op = '+'; break;
7952                 case EXPR_BINARY_SUB: op = '-'; break;
7953                 default:              return;
7954         }
7955
7956         position_t const *const pos = &expr->base.pos;
7957         warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7958 }
7959
7960 static bool semantic_shift(binary_expression_t *expression)
7961 {
7962         expression_t *const left            = expression->left;
7963         expression_t *const right           = expression->right;
7964         type_t       *const orig_type_left  = left->base.type;
7965         type_t       *const orig_type_right = right->base.type;
7966         type_t       *      type_left       = skip_typeref(orig_type_left);
7967         type_t       *      type_right      = skip_typeref(orig_type_right);
7968
7969         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7970                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7971                         position_t const *const pos = &expression->base.pos;
7972                         errorf(pos, "operands of shift expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7973                 }
7974                 return false;
7975         }
7976
7977         type_left = promote_integer(type_left);
7978
7979         if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7980                 position_t const *const pos   = &right->base.pos;
7981                 long              const count = fold_constant_to_int(right);
7982                 if (count < 0) {
7983                         warningf(WARN_OTHER, pos, "shift count must be non-negative");
7984                 } else if ((unsigned long)count >=
7985                                 get_atomic_type_size(type_left->atomic.akind) * 8) {
7986                         warningf(WARN_OTHER, pos, "shift count must be less than type width");
7987                 }
7988         }
7989
7990         type_right        = promote_integer(type_right);
7991         expression->right = create_implicit_cast(right, type_right);
7992
7993         return true;
7994 }
7995
7996 static void semantic_shift_op(binary_expression_t *expression)
7997 {
7998         expression_t *const left  = expression->left;
7999         expression_t *const right = expression->right;
8000
8001         if (!semantic_shift(expression))
8002                 return;
8003
8004         warn_addsub_in_shift(left);
8005         warn_addsub_in_shift(right);
8006
8007         type_t *const orig_type_left = left->base.type;
8008         type_t *      type_left      = skip_typeref(orig_type_left);
8009
8010         type_left             = promote_integer(type_left);
8011         expression->left      = create_implicit_cast(left, type_left);
8012         expression->base.type = type_left;
8013 }
8014
8015 static void semantic_add(binary_expression_t *expression)
8016 {
8017         expression_t *const left            = expression->left;
8018         expression_t *const right           = expression->right;
8019         type_t       *const orig_type_left  = left->base.type;
8020         type_t       *const orig_type_right = right->base.type;
8021         type_t       *const type_left       = skip_typeref(orig_type_left);
8022         type_t       *const type_right      = skip_typeref(orig_type_right);
8023
8024         /* §6.5.6 */
8025         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8026                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8027                 expression->left  = create_implicit_cast(left, arithmetic_type);
8028                 expression->right = create_implicit_cast(right, arithmetic_type);
8029                 expression->base.type = arithmetic_type;
8030         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8031                 check_pointer_arithmetic(&expression->base.pos, type_left,
8032                                          orig_type_left);
8033                 expression->base.type = type_left;
8034         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8035                 check_pointer_arithmetic(&expression->base.pos, type_right,
8036                                          orig_type_right);
8037                 expression->base.type = type_right;
8038         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8039                 errorf(&expression->base.pos,
8040                        "invalid operands to binary + ('%T', '%T')",
8041                        orig_type_left, orig_type_right);
8042         }
8043 }
8044
8045 static void semantic_sub(binary_expression_t *expression)
8046 {
8047         expression_t     *const left            = expression->left;
8048         expression_t     *const right           = expression->right;
8049         type_t           *const orig_type_left  = left->base.type;
8050         type_t           *const orig_type_right = right->base.type;
8051         type_t           *const type_left       = skip_typeref(orig_type_left);
8052         type_t           *const type_right      = skip_typeref(orig_type_right);
8053         position_t const *const pos             = &expression->base.pos;
8054
8055         /* §5.6.5 */
8056         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8057                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8058                 expression->left        = create_implicit_cast(left, arithmetic_type);
8059                 expression->right       = create_implicit_cast(right, arithmetic_type);
8060                 expression->base.type =  arithmetic_type;
8061         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8062                 check_pointer_arithmetic(&expression->base.pos, type_left,
8063                                          orig_type_left);
8064                 expression->base.type = type_left;
8065         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8066                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8067                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8068                 if (!types_compatible(unqual_left, unqual_right)) {
8069                         errorf(pos,
8070                                "subtracting pointers to incompatible types '%T' and '%T'",
8071                                orig_type_left, orig_type_right);
8072                 } else if (!is_type_object(unqual_left)) {
8073                         if (!is_type_void(unqual_left)) {
8074                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8075                                        orig_type_left);
8076                         } else {
8077                                 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8078                         }
8079                 }
8080                 expression->base.type = type_ptrdiff_t;
8081         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8082                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8083                        orig_type_left, orig_type_right);
8084         }
8085 }
8086
8087 static void warn_string_literal_address(expression_t const* expr)
8088 {
8089         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8090                 expr = expr->unary.value;
8091                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8092                         return;
8093                 expr = expr->unary.value;
8094         }
8095
8096         if (expr->kind == EXPR_STRING_LITERAL) {
8097                 position_t const *const pos = &expr->base.pos;
8098                 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8099         }
8100 }
8101
8102 static bool maybe_negative(expression_t const *const expr)
8103 {
8104         switch (is_constant_expression(expr)) {
8105                 case EXPR_CLASS_ERROR:    return false;
8106                 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8107                 default:                  return true;
8108         }
8109 }
8110
8111 static void warn_comparison(position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8112 {
8113         warn_string_literal_address(expr);
8114
8115         expression_t const* const ref = get_reference_address(expr);
8116         if (ref != NULL && is_null_pointer_constant(other)) {
8117                 entity_t const *const ent = ref->reference.entity;
8118                 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8119         }
8120
8121         if (!expr->base.parenthesized) {
8122                 switch (expr->base.kind) {
8123                         case EXPR_BINARY_LESS:
8124                         case EXPR_BINARY_GREATER:
8125                         case EXPR_BINARY_LESSEQUAL:
8126                         case EXPR_BINARY_GREATEREQUAL:
8127                         case EXPR_BINARY_NOTEQUAL:
8128                         case EXPR_BINARY_EQUAL:
8129                                 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8130                                 break;
8131                         default:
8132                                 break;
8133                 }
8134         }
8135 }
8136
8137 /**
8138  * Check the semantics of comparison expressions.
8139  */
8140 static void semantic_comparison(binary_expression_t *expression,
8141                                 bool is_relational)
8142 {
8143         position_t const *const pos   = &expression->base.pos;
8144         expression_t     *const left  = expression->left;
8145         expression_t     *const right = expression->right;
8146
8147         warn_comparison(pos, left, right);
8148         warn_comparison(pos, right, left);
8149
8150         type_t *orig_type_left  = left->base.type;
8151         type_t *orig_type_right = right->base.type;
8152         type_t *type_left       = skip_typeref(orig_type_left);
8153         type_t *type_right      = skip_typeref(orig_type_right);
8154
8155         /* TODO non-arithmetic types */
8156         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8157                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8158
8159                 /* test for signed vs unsigned compares */
8160                 if (is_type_integer(arithmetic_type)) {
8161                         bool const signed_left  = is_type_signed(type_left);
8162                         bool const signed_right = is_type_signed(type_right);
8163                         if (signed_left != signed_right) {
8164                                 /* FIXME long long needs better const folding magic */
8165                                 /* TODO check whether constant value can be represented by other type */
8166                                 if ((signed_left  && maybe_negative(left)) ||
8167                                                 (signed_right && maybe_negative(right))) {
8168                                         warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8169                                 }
8170                         }
8171                 }
8172
8173                 expression->left      = create_implicit_cast(left, arithmetic_type);
8174                 expression->right     = create_implicit_cast(right, arithmetic_type);
8175                 expression->base.type = arithmetic_type;
8176                 if (!is_relational && is_type_float(arithmetic_type)) {
8177                         warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8178                 }
8179                 /* for relational ops we need real types, not just arithmetic */
8180                 if (is_relational
8181                     && (!is_type_real(type_left) || !is_type_real(type_right))) {
8182                         type_error_incompatible("invalid operands for relational operator", pos, type_left, type_right);
8183                 }
8184         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8185                 /* TODO check compatibility */
8186         } else if (is_type_pointer(type_left)) {
8187                 expression->right = create_implicit_cast(right, type_left);
8188         } else if (is_type_pointer(type_right)) {
8189                 expression->left = create_implicit_cast(left, type_right);
8190         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8191                 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8192         }
8193         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8194 }
8195
8196 static void semantic_relational(binary_expression_t *expression)
8197 {
8198         semantic_comparison(expression, true);
8199 }
8200
8201 static void semantic_equality(binary_expression_t *expression)
8202 {
8203         semantic_comparison(expression, false);
8204 }
8205
8206 /**
8207  * Checks if a compound type has constant fields.
8208  */
8209 static bool has_const_fields(const compound_type_t *type)
8210 {
8211         compound_t *compound = type->compound;
8212         entity_t   *entry    = compound->members.entities;
8213
8214         for (; entry != NULL; entry = entry->base.next) {
8215                 if (!is_declaration(entry))
8216                         continue;
8217
8218                 const type_t *decl_type = skip_typeref(entry->declaration.type);
8219                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8220                         return true;
8221         }
8222
8223         return false;
8224 }
8225
8226 static bool is_valid_assignment_lhs(expression_t const* const left)
8227 {
8228         type_t *const orig_type_left = revert_automatic_type_conversion(left);
8229         type_t *const type_left      = skip_typeref(orig_type_left);
8230
8231         if (!is_lvalue(left)) {
8232                 errorf(&left->base.pos,
8233                        "left hand side '%E' of assignment is not an lvalue", left);
8234                 return false;
8235         }
8236
8237         if (left->kind == EXPR_REFERENCE
8238                         && left->reference.entity->kind == ENTITY_FUNCTION) {
8239                 errorf(&left->base.pos, "cannot assign to function '%E'", left);
8240                 return false;
8241         }
8242
8243         if (is_type_array(type_left)) {
8244                 errorf(&left->base.pos, "cannot assign to array '%E'", left);
8245                 return false;
8246         }
8247         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8248                 errorf(&left->base.pos,
8249                        "assignment to read-only location '%E' (type '%T')", left,
8250                        orig_type_left);
8251                 return false;
8252         }
8253         if (is_type_incomplete(type_left)) {
8254                 errorf(&left->base.pos, "left-hand side '%E' of assignment has incomplete type '%T'",
8255                        left, orig_type_left);
8256                 return false;
8257         }
8258         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8259                 errorf(&left->base.pos, "cannot assign to '%E' because compound type '%T' has read-only fields",
8260                        left, orig_type_left);
8261                 return false;
8262         }
8263
8264         return true;
8265 }
8266
8267 static void semantic_arithmetic_assign(binary_expression_t *expression)
8268 {
8269         expression_t *left            = expression->left;
8270         expression_t *right           = expression->right;
8271         type_t       *orig_type_left  = left->base.type;
8272         type_t       *orig_type_right = right->base.type;
8273
8274         if (!is_valid_assignment_lhs(left))
8275                 return;
8276
8277         type_t *type_left  = skip_typeref(orig_type_left);
8278         type_t *type_right = skip_typeref(orig_type_right);
8279
8280         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8281                 /* TODO: improve error message */
8282                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8283                         errorf(&expression->base.pos, "operation needs arithmetic types");
8284                 }
8285                 return;
8286         }
8287
8288         /* combined instructions are tricky. We can't create an implicit cast on
8289          * the left side, because we need the uncasted form for the store.
8290          * The ast2firm pass has to know that left_type must be right_type
8291          * for the arithmetic operation and create a cast by itself */
8292         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8293         expression->right       = create_implicit_cast(right, arithmetic_type);
8294         expression->base.type   = type_left;
8295 }
8296
8297 static void semantic_divmod_assign(binary_expression_t *expression)
8298 {
8299         semantic_arithmetic_assign(expression);
8300         warn_div_by_zero(expression);
8301 }
8302
8303 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8304 {
8305         expression_t *const left            = expression->left;
8306         expression_t *const right           = expression->right;
8307         type_t       *const orig_type_left  = left->base.type;
8308         type_t       *const orig_type_right = right->base.type;
8309         type_t       *const type_left       = skip_typeref(orig_type_left);
8310         type_t       *const type_right      = skip_typeref(orig_type_right);
8311
8312         if (!is_valid_assignment_lhs(left))
8313                 return;
8314
8315         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8316                 /* combined instructions are tricky. We can't create an implicit cast on
8317                  * the left side, because we need the uncasted form for the store.
8318                  * The ast2firm pass has to know that left_type must be right_type
8319                  * for the arithmetic operation and create a cast by itself */
8320                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8321                 expression->right     = create_implicit_cast(right, arithmetic_type);
8322                 expression->base.type = type_left;
8323         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8324                 check_pointer_arithmetic(&expression->base.pos, type_left,
8325                                          orig_type_left);
8326                 expression->base.type = type_left;
8327         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8328                 errorf(&expression->base.pos,
8329                        "incompatible types '%T' and '%T' in assignment",
8330                        orig_type_left, orig_type_right);
8331         }
8332 }
8333
8334 static void semantic_integer_assign(binary_expression_t *expression)
8335 {
8336         expression_t *left            = expression->left;
8337         expression_t *right           = expression->right;
8338         type_t       *orig_type_left  = left->base.type;
8339         type_t       *orig_type_right = right->base.type;
8340
8341         if (!is_valid_assignment_lhs(left))
8342                 return;
8343
8344         type_t *type_left  = skip_typeref(orig_type_left);
8345         type_t *type_right = skip_typeref(orig_type_right);
8346
8347         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8348                 /* TODO: improve error message */
8349                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8350                         errorf(&expression->base.pos, "operation needs integer types");
8351                 }
8352                 return;
8353         }
8354
8355         /* combined instructions are tricky. We can't create an implicit cast on
8356          * the left side, because we need the uncasted form for the store.
8357          * The ast2firm pass has to know that left_type must be right_type
8358          * for the arithmetic operation and create a cast by itself */
8359         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8360         expression->right       = create_implicit_cast(right, arithmetic_type);
8361         expression->base.type   = type_left;
8362 }
8363
8364 static void semantic_shift_assign(binary_expression_t *expression)
8365 {
8366         expression_t *left           = expression->left;
8367
8368         if (!is_valid_assignment_lhs(left))
8369                 return;
8370
8371         if (!semantic_shift(expression))
8372                 return;
8373
8374         expression->base.type = skip_typeref(left->base.type);
8375 }
8376
8377 static void warn_logical_and_within_or(const expression_t *const expr)
8378 {
8379         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8380                 return;
8381         if (expr->base.parenthesized)
8382                 return;
8383         position_t const *const pos = &expr->base.pos;
8384         warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8385 }
8386
8387 /**
8388  * Check the semantic restrictions of a logical expression.
8389  */
8390 static void semantic_logical_op(binary_expression_t *expression)
8391 {
8392         /* §6.5.13:2  Each of the operands shall have scalar type.
8393          * §6.5.14:2  Each of the operands shall have scalar type. */
8394         semantic_condition(expression->left,   "left operand of logical operator");
8395         semantic_condition(expression->right, "right operand of logical operator");
8396         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8397                 warn_logical_and_within_or(expression->left);
8398                 warn_logical_and_within_or(expression->right);
8399         }
8400         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8401 }
8402
8403 /**
8404  * Check the semantic restrictions of a binary assign expression.
8405  */
8406 static void semantic_binexpr_assign(binary_expression_t *expression)
8407 {
8408         expression_t *left           = expression->left;
8409         type_t       *orig_type_left = left->base.type;
8410
8411         if (!is_valid_assignment_lhs(left))
8412                 return;
8413
8414         assign_error_t error = semantic_assign(orig_type_left, expression->right);
8415         report_assign_error(error, orig_type_left, expression->right,
8416                             "assignment", &left->base.pos);
8417         expression->right = create_implicit_cast(expression->right, orig_type_left);
8418         expression->base.type = orig_type_left;
8419 }
8420
8421 /**
8422  * Determine if the outermost operation (or parts thereof) of the given
8423  * expression has no effect in order to generate a warning about this fact.
8424  * Therefore in some cases this only examines some of the operands of the
8425  * expression (see comments in the function and examples below).
8426  * Examples:
8427  *   f() + 23;    // warning, because + has no effect
8428  *   x || f();    // no warning, because x controls execution of f()
8429  *   x ? y : f(); // warning, because y has no effect
8430  *   (void)x;     // no warning to be able to suppress the warning
8431  * This function can NOT be used for an "expression has definitely no effect"-
8432  * analysis. */
8433 static bool expression_has_effect(const expression_t *const expr)
8434 {
8435         switch (expr->kind) {
8436                 case EXPR_ERROR:                      return true; /* do NOT warn */
8437                 case EXPR_REFERENCE:                  return false;
8438                 case EXPR_ENUM_CONSTANT:              return false;
8439                 case EXPR_LABEL_ADDRESS:              return false;
8440
8441                 /* suppress the warning for microsoft __noop operations */
8442                 case EXPR_LITERAL_MS_NOOP:            return true;
8443                 case EXPR_LITERAL_BOOLEAN:
8444                 case EXPR_LITERAL_CHARACTER:
8445                 case EXPR_LITERAL_INTEGER:
8446                 case EXPR_LITERAL_FLOATINGPOINT:
8447                 case EXPR_STRING_LITERAL:             return false;
8448
8449                 case EXPR_CALL: {
8450                         const call_expression_t *const call = &expr->call;
8451                         if (call->function->kind != EXPR_REFERENCE)
8452                                 return true;
8453
8454                         switch (call->function->reference.entity->function.btk) {
8455                                 /* FIXME: which builtins have no effect? */
8456                                 default:                      return true;
8457                         }
8458                 }
8459
8460                 /* Generate the warning if either the left or right hand side of a
8461                  * conditional expression has no effect */
8462                 case EXPR_CONDITIONAL: {
8463                         conditional_expression_t const *const cond = &expr->conditional;
8464                         expression_t             const *const t    = cond->true_expression;
8465                         return
8466                                 (t == NULL || expression_has_effect(t)) &&
8467                                 expression_has_effect(cond->false_expression);
8468                 }
8469
8470                 case EXPR_SELECT:                     return false;
8471                 case EXPR_ARRAY_ACCESS:               return false;
8472                 case EXPR_SIZEOF:                     return false;
8473                 case EXPR_CLASSIFY_TYPE:              return false;
8474                 case EXPR_ALIGNOF:                    return false;
8475
8476                 case EXPR_FUNCNAME:                   return false;
8477                 case EXPR_BUILTIN_CONSTANT_P:         return false;
8478                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8479                 case EXPR_OFFSETOF:                   return false;
8480                 case EXPR_VA_START:                   return true;
8481                 case EXPR_VA_ARG:                     return true;
8482                 case EXPR_VA_COPY:                    return true;
8483                 case EXPR_STATEMENT:                  return true; // TODO
8484                 case EXPR_COMPOUND_LITERAL:           return false;
8485
8486                 case EXPR_UNARY_NEGATE:               return false;
8487                 case EXPR_UNARY_PLUS:                 return false;
8488                 case EXPR_UNARY_COMPLEMENT:           return false;
8489                 case EXPR_UNARY_NOT:                  return false;
8490                 case EXPR_UNARY_DEREFERENCE:          return false;
8491                 case EXPR_UNARY_TAKE_ADDRESS:         return false;
8492                 case EXPR_UNARY_REAL:                 return false;
8493                 case EXPR_UNARY_IMAG:                 return false;
8494                 case EXPR_UNARY_POSTFIX_INCREMENT:    return true;
8495                 case EXPR_UNARY_POSTFIX_DECREMENT:    return true;
8496                 case EXPR_UNARY_PREFIX_INCREMENT:     return true;
8497                 case EXPR_UNARY_PREFIX_DECREMENT:     return true;
8498
8499                 /* Treat void casts as if they have an effect in order to being able to
8500                  * suppress the warning */
8501                 case EXPR_UNARY_CAST: {
8502                         type_t *const type = skip_typeref(expr->base.type);
8503                         return is_type_void(type);
8504                 }
8505
8506                 case EXPR_UNARY_ASSUME:               return true;
8507                 case EXPR_UNARY_DELETE:               return true;
8508                 case EXPR_UNARY_DELETE_ARRAY:         return true;
8509                 case EXPR_UNARY_THROW:                return true;
8510
8511                 case EXPR_BINARY_ADD:                 return false;
8512                 case EXPR_BINARY_SUB:                 return false;
8513                 case EXPR_BINARY_MUL:                 return false;
8514                 case EXPR_BINARY_DIV:                 return false;
8515                 case EXPR_BINARY_MOD:                 return false;
8516                 case EXPR_BINARY_EQUAL:               return false;
8517                 case EXPR_BINARY_NOTEQUAL:            return false;
8518                 case EXPR_BINARY_LESS:                return false;
8519                 case EXPR_BINARY_LESSEQUAL:           return false;
8520                 case EXPR_BINARY_GREATER:             return false;
8521                 case EXPR_BINARY_GREATEREQUAL:        return false;
8522                 case EXPR_BINARY_BITWISE_AND:         return false;
8523                 case EXPR_BINARY_BITWISE_OR:          return false;
8524                 case EXPR_BINARY_BITWISE_XOR:         return false;
8525                 case EXPR_BINARY_SHIFTLEFT:           return false;
8526                 case EXPR_BINARY_SHIFTRIGHT:          return false;
8527                 case EXPR_BINARY_ASSIGN:              return true;
8528                 case EXPR_BINARY_MUL_ASSIGN:          return true;
8529                 case EXPR_BINARY_DIV_ASSIGN:          return true;
8530                 case EXPR_BINARY_MOD_ASSIGN:          return true;
8531                 case EXPR_BINARY_ADD_ASSIGN:          return true;
8532                 case EXPR_BINARY_SUB_ASSIGN:          return true;
8533                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:    return true;
8534                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:   return true;
8535                 case EXPR_BINARY_BITWISE_AND_ASSIGN:  return true;
8536                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:  return true;
8537                 case EXPR_BINARY_BITWISE_OR_ASSIGN:   return true;
8538
8539                 /* Only examine the right hand side of && and ||, because the left hand
8540                  * side already has the effect of controlling the execution of the right
8541                  * hand side */
8542                 case EXPR_BINARY_LOGICAL_AND:
8543                 case EXPR_BINARY_LOGICAL_OR:
8544                 /* Only examine the right hand side of a comma expression, because the left
8545                  * hand side has a separate warning */
8546                 case EXPR_BINARY_COMMA:
8547                         return expression_has_effect(expr->binary.right);
8548
8549                 case EXPR_BINARY_ISGREATER:           return false;
8550                 case EXPR_BINARY_ISGREATEREQUAL:      return false;
8551                 case EXPR_BINARY_ISLESS:              return false;
8552                 case EXPR_BINARY_ISLESSEQUAL:         return false;
8553                 case EXPR_BINARY_ISLESSGREATER:       return false;
8554                 case EXPR_BINARY_ISUNORDERED:         return false;
8555         }
8556
8557         internal_errorf(HERE, "unexpected expression");
8558 }
8559
8560 static void semantic_comma(binary_expression_t *expression)
8561 {
8562         const expression_t *const left = expression->left;
8563         if (!expression_has_effect(left)) {
8564                 position_t const *const pos = &left->base.pos;
8565                 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8566         }
8567         expression->base.type = expression->right->base.type;
8568 }
8569
8570 /**
8571  * @param prec_r precedence of the right operand
8572  */
8573 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8574 static expression_t *parse_##binexpression_type(expression_t *left)          \
8575 {                                                                            \
8576         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
8577         binexpr->binary.left  = left;                                            \
8578         eat(token_kind);                                                         \
8579                                                                              \
8580         expression_t *right = parse_subexpression(prec_r);                       \
8581                                                                              \
8582         binexpr->binary.right = right;                                           \
8583         sfunc(&binexpr->binary);                                                 \
8584                                                                              \
8585         return binexpr;                                                          \
8586 }
8587
8588 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
8589 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_div)
8590 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_mod)
8591 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
8592 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
8593 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
8594 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
8595 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_relational)
8596 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_relational)
8597 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_relational)
8598 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_relational)
8599 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_equality)
8600 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_equality)
8601 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_integer)
8602 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_integer)
8603 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_integer)
8604 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
8605 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
8606 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
8607 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
8608 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
8609 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
8610 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
8611 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
8612 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_shift_assign)
8613 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_shift_assign)
8614 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
8615 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_integer_assign)
8616 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
8617 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
8618
8619
8620 static expression_t *parse_subexpression(precedence_t precedence)
8621 {
8622         expression_parser_function_t *parser
8623                 = &expression_parsers[token.kind];
8624         expression_t                 *left;
8625
8626         if (parser->parser != NULL) {
8627                 left = parser->parser();
8628         } else {
8629                 left = parse_primary_expression();
8630         }
8631         assert(left != NULL);
8632
8633         while (true) {
8634                 parser = &expression_parsers[token.kind];
8635                 if (parser->infix_parser == NULL)
8636                         break;
8637                 if (parser->infix_precedence < precedence)
8638                         break;
8639
8640                 left = parser->infix_parser(left);
8641
8642                 assert(left != NULL);
8643         }
8644
8645         return left;
8646 }
8647
8648 /**
8649  * Parse an expression.
8650  */
8651 static expression_t *parse_expression(void)
8652 {
8653         return parse_subexpression(PREC_EXPRESSION);
8654 }
8655
8656 /**
8657  * Register a parser for a prefix-like operator.
8658  *
8659  * @param parser      the parser function
8660  * @param token_kind  the token type of the prefix token
8661  */
8662 static void register_expression_parser(parse_expression_function parser,
8663                                        int token_kind)
8664 {
8665         expression_parser_function_t *entry = &expression_parsers[token_kind];
8666
8667         assert(!entry->parser);
8668         entry->parser = parser;
8669 }
8670
8671 /**
8672  * Register a parser for an infix operator with given precedence.
8673  *
8674  * @param parser      the parser function
8675  * @param token_kind  the token type of the infix operator
8676  * @param precedence  the precedence of the operator
8677  */
8678 static void register_infix_parser(parse_expression_infix_function parser,
8679                                   int token_kind, precedence_t precedence)
8680 {
8681         expression_parser_function_t *entry = &expression_parsers[token_kind];
8682
8683         assert(!entry->infix_parser);
8684         entry->infix_parser     = parser;
8685         entry->infix_precedence = precedence;
8686 }
8687
8688 /**
8689  * Initialize the expression parsers.
8690  */
8691 static void init_expression_parsers(void)
8692 {
8693         memset(&expression_parsers, 0, sizeof(expression_parsers));
8694
8695         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
8696         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
8697         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
8698         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
8699         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
8700         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
8701         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
8702         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
8703         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
8704         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
8705         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
8706         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
8707         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
8708         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
8709         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
8710         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
8711         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
8712         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
8713         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8714         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
8715         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
8716         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
8717         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
8718         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
8719         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
8720         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
8721         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
8722         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
8723         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
8724         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
8725         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
8726         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
8727         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
8728         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
8729         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
8730         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
8731         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
8732
8733         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
8734         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
8735         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
8736         register_expression_parser(parse_EXPR_UNARY_COMPLEMENT,       '~');
8737         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
8738         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
8739         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8740         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8741         register_expression_parser(parse_sizeof,                      T_sizeof);
8742         register_expression_parser(parse_alignof,                     T__Alignof);
8743         register_expression_parser(parse_extension,                   T___extension__);
8744         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
8745         register_expression_parser(parse_delete,                      T_delete);
8746         register_expression_parser(parse_throw,                       T_throw);
8747 }
8748
8749 /**
8750  * Parse a asm statement arguments specification.
8751  */
8752 static void parse_asm_arguments(asm_argument_t **anchor, bool const is_out)
8753 {
8754         if (token.kind == T_STRING_LITERAL || token.kind == '[') {
8755                 add_anchor_token(',');
8756                 do {
8757                         asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8758
8759                         add_anchor_token(')');
8760                         add_anchor_token('(');
8761                         add_anchor_token(T_STRING_LITERAL);
8762
8763                         if (accept('[')) {
8764                                 add_anchor_token(']');
8765                                 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8766                                 rem_anchor_token(']');
8767                                 expect(']');
8768                         }
8769
8770                         rem_anchor_token(T_STRING_LITERAL);
8771                         argument->constraints = parse_string_literals("asm argument");
8772                         rem_anchor_token('(');
8773                         expect('(');
8774                         expression_t *expression = parse_expression();
8775                         if (is_out) {
8776                                 /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
8777                                  * change size or type representation (e.g. int -> long is ok, but
8778                                  * int -> float is not) */
8779                                 if (expression->kind == EXPR_UNARY_CAST) {
8780                                         type_t      *const type = expression->base.type;
8781                                         type_kind_t  const kind = type->kind;
8782                                         if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8783                                                 unsigned flags;
8784                                                 unsigned size;
8785                                                 if (kind == TYPE_ATOMIC) {
8786                                                         atomic_type_kind_t const akind = type->atomic.akind;
8787                                                         flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8788                                                         size  = get_atomic_type_size(akind);
8789                                                 } else {
8790                                                         flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8791                                                         size  = get_type_size(type_void_ptr);
8792                                                 }
8793
8794                                                 do {
8795                                                         expression_t *const value      = expression->unary.value;
8796                                                         type_t       *const value_type = value->base.type;
8797                                                         type_kind_t   const value_kind = value_type->kind;
8798
8799                                                         unsigned value_flags;
8800                                                         unsigned value_size;
8801                                                         if (value_kind == TYPE_ATOMIC) {
8802                                                                 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8803                                                                 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8804                                                                 value_size  = get_atomic_type_size(value_akind);
8805                                                         } else if (value_kind == TYPE_POINTER) {
8806                                                                 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8807                                                                 value_size  = get_type_size(type_void_ptr);
8808                                                         } else {
8809                                                                 break;
8810                                                         }
8811
8812                                                         if (value_flags != flags || value_size != size)
8813                                                                 break;
8814
8815                                                         expression = value;
8816                                                 } while (expression->kind == EXPR_UNARY_CAST);
8817                                         }
8818                                 }
8819
8820                                 if (!is_lvalue(expression))
8821                                         errorf(&expression->base.pos,
8822                                                "asm output argument is not an lvalue");
8823
8824                                 if (argument->constraints.begin[0] == '=')
8825                                         determine_lhs_ent(expression, NULL);
8826                                 else
8827                                         mark_vars_read(expression, NULL);
8828                         } else {
8829                                 mark_vars_read(expression, NULL);
8830                         }
8831                         argument->expression = expression;
8832                         rem_anchor_token(')');
8833                         expect(')');
8834
8835                         set_address_taken(expression, true);
8836
8837                         *anchor = argument;
8838                         anchor  = &argument->next;
8839                 } while (accept(','));
8840                 rem_anchor_token(',');
8841         }
8842 }
8843
8844 /**
8845  * Parse a asm statement clobber specification.
8846  */
8847 static void parse_asm_clobbers(asm_clobber_t **anchor)
8848 {
8849         if (token.kind == T_STRING_LITERAL) {
8850                 add_anchor_token(',');
8851                 do {
8852                         asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8853                         clobber->clobber       = parse_string_literals(NULL);
8854
8855                         *anchor = clobber;
8856                         anchor  = &clobber->next;
8857                 } while (accept(','));
8858                 rem_anchor_token(',');
8859         }
8860 }
8861
8862 static void parse_asm_labels(asm_label_t **anchor)
8863 {
8864         if (token.kind == T_IDENTIFIER) {
8865                 add_anchor_token(',');
8866                 do {
8867                         label_t *const label = get_label("while parsing 'asm goto' labels");
8868                         if (label) {
8869                                 asm_label_t *const asm_label = allocate_ast_zero(sizeof(*asm_label));
8870                                 asm_label->label = label;
8871
8872                                 *anchor = asm_label;
8873                                 anchor  = &asm_label->next;
8874                         }
8875                 } while (accept(','));
8876                 rem_anchor_token(',');
8877         }
8878 }
8879
8880 /**
8881  * Parse an asm statement.
8882  */
8883 static statement_t *parse_asm_statement(void)
8884 {
8885         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
8886         asm_statement_t *asm_statement = &statement->asms;
8887
8888         eat(T_asm);
8889         add_anchor_token(')');
8890         add_anchor_token(':');
8891         add_anchor_token(T_STRING_LITERAL);
8892
8893         if (accept(T_volatile))
8894                 asm_statement->is_volatile = true;
8895
8896         bool const asm_goto = accept(T_goto);
8897
8898         expect('(');
8899         rem_anchor_token(T_STRING_LITERAL);
8900         asm_statement->asm_text = parse_string_literals("asm statement");
8901
8902         if (accept(':')) parse_asm_arguments(&asm_statement->outputs, true);
8903         if (accept(':')) parse_asm_arguments(&asm_statement->inputs, false);
8904         if (accept(':')) parse_asm_clobbers( &asm_statement->clobbers);
8905
8906         rem_anchor_token(':');
8907         if (accept(':')) {
8908                 if (!asm_goto)
8909                         warningf(WARN_OTHER, &statement->base.pos, "assembler statement with labels should be 'asm goto'");
8910                 parse_asm_labels(&asm_statement->labels);
8911                 if (asm_statement->labels)
8912                         errorf(&statement->base.pos, "'asm goto' not supported");
8913         } else {
8914                 if (asm_goto)
8915                         warningf(WARN_OTHER, &statement->base.pos, "'asm goto' without labels");
8916         }
8917
8918         rem_anchor_token(')');
8919         expect(')');
8920         expect(';');
8921
8922         if (asm_statement->outputs == NULL) {
8923                 /* GCC: An 'asm' instruction without any output operands will be treated
8924                  * identically to a volatile 'asm' instruction. */
8925                 asm_statement->is_volatile = true;
8926         }
8927
8928         return statement;
8929 }
8930
8931 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8932 {
8933         statement_t *inner_stmt;
8934         switch (token.kind) {
8935                 case '}':
8936                         errorf(&label->base.pos, "%s at end of compound statement", label_kind);
8937                         inner_stmt = create_error_statement();
8938                         break;
8939
8940                 case ';':
8941                         if (label->kind == STATEMENT_LABEL) {
8942                                 /* Eat an empty statement here, to avoid the warning about an empty
8943                                  * statement after a label.  label:; is commonly used to have a label
8944                                  * before a closing brace. */
8945                                 inner_stmt = create_empty_statement();
8946                                 eat(';');
8947                                 break;
8948                         }
8949                         /* FALLTHROUGH */
8950
8951                 default:
8952                         inner_stmt = parse_statement();
8953                         /* ISO/IEC  9899:1999(E) §6.8:1/6.8.2:1  Declarations are no statements */
8954                         /* ISO/IEC 14882:1998(E) §6:1/§6.7       Declarations are statements */
8955                         if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8956                                 errorf(&inner_stmt->base.pos, "declaration after %s", label_kind);
8957                         }
8958                         break;
8959         }
8960         return inner_stmt;
8961 }
8962
8963 /**
8964  * Parse a case statement.
8965  */
8966 static statement_t *parse_case_statement(void)
8967 {
8968         statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8969         position_t  *const pos       = &statement->base.pos;
8970
8971         eat(T_case);
8972         add_anchor_token(':');
8973
8974         expression_t *expression = parse_expression();
8975         type_t *expression_type = expression->base.type;
8976         type_t *skipped         = skip_typeref(expression_type);
8977         if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8978                 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8979                        expression, expression_type);
8980         }
8981
8982         type_t *type = expression_type;
8983         if (current_switch != NULL) {
8984                 type_t *switch_type = current_switch->expression->base.type;
8985                 if (is_type_valid(skip_typeref(switch_type))) {
8986                         expression = create_implicit_cast(expression, switch_type);
8987                 }
8988         }
8989
8990         statement->case_label.expression = expression;
8991         expression_classification_t const expr_class = is_constant_expression(expression);
8992         if (expr_class != EXPR_CLASS_CONSTANT) {
8993                 if (expr_class != EXPR_CLASS_ERROR) {
8994                         errorf(pos, "case label does not reduce to an integer constant");
8995                 }
8996                 statement->case_label.is_bad = true;
8997         } else {
8998                 ir_tarval *val = fold_constant_to_tarval(expression);
8999                 statement->case_label.first_case = val;
9000                 statement->case_label.last_case  = val;
9001         }
9002
9003         if (GNU_MODE) {
9004                 if (accept(T_DOTDOTDOT)) {
9005                         expression_t *end_range = parse_expression();
9006                         expression_type = expression->base.type;
9007                         skipped         = skip_typeref(expression_type);
9008                         if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9009                                 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9010                                            expression, expression_type);
9011                         }
9012
9013                         end_range = create_implicit_cast(end_range, type);
9014                         statement->case_label.end_range = end_range;
9015                         expression_classification_t const end_class = is_constant_expression(end_range);
9016                         if (end_class != EXPR_CLASS_CONSTANT) {
9017                                 if (end_class != EXPR_CLASS_ERROR) {
9018                                         errorf(pos, "case range does not reduce to an integer constant");
9019                                 }
9020                                 statement->case_label.is_bad = true;
9021                         } else {
9022                                 ir_tarval *val = fold_constant_to_tarval(end_range);
9023                                 statement->case_label.last_case = val;
9024
9025                                 if (tarval_cmp(val, statement->case_label.first_case)
9026                                     == ir_relation_less) {
9027                                         statement->case_label.is_empty_range = true;
9028                                         warningf(WARN_OTHER, pos, "empty range specified");
9029                                 }
9030                         }
9031                 }
9032         }
9033
9034         PUSH_PARENT(statement);
9035
9036         rem_anchor_token(':');
9037         expect(':');
9038
9039         if (current_switch != NULL) {
9040                 if (! statement->case_label.is_bad) {
9041                         /* Check for duplicate case values */
9042                         case_label_statement_t *c = &statement->case_label;
9043                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9044                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9045                                         continue;
9046
9047                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9048                                         continue;
9049
9050                                 errorf(pos, "duplicate case value (previously used %P)",
9051                                        &l->base.pos);
9052                                 break;
9053                         }
9054                 }
9055                 /* link all cases into the switch statement */
9056                 if (current_switch->last_case == NULL) {
9057                         current_switch->first_case      = &statement->case_label;
9058                 } else {
9059                         current_switch->last_case->next = &statement->case_label;
9060                 }
9061                 current_switch->last_case = &statement->case_label;
9062         } else {
9063                 errorf(pos, "case label not within a switch statement");
9064         }
9065
9066         statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9067
9068         POP_PARENT();
9069         return statement;
9070 }
9071
9072 /**
9073  * Parse a default statement.
9074  */
9075 static statement_t *parse_default_statement(void)
9076 {
9077         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9078
9079         eat(T_default);
9080
9081         PUSH_PARENT(statement);
9082
9083         expect(':');
9084
9085         if (current_switch != NULL) {
9086                 const case_label_statement_t *def_label = current_switch->default_label;
9087                 if (def_label != NULL) {
9088                         errorf(&statement->base.pos, "multiple default labels in one switch (previous declared %P)", &def_label->base.pos);
9089                 } else {
9090                         current_switch->default_label = &statement->case_label;
9091
9092                         /* link all cases into the switch statement */
9093                         if (current_switch->last_case == NULL) {
9094                                 current_switch->first_case      = &statement->case_label;
9095                         } else {
9096                                 current_switch->last_case->next = &statement->case_label;
9097                         }
9098                         current_switch->last_case = &statement->case_label;
9099                 }
9100         } else {
9101                 errorf(&statement->base.pos,
9102                        "'default' label not within a switch statement");
9103         }
9104
9105         statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9106
9107         POP_PARENT();
9108         return statement;
9109 }
9110
9111 /**
9112  * Parse a label statement.
9113  */
9114 static statement_t *parse_label_statement(void)
9115 {
9116         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9117         label_t     *const label     = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9118         statement->label.label = label;
9119
9120         PUSH_PARENT(statement);
9121
9122         /* if statement is already set then the label is defined twice,
9123          * otherwise it was just mentioned in a goto/local label declaration so far
9124          */
9125         position_t const* const pos = &statement->base.pos;
9126         if (label->statement != NULL) {
9127                 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.pos);
9128         } else {
9129                 label->base.pos  = *pos;
9130                 label->statement = statement;
9131                 label->n_users  += 1;
9132         }
9133
9134         eat(':');
9135
9136         if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9137                 parse_attributes(NULL); // TODO process attributes
9138         }
9139
9140         statement->label.statement = parse_label_inner_statement(statement, "label");
9141
9142         /* remember the labels in a list for later checking */
9143         *label_anchor = &statement->label;
9144         label_anchor  = &statement->label.next;
9145
9146         POP_PARENT();
9147         return statement;
9148 }
9149
9150 static statement_t *parse_inner_statement(void)
9151 {
9152         statement_t *const stmt = parse_statement();
9153         /* ISO/IEC  9899:1999(E) §6.8:1/6.8.2:1  Declarations are no statements */
9154         /* ISO/IEC 14882:1998(E) §6:1/§6.7       Declarations are statements */
9155         if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9156                 errorf(&stmt->base.pos, "declaration as inner statement, use {}");
9157         }
9158         return stmt;
9159 }
9160
9161 /**
9162  * Parse an expression in parentheses and mark its variables as read.
9163  */
9164 static expression_t *parse_condition(void)
9165 {
9166         add_anchor_token(')');
9167         expect('(');
9168         expression_t *const expr = parse_expression();
9169         mark_vars_read(expr, NULL);
9170         rem_anchor_token(')');
9171         expect(')');
9172         return expr;
9173 }
9174
9175 /**
9176  * Parse an if statement.
9177  */
9178 static statement_t *parse_if(void)
9179 {
9180         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9181
9182         eat(T_if);
9183
9184         PUSH_PARENT(statement);
9185         PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9186
9187         add_anchor_token(T_else);
9188
9189         expression_t *const expr = parse_condition();
9190         statement->ifs.condition = expr;
9191         /* §6.8.4.1:1  The controlling expression of an if statement shall have
9192          *             scalar type. */
9193         semantic_condition(expr, "condition of 'if'-statment");
9194
9195         statement_t *const true_stmt = parse_inner_statement();
9196         statement->ifs.true_statement = true_stmt;
9197         rem_anchor_token(T_else);
9198
9199         if (true_stmt->kind == STATEMENT_EMPTY) {
9200                 warningf(WARN_EMPTY_BODY, HERE,
9201                         "suggest braces around empty body in an ‘if’ statement");
9202         }
9203
9204         if (accept(T_else)) {
9205                 statement->ifs.false_statement = parse_inner_statement();
9206
9207                 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9208                         warningf(WARN_EMPTY_BODY, HERE,
9209                                         "suggest braces around empty body in an ‘if’ statement");
9210                 }
9211         } else if (true_stmt->kind == STATEMENT_IF &&
9212                         true_stmt->ifs.false_statement != NULL) {
9213                 position_t const *const pos = &true_stmt->base.pos;
9214                 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9215         }
9216
9217         POP_SCOPE();
9218         POP_PARENT();
9219         return statement;
9220 }
9221
9222 /**
9223  * Check that all enums are handled in a switch.
9224  *
9225  * @param statement  the switch statement to check
9226  */
9227 static void check_enum_cases(const switch_statement_t *statement)
9228 {
9229         if (!is_warn_on(WARN_SWITCH_ENUM))
9230                 return;
9231         type_t *type = skip_typeref(statement->expression->base.type);
9232         if (! is_type_enum(type))
9233                 return;
9234         enum_type_t *enumt = &type->enumt;
9235
9236         /* if we have a default, no warnings */
9237         if (statement->default_label != NULL)
9238                 return;
9239
9240         determine_enum_values(enumt);
9241
9242         /* FIXME: calculation of value should be done while parsing */
9243         /* TODO: quadratic algorithm here. Change to an n log n one */
9244         const entity_t *entry = enumt->enume->base.next;
9245         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9246              entry = entry->base.next) {
9247                 ir_tarval *value = entry->enum_value.tv;
9248                 bool       found = false;
9249                 for (const case_label_statement_t *l = statement->first_case; l != NULL;
9250                      l = l->next) {
9251                         if (l->expression == NULL)
9252                                 continue;
9253                         if (l->first_case == l->last_case && l->first_case != value)
9254                                 continue;
9255                         if ((tarval_cmp(l->first_case, value) & ir_relation_less_equal)
9256                          && (tarval_cmp(value, l->last_case) & ir_relation_less_equal)) {
9257                                 found = true;
9258                                 break;
9259                         }
9260                 }
9261                 if (!found) {
9262                         position_t const *const pos = &statement->base.pos;
9263                         warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9264                 }
9265         }
9266 }
9267
9268 /**
9269  * Parse a switch statement.
9270  */
9271 static statement_t *parse_switch(void)
9272 {
9273         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9274
9275         eat(T_switch);
9276
9277         PUSH_PARENT(statement);
9278         PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9279
9280         expression_t *const expr = parse_condition();
9281         type_t       *      type = skip_typeref(expr->base.type);
9282         if (is_type_integer(type)) {
9283                 type = promote_integer(type);
9284                 if (get_akind_rank(get_arithmetic_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9285                         warningf(WARN_TRADITIONAL, &expr->base.pos,
9286                                  "'%T' switch expression not converted to '%T' in ISO C",
9287                                  type, type_int);
9288                 }
9289         } else if (is_type_valid(type)) {
9290                 errorf(&expr->base.pos, "switch quantity is not an integer, but '%T'",
9291                        type);
9292                 type = type_error_type;
9293         }
9294         statement->switchs.expression = create_implicit_cast(expr, type);
9295
9296         switch_statement_t *rem = current_switch;
9297         current_switch          = &statement->switchs;
9298         statement->switchs.body = parse_inner_statement();
9299         current_switch          = rem;
9300
9301         if (statement->switchs.default_label == NULL) {
9302                 warningf(WARN_SWITCH_DEFAULT, &statement->base.pos, "switch has no default case");
9303         }
9304         check_enum_cases(&statement->switchs);
9305
9306         POP_SCOPE();
9307         POP_PARENT();
9308         return statement;
9309 }
9310
9311 static statement_t *parse_loop_body(statement_t *const loop)
9312 {
9313         statement_t *const rem = current_loop;
9314         current_loop = loop;
9315
9316         statement_t *const body = parse_inner_statement();
9317
9318         current_loop = rem;
9319         return body;
9320 }
9321
9322 /**
9323  * Parse a while statement.
9324  */
9325 static statement_t *parse_while(void)
9326 {
9327         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9328
9329         eat(T_while);
9330
9331         PUSH_PARENT(statement);
9332         PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9333
9334         expression_t *const cond = parse_condition();
9335         statement->fors.condition = cond;
9336         /* §6.8.5:2    The controlling expression of an iteration statement shall
9337          *             have scalar type. */
9338         semantic_condition(cond, "condition of 'while'-statement");
9339
9340         statement->fors.body = parse_loop_body(statement);
9341
9342         POP_SCOPE();
9343         POP_PARENT();
9344         return statement;
9345 }
9346
9347 /**
9348  * Parse a do statement.
9349  */
9350 static statement_t *parse_do(void)
9351 {
9352         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9353
9354         eat(T_do);
9355
9356         PUSH_PARENT(statement);
9357         PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9358
9359         add_anchor_token(T_while);
9360         statement->do_while.body = parse_loop_body(statement);
9361         rem_anchor_token(T_while);
9362
9363         expect(T_while);
9364         expression_t *const cond = parse_condition();
9365         statement->do_while.condition = cond;
9366         /* §6.8.5:2    The controlling expression of an iteration statement shall
9367          *             have scalar type. */
9368         semantic_condition(cond, "condition of 'do-while'-statement");
9369         expect(';');
9370
9371         POP_SCOPE();
9372         POP_PARENT();
9373         return statement;
9374 }
9375
9376 /**
9377  * Parse a for statement.
9378  */
9379 static statement_t *parse_for(void)
9380 {
9381         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9382
9383         eat(T_for);
9384
9385         PUSH_PARENT(statement);
9386         PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9387
9388         add_anchor_token(')');
9389         expect('(');
9390
9391         PUSH_EXTENSION();
9392
9393         if (accept(';')) {
9394         } else if (is_declaration_specifier(&token)) {
9395                 parse_declaration(record_entity, DECL_FLAGS_NONE);
9396         } else {
9397                 add_anchor_token(';');
9398                 expression_t *const init = parse_expression();
9399                 statement->fors.initialisation = init;
9400                 mark_vars_read(init, ENT_ANY);
9401                 if (!expression_has_effect(init)) {
9402                         warningf(WARN_UNUSED_VALUE, &init->base.pos, "initialisation of 'for'-statement has no effect");
9403                 }
9404                 rem_anchor_token(';');
9405                 expect(';');
9406         }
9407
9408         POP_EXTENSION();
9409
9410         if (token.kind != ';') {
9411                 add_anchor_token(';');
9412                 expression_t *const cond = parse_expression();
9413                 statement->fors.condition = cond;
9414                 /* §6.8.5:2    The controlling expression of an iteration statement
9415                  *             shall have scalar type. */
9416                 semantic_condition(cond, "condition of 'for'-statement");
9417                 mark_vars_read(cond, NULL);
9418                 rem_anchor_token(';');
9419         }
9420         expect(';');
9421         if (token.kind != ')') {
9422                 expression_t *const step = parse_expression();
9423                 statement->fors.step = step;
9424                 mark_vars_read(step, ENT_ANY);
9425                 if (!expression_has_effect(step)) {
9426                         warningf(WARN_UNUSED_VALUE, &step->base.pos, "step of 'for'-statement has no effect");
9427                 }
9428         }
9429         rem_anchor_token(')');
9430         expect(')');
9431         statement->fors.body = parse_loop_body(statement);
9432
9433         POP_SCOPE();
9434         POP_PARENT();
9435         return statement;
9436 }
9437
9438 /**
9439  * Parse a goto statement.
9440  */
9441 static statement_t *parse_goto(void)
9442 {
9443         statement_t *statement;
9444         if (GNU_MODE && look_ahead(1)->kind == '*') {
9445                 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9446                 eat(T_goto);
9447                 eat('*');
9448
9449                 expression_t *expression = parse_expression();
9450                 mark_vars_read(expression, NULL);
9451
9452                 /* Argh: although documentation says the expression must be of type void*,
9453                  * gcc accepts anything that can be casted into void* without error */
9454                 type_t *type = expression->base.type;
9455
9456                 if (type != type_error_type) {
9457                         if (!is_type_pointer(type) && !is_type_integer(type)) {
9458                                 errorf(&expression->base.pos, "cannot convert to a pointer type");
9459                         } else if (type != type_void_ptr) {
9460                                 warningf(WARN_OTHER, &expression->base.pos, "type of computed goto expression should be 'void*' not '%T'", type);
9461                         }
9462                         expression = create_implicit_cast(expression, type_void_ptr);
9463                 }
9464
9465                 statement->computed_goto.expression = expression;
9466         } else {
9467                 statement = allocate_statement_zero(STATEMENT_GOTO);
9468                 eat(T_goto);
9469
9470                 label_t *const label = get_label("while parsing goto");
9471                 if (label) {
9472                         label->n_users        += 1;
9473                         label->used            = true;
9474                         statement->gotos.label = label;
9475
9476                         /* remember the goto's in a list for later checking */
9477                         *goto_anchor = &statement->gotos;
9478                         goto_anchor  = &statement->gotos.next;
9479                 } else {
9480                         statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_position)->label;
9481                 }
9482         }
9483
9484         expect(';');
9485         return statement;
9486 }
9487
9488 /**
9489  * Parse a continue statement.
9490  */
9491 static statement_t *parse_continue(void)
9492 {
9493         if (current_loop == NULL) {
9494                 errorf(HERE, "continue statement not within loop");
9495         }
9496
9497         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9498
9499         eat(T_continue);
9500         expect(';');
9501         return statement;
9502 }
9503
9504 /**
9505  * Parse a break statement.
9506  */
9507 static statement_t *parse_break(void)
9508 {
9509         if (current_switch == NULL && current_loop == NULL) {
9510                 errorf(HERE, "break statement not within loop or switch");
9511         }
9512
9513         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9514
9515         eat(T_break);
9516         expect(';');
9517         return statement;
9518 }
9519
9520 /**
9521  * Parse a __leave statement.
9522  */
9523 static statement_t *parse_leave_statement(void)
9524 {
9525         if (current_try == NULL) {
9526                 errorf(HERE, "__leave statement not within __try");
9527         }
9528
9529         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9530
9531         eat(T___leave);
9532         expect(';');
9533         return statement;
9534 }
9535
9536 /**
9537  * Check if a given entity represents a local variable.
9538  */
9539 static bool is_local_variable(const entity_t *entity)
9540 {
9541         if (entity->kind != ENTITY_VARIABLE)
9542                 return false;
9543
9544         switch ((storage_class_tag_t) entity->declaration.storage_class) {
9545         case STORAGE_CLASS_AUTO:
9546         case STORAGE_CLASS_REGISTER: {
9547                 const type_t *type = skip_typeref(entity->declaration.type);
9548                 if (is_type_function(type)) {
9549                         return false;
9550                 } else {
9551                         return true;
9552                 }
9553         }
9554         default:
9555                 return false;
9556         }
9557 }
9558
9559 /**
9560  * Check if a given expression represents a local variable.
9561  */
9562 static bool expression_is_local_variable(const expression_t *expression)
9563 {
9564         if (expression->base.kind != EXPR_REFERENCE) {
9565                 return false;
9566         }
9567         const entity_t *entity = expression->reference.entity;
9568         return is_local_variable(entity);
9569 }
9570
9571 static void err_or_warn(position_t const *const pos, char const *const msg)
9572 {
9573         if (c_mode & _CXX || strict_mode) {
9574                 errorf(pos, msg);
9575         } else {
9576                 warningf(WARN_OTHER, pos, msg);
9577         }
9578 }
9579
9580 /**
9581  * Parse a return statement.
9582  */
9583 static statement_t *parse_return(void)
9584 {
9585         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9586         eat(T_return);
9587
9588         expression_t *return_value = NULL;
9589         if (token.kind != ';') {
9590                 return_value = parse_expression();
9591                 mark_vars_read(return_value, NULL);
9592         }
9593
9594         const type_t *const func_type = skip_typeref(current_function->base.type);
9595         assert(is_type_function(func_type));
9596         type_t *const return_type = skip_typeref(func_type->function.return_type);
9597
9598         position_t const *const pos = &statement->base.pos;
9599         if (return_value != NULL) {
9600                 type_t *return_value_type = skip_typeref(return_value->base.type);
9601
9602                 if (is_type_void(return_type)) {
9603                         if (!is_type_void(return_value_type)) {
9604                                 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9605                                 /* Only warn in C mode, because GCC does the same */
9606                                 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9607                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9608                                 /* Only warn in C mode, because GCC does the same */
9609                                 err_or_warn(pos, "'return' with expression in function returning 'void'");
9610                         }
9611                 } else {
9612                         assign_error_t error = semantic_assign(return_type, return_value);
9613                         report_assign_error(error, return_type, return_value, "'return'",
9614                                             pos);
9615                 }
9616                 return_value = create_implicit_cast(return_value, return_type);
9617                 /* check for returning address of a local var */
9618                 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9619                         const expression_t *expression = return_value->unary.value;
9620                         if (expression_is_local_variable(expression)) {
9621                                 warningf(WARN_OTHER, pos, "function returns address of local variable");
9622                         }
9623                 }
9624         } else if (!is_type_void(return_type)) {
9625                 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9626                 err_or_warn(pos, "'return' without value, in function returning non-void");
9627         }
9628         statement->returns.value = return_value;
9629
9630         expect(';');
9631         return statement;
9632 }
9633
9634 /**
9635  * Parse a declaration statement.
9636  */
9637 static statement_t *parse_declaration_statement(void)
9638 {
9639         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9640
9641         entity_t *before = current_scope->last_entity;
9642         if (GNU_MODE) {
9643                 parse_external_declaration();
9644         } else {
9645                 parse_declaration(record_entity, DECL_FLAGS_NONE);
9646         }
9647
9648         declaration_statement_t *const decl  = &statement->declaration;
9649         entity_t                *const begin =
9650                 before != NULL ? before->base.next : current_scope->entities;
9651         decl->declarations_begin = begin;
9652         decl->declarations_end   = begin != NULL ? current_scope->last_entity : NULL;
9653
9654         return statement;
9655 }
9656
9657 /**
9658  * Parse an expression statement, i.e. expr ';'.
9659  */
9660 static statement_t *parse_expression_statement(void)
9661 {
9662         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9663
9664         expression_t *const expr         = parse_expression();
9665         statement->expression.expression = expr;
9666         mark_vars_read(expr, ENT_ANY);
9667
9668         expect(';');
9669         return statement;
9670 }
9671
9672 /**
9673  * Parse a microsoft __try { } __finally { } or
9674  * __try{ } __except() { }
9675  */
9676 static statement_t *parse_ms_try_statment(void)
9677 {
9678         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9679         eat(T___try);
9680
9681         PUSH_PARENT(statement);
9682
9683         ms_try_statement_t *rem = current_try;
9684         current_try = &statement->ms_try;
9685         statement->ms_try.try_statement = parse_compound_statement(false);
9686         current_try = rem;
9687
9688         POP_PARENT();
9689
9690         if (accept(T___except)) {
9691                 expression_t *const expr = parse_condition();
9692                 type_t       *      type = skip_typeref(expr->base.type);
9693                 if (is_type_integer(type)) {
9694                         type = promote_integer(type);
9695                 } else if (is_type_valid(type)) {
9696                         errorf(&expr->base.pos,
9697                                "__expect expression is not an integer, but '%T'", type);
9698                         type = type_error_type;
9699                 }
9700                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9701         } else if (!accept(T__finally)) {
9702                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9703         }
9704         statement->ms_try.final_statement = parse_compound_statement(false);
9705         return statement;
9706 }
9707
9708 static statement_t *parse_empty_statement(void)
9709 {
9710         warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9711         statement_t *const statement = create_empty_statement();
9712         eat(';');
9713         return statement;
9714 }
9715
9716 static statement_t *parse_local_label_declaration(void)
9717 {
9718         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9719
9720         eat(T___label__);
9721
9722         entity_t *begin   = NULL;
9723         entity_t *end     = NULL;
9724         entity_t **anchor = &begin;
9725         add_anchor_token(';');
9726         add_anchor_token(',');
9727         do {
9728                 position_t pos;
9729                 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9730                 if (symbol) {
9731                         entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9732                         if (entity != NULL && entity->base.parent_scope == current_scope) {
9733                                 position_t const *const ppos = &entity->base.pos;
9734                                 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9735                         } else {
9736                                 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9737                                 entity->base.parent_scope = current_scope;
9738
9739                                 *anchor = entity;
9740                                 anchor  = &entity->base.next;
9741                                 end     = entity;
9742
9743                                 environment_push(entity);
9744                         }
9745                 }
9746         } while (accept(','));
9747         rem_anchor_token(',');
9748         rem_anchor_token(';');
9749         expect(';');
9750         statement->declaration.declarations_begin = begin;
9751         statement->declaration.declarations_end   = end;
9752         return statement;
9753 }
9754
9755 static void parse_namespace_definition(void)
9756 {
9757         eat(T_namespace);
9758
9759         entity_t *entity = NULL;
9760         symbol_t *symbol = NULL;
9761
9762         if (token.kind == T_IDENTIFIER) {
9763                 symbol = token.base.symbol;
9764                 entity = get_entity(symbol, NAMESPACE_NORMAL);
9765                 if (entity && entity->kind != ENTITY_NAMESPACE) {
9766                         entity = NULL;
9767                         if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9768                                 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9769                         }
9770                 }
9771                 eat(T_IDENTIFIER);
9772         }
9773
9774         if (entity == NULL) {
9775                 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9776                 entity->base.parent_scope = current_scope;
9777         }
9778
9779         if (token.kind == '=') {
9780                 /* TODO: parse namespace alias */
9781                 panic("namespace alias definition not supported yet");
9782         }
9783
9784         environment_push(entity);
9785         append_entity(current_scope, entity);
9786
9787         PUSH_SCOPE(&entity->namespacee.members);
9788         PUSH_CURRENT_ENTITY(entity);
9789
9790         add_anchor_token('}');
9791         expect('{');
9792         parse_externals();
9793         rem_anchor_token('}');
9794         expect('}');
9795
9796         POP_CURRENT_ENTITY();
9797         POP_SCOPE();
9798 }
9799
9800 /**
9801  * Parse a statement.
9802  * There's also parse_statement() which additionally checks for
9803  * "statement has no effect" warnings
9804  */
9805 static statement_t *intern_parse_statement(void)
9806 {
9807         /* declaration or statement */
9808         statement_t *statement;
9809         switch (token.kind) {
9810         case T_IDENTIFIER: {
9811                 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9812                 if (la1_type == ':') {
9813                         statement = parse_label_statement();
9814                 } else if (is_typedef_symbol(token.base.symbol)) {
9815                         statement = parse_declaration_statement();
9816                 } else {
9817                         /* it's an identifier, the grammar says this must be an
9818                          * expression statement. However it is common that users mistype
9819                          * declaration types, so we guess a bit here to improve robustness
9820                          * for incorrect programs */
9821                         switch (la1_type) {
9822                         case '&':
9823                         case '*':
9824                                 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9825                         default:
9826                                         statement = parse_expression_statement();
9827                                 } else {
9828                         DECLARATION_START
9829                         case T_IDENTIFIER:
9830                                         statement = parse_declaration_statement();
9831                                 }
9832                                 break;
9833                         }
9834                 }
9835                 break;
9836         }
9837
9838         case T___extension__: {
9839                 /* This can be a prefix to a declaration or an expression statement.
9840                  * We simply eat it now and parse the rest with tail recursion. */
9841                 PUSH_EXTENSION();
9842                 statement = intern_parse_statement();
9843                 POP_EXTENSION();
9844                 break;
9845         }
9846
9847         DECLARATION_START
9848                 statement = parse_declaration_statement();
9849                 break;
9850
9851         case T___label__:
9852                 statement = parse_local_label_declaration();
9853                 break;
9854
9855         case ';':         statement = parse_empty_statement();         break;
9856         case '{':         statement = parse_compound_statement(false); break;
9857         case T___leave:   statement = parse_leave_statement();         break;
9858         case T___try:     statement = parse_ms_try_statment();         break;
9859         case T_asm:       statement = parse_asm_statement();           break;
9860         case T_break:     statement = parse_break();                   break;
9861         case T_case:      statement = parse_case_statement();          break;
9862         case T_continue:  statement = parse_continue();                break;
9863         case T_default:   statement = parse_default_statement();       break;
9864         case T_do:        statement = parse_do();                      break;
9865         case T_for:       statement = parse_for();                     break;
9866         case T_goto:      statement = parse_goto();                    break;
9867         case T_if:        statement = parse_if();                      break;
9868         case T_return:    statement = parse_return();                  break;
9869         case T_switch:    statement = parse_switch();                  break;
9870         case T_while:     statement = parse_while();                   break;
9871
9872         EXPRESSION_START
9873                 statement = parse_expression_statement();
9874                 break;
9875
9876         default:
9877                 errorf(HERE, "unexpected token %K while parsing statement", &token);
9878                 statement = create_error_statement();
9879                 eat_until_anchor();
9880                 break;
9881         }
9882
9883         return statement;
9884 }
9885
9886 /**
9887  * parse a statement and emits "statement has no effect" warning if needed
9888  * (This is really a wrapper around intern_parse_statement with check for 1
9889  *  single warning. It is needed, because for statement expressions we have
9890  *  to avoid the warning on the last statement)
9891  */
9892 static statement_t *parse_statement(void)
9893 {
9894         statement_t *statement = intern_parse_statement();
9895
9896         if (statement->kind == STATEMENT_EXPRESSION) {
9897                 expression_t *expression = statement->expression.expression;
9898                 if (!expression_has_effect(expression)) {
9899                         warningf(WARN_UNUSED_VALUE, &expression->base.pos,
9900                                  "statement has no effect");
9901                 }
9902         }
9903
9904         return statement;
9905 }
9906
9907 /**
9908  * Parse a compound statement.
9909  */
9910 static statement_t *parse_compound_statement(bool inside_expression_statement)
9911 {
9912         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9913
9914         PUSH_PARENT(statement);
9915         PUSH_SCOPE(&statement->compound.scope);
9916
9917         eat('{');
9918         add_anchor_token('}');
9919         /* tokens, which can start a statement */
9920         /* TODO MS, __builtin_FOO */
9921         add_anchor_token('!');
9922         add_anchor_token('&');
9923         add_anchor_token('(');
9924         add_anchor_token('*');
9925         add_anchor_token('+');
9926         add_anchor_token('-');
9927         add_anchor_token(';');
9928         add_anchor_token('{');
9929         add_anchor_token('~');
9930         add_anchor_token(T_CHARACTER_CONSTANT);
9931         add_anchor_token(T_COLONCOLON);
9932         add_anchor_token(T_IDENTIFIER);
9933         add_anchor_token(T_MINUSMINUS);
9934         add_anchor_token(T_NUMBER);
9935         add_anchor_token(T_PLUSPLUS);
9936         add_anchor_token(T_STRING_LITERAL);
9937         add_anchor_token(T__Alignof);
9938         add_anchor_token(T__Bool);
9939         add_anchor_token(T__Complex);
9940         add_anchor_token(T__Imaginary);
9941         add_anchor_token(T__Thread_local);
9942         add_anchor_token(T___PRETTY_FUNCTION__);
9943         add_anchor_token(T___attribute__);
9944         add_anchor_token(T___builtin_va_start);
9945         add_anchor_token(T___extension__);
9946         add_anchor_token(T___func__);
9947         add_anchor_token(T___imag__);
9948         add_anchor_token(T___label__);
9949         add_anchor_token(T___real__);
9950         add_anchor_token(T_asm);
9951         add_anchor_token(T_auto);
9952         add_anchor_token(T_bool);
9953         add_anchor_token(T_break);
9954         add_anchor_token(T_case);
9955         add_anchor_token(T_char);
9956         add_anchor_token(T_class);
9957         add_anchor_token(T_const);
9958         add_anchor_token(T_const_cast);
9959         add_anchor_token(T_continue);
9960         add_anchor_token(T_default);
9961         add_anchor_token(T_delete);
9962         add_anchor_token(T_double);
9963         add_anchor_token(T_do);
9964         add_anchor_token(T_dynamic_cast);
9965         add_anchor_token(T_enum);
9966         add_anchor_token(T_extern);
9967         add_anchor_token(T_false);
9968         add_anchor_token(T_float);
9969         add_anchor_token(T_for);
9970         add_anchor_token(T_goto);
9971         add_anchor_token(T_if);
9972         add_anchor_token(T_inline);
9973         add_anchor_token(T_int);
9974         add_anchor_token(T_long);
9975         add_anchor_token(T_new);
9976         add_anchor_token(T_operator);
9977         add_anchor_token(T_register);
9978         add_anchor_token(T_reinterpret_cast);
9979         add_anchor_token(T_restrict);
9980         add_anchor_token(T_return);
9981         add_anchor_token(T_short);
9982         add_anchor_token(T_signed);
9983         add_anchor_token(T_sizeof);
9984         add_anchor_token(T_static);
9985         add_anchor_token(T_static_cast);
9986         add_anchor_token(T_struct);
9987         add_anchor_token(T_switch);
9988         add_anchor_token(T_template);
9989         add_anchor_token(T_this);
9990         add_anchor_token(T_throw);
9991         add_anchor_token(T_true);
9992         add_anchor_token(T_try);
9993         add_anchor_token(T_typedef);
9994         add_anchor_token(T_typeid);
9995         add_anchor_token(T_typename);
9996         add_anchor_token(T_typeof);
9997         add_anchor_token(T_union);
9998         add_anchor_token(T_unsigned);
9999         add_anchor_token(T_using);
10000         add_anchor_token(T_void);
10001         add_anchor_token(T_volatile);
10002         add_anchor_token(T_wchar_t);
10003         add_anchor_token(T_while);
10004
10005         statement_t **anchor            = &statement->compound.statements;
10006         bool          only_decls_so_far = true;
10007         while (token.kind != '}' && token.kind != T_EOF) {
10008                 statement_t *sub_statement = intern_parse_statement();
10009                 if (sub_statement->kind == STATEMENT_ERROR) {
10010                         break;
10011                 }
10012
10013                 if (sub_statement->kind != STATEMENT_DECLARATION) {
10014                         only_decls_so_far = false;
10015                 } else if (!only_decls_so_far) {
10016                         position_t const *const pos = &sub_statement->base.pos;
10017                         warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10018                 }
10019
10020                 *anchor = sub_statement;
10021                 anchor  = &sub_statement->base.next;
10022         }
10023         expect('}');
10024
10025         /* look over all statements again to produce no effect warnings */
10026         if (is_warn_on(WARN_UNUSED_VALUE)) {
10027                 statement_t *sub_statement = statement->compound.statements;
10028                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10029                         if (sub_statement->kind != STATEMENT_EXPRESSION)
10030                                 continue;
10031                         /* don't emit a warning for the last expression in an expression
10032                          * statement as it has always an effect */
10033                         if (inside_expression_statement && sub_statement->base.next == NULL)
10034                                 continue;
10035
10036                         expression_t *expression = sub_statement->expression.expression;
10037                         if (!expression_has_effect(expression)) {
10038                                 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
10039                                          "statement has no effect");
10040                         }
10041                 }
10042         }
10043
10044         rem_anchor_token(T_while);
10045         rem_anchor_token(T_wchar_t);
10046         rem_anchor_token(T_volatile);
10047         rem_anchor_token(T_void);
10048         rem_anchor_token(T_using);
10049         rem_anchor_token(T_unsigned);
10050         rem_anchor_token(T_union);
10051         rem_anchor_token(T_typeof);
10052         rem_anchor_token(T_typename);
10053         rem_anchor_token(T_typeid);
10054         rem_anchor_token(T_typedef);
10055         rem_anchor_token(T_try);
10056         rem_anchor_token(T_true);
10057         rem_anchor_token(T_throw);
10058         rem_anchor_token(T_this);
10059         rem_anchor_token(T_template);
10060         rem_anchor_token(T_switch);
10061         rem_anchor_token(T_struct);
10062         rem_anchor_token(T_static_cast);
10063         rem_anchor_token(T_static);
10064         rem_anchor_token(T_sizeof);
10065         rem_anchor_token(T_signed);
10066         rem_anchor_token(T_short);
10067         rem_anchor_token(T_return);
10068         rem_anchor_token(T_restrict);
10069         rem_anchor_token(T_reinterpret_cast);
10070         rem_anchor_token(T_register);
10071         rem_anchor_token(T_operator);
10072         rem_anchor_token(T_new);
10073         rem_anchor_token(T_long);
10074         rem_anchor_token(T_int);
10075         rem_anchor_token(T_inline);
10076         rem_anchor_token(T_if);
10077         rem_anchor_token(T_goto);
10078         rem_anchor_token(T_for);
10079         rem_anchor_token(T_float);
10080         rem_anchor_token(T_false);
10081         rem_anchor_token(T_extern);
10082         rem_anchor_token(T_enum);
10083         rem_anchor_token(T_dynamic_cast);
10084         rem_anchor_token(T_do);
10085         rem_anchor_token(T_double);
10086         rem_anchor_token(T_delete);
10087         rem_anchor_token(T_default);
10088         rem_anchor_token(T_continue);
10089         rem_anchor_token(T_const_cast);
10090         rem_anchor_token(T_const);
10091         rem_anchor_token(T_class);
10092         rem_anchor_token(T_char);
10093         rem_anchor_token(T_case);
10094         rem_anchor_token(T_break);
10095         rem_anchor_token(T_bool);
10096         rem_anchor_token(T_auto);
10097         rem_anchor_token(T_asm);
10098         rem_anchor_token(T___real__);
10099         rem_anchor_token(T___label__);
10100         rem_anchor_token(T___imag__);
10101         rem_anchor_token(T___func__);
10102         rem_anchor_token(T___extension__);
10103         rem_anchor_token(T___builtin_va_start);
10104         rem_anchor_token(T___attribute__);
10105         rem_anchor_token(T___PRETTY_FUNCTION__);
10106         rem_anchor_token(T__Thread_local);
10107         rem_anchor_token(T__Imaginary);
10108         rem_anchor_token(T__Complex);
10109         rem_anchor_token(T__Bool);
10110         rem_anchor_token(T__Alignof);
10111         rem_anchor_token(T_STRING_LITERAL);
10112         rem_anchor_token(T_PLUSPLUS);
10113         rem_anchor_token(T_NUMBER);
10114         rem_anchor_token(T_MINUSMINUS);
10115         rem_anchor_token(T_IDENTIFIER);
10116         rem_anchor_token(T_COLONCOLON);
10117         rem_anchor_token(T_CHARACTER_CONSTANT);
10118         rem_anchor_token('~');
10119         rem_anchor_token('{');
10120         rem_anchor_token(';');
10121         rem_anchor_token('-');
10122         rem_anchor_token('+');
10123         rem_anchor_token('*');
10124         rem_anchor_token('(');
10125         rem_anchor_token('&');
10126         rem_anchor_token('!');
10127         rem_anchor_token('}');
10128
10129         POP_SCOPE();
10130         POP_PARENT();
10131         return statement;
10132 }
10133
10134 /**
10135  * Check for unused global static functions and variables
10136  */
10137 static void check_unused_globals(void)
10138 {
10139         if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10140                 return;
10141
10142         for (const entity_t *entity = file_scope->entities; entity != NULL;
10143              entity = entity->base.next) {
10144                 if (!is_declaration(entity))
10145                         continue;
10146
10147                 const declaration_t *declaration = &entity->declaration;
10148                 if (declaration->used                  ||
10149                     declaration->modifiers & DM_UNUSED ||
10150                     declaration->modifiers & DM_USED   ||
10151                     declaration->storage_class != STORAGE_CLASS_STATIC)
10152                         continue;
10153
10154                 warning_t   why;
10155                 char const *s;
10156                 if (entity->kind == ENTITY_FUNCTION) {
10157                         /* inhibit warning for static inline functions */
10158                         if (entity->function.is_inline)
10159                                 continue;
10160
10161                         why = WARN_UNUSED_FUNCTION;
10162                         s   = entity->function.body != NULL ? "defined" : "declared";
10163                 } else {
10164                         why = WARN_UNUSED_VARIABLE;
10165                         s   = "defined";
10166                 }
10167
10168                 warningf(why, &declaration->base.pos, "'%#N' %s but not used", entity, s);
10169         }
10170 }
10171
10172 static void parse_global_asm(void)
10173 {
10174         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10175
10176         eat(T_asm);
10177         add_anchor_token(';');
10178         add_anchor_token(')');
10179         add_anchor_token(T_STRING_LITERAL);
10180         expect('(');
10181
10182         rem_anchor_token(T_STRING_LITERAL);
10183         statement->asms.asm_text = parse_string_literals("global asm");
10184         statement->base.next     = unit->global_asm;
10185         unit->global_asm         = statement;
10186
10187         rem_anchor_token(')');
10188         expect(')');
10189         rem_anchor_token(';');
10190         expect(';');
10191 }
10192
10193 static void parse_linkage_specification(void)
10194 {
10195         eat(T_extern);
10196
10197         position_t  const pos     = *HERE;
10198         char const *const linkage = parse_string_literals(NULL).begin;
10199
10200         linkage_kind_t old_linkage = current_linkage;
10201         linkage_kind_t new_linkage;
10202         if (streq(linkage, "C")) {
10203                 new_linkage = LINKAGE_C;
10204         } else if (streq(linkage, "C++")) {
10205                 new_linkage = LINKAGE_CXX;
10206         } else {
10207                 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10208                 new_linkage = LINKAGE_C;
10209         }
10210         current_linkage = new_linkage;
10211
10212         if (accept('{')) {
10213                 parse_externals();
10214                 expect('}');
10215         } else {
10216                 parse_external();
10217         }
10218
10219         assert(current_linkage == new_linkage);
10220         current_linkage = old_linkage;
10221 }
10222
10223 static void parse_external(void)
10224 {
10225         switch (token.kind) {
10226                 case T_extern:
10227                         if (look_ahead(1)->kind == T_STRING_LITERAL) {
10228                                 parse_linkage_specification();
10229                         } else {
10230                 DECLARATION_START_NO_EXTERN
10231                 case T_IDENTIFIER:
10232                 case T___extension__:
10233                 /* tokens below are for implicit int */
10234                 case '&':  /* & x; -> int& x; (and error later, because C++ has no
10235                               implicit int) */
10236                 case '*':  /* * x; -> int* x; */
10237                 case '(':  /* (x); -> int (x); */
10238                                 PUSH_EXTENSION();
10239                                 parse_external_declaration();
10240                                 POP_EXTENSION();
10241                         }
10242                         return;
10243
10244                 case T_asm:
10245                         parse_global_asm();
10246                         return;
10247
10248                 case T_namespace:
10249                         parse_namespace_definition();
10250                         return;
10251
10252                 case ';':
10253                         if (!strict_mode) {
10254                                 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10255                                 eat(';');
10256                                 return;
10257                         }
10258                         /* FALLTHROUGH */
10259
10260                 default:
10261                         errorf(HERE, "stray %K outside of function", &token);
10262                         if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10263                                 eat_until_matching_token(token.kind);
10264                         next_token();
10265                         return;
10266         }
10267 }
10268
10269 static void parse_externals(void)
10270 {
10271         add_anchor_token('}');
10272         add_anchor_token(T_EOF);
10273
10274 #ifndef NDEBUG
10275         /* make a copy of the anchor set, so we can check if it is restored after parsing */
10276         unsigned short token_anchor_copy[T_LAST_TOKEN];
10277         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10278 #endif
10279
10280         while (token.kind != T_EOF && token.kind != '}') {
10281 #ifndef NDEBUG
10282                 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10283                         unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10284                         if (count != 0) {
10285                                 /* the anchor set and its copy differs */
10286                                 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10287                         }
10288                 }
10289                 if (in_gcc_extension) {
10290                         /* an gcc extension scope was not closed */
10291                         internal_errorf(HERE, "Leaked __extension__");
10292                 }
10293 #endif
10294
10295                 parse_external();
10296         }
10297
10298         rem_anchor_token(T_EOF);
10299         rem_anchor_token('}');
10300 }
10301
10302 /**
10303  * Parse a translation unit.
10304  */
10305 static void parse_translation_unit(void)
10306 {
10307         add_anchor_token(T_EOF);
10308
10309         while (true) {
10310                 parse_externals();
10311
10312                 if (token.kind == T_EOF)
10313                         break;
10314
10315                 errorf(HERE, "stray %K outside of function", &token);
10316                 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10317                         eat_until_matching_token(token.kind);
10318                 next_token();
10319         }
10320 }
10321
10322 void set_default_visibility(elf_visibility_tag_t visibility)
10323 {
10324         default_visibility = visibility;
10325 }
10326
10327 /**
10328  * Parse the input.
10329  *
10330  * @return  the translation unit or NULL if errors occurred.
10331  */
10332 void start_parsing(void)
10333 {
10334         environment_stack = NEW_ARR_F(stack_entry_t, 0);
10335         label_stack       = NEW_ARR_F(stack_entry_t, 0);
10336
10337         print_to_file(stderr);
10338
10339         assert(unit == NULL);
10340         unit = allocate_ast_zero(sizeof(unit[0]));
10341
10342         assert(file_scope == NULL);
10343         file_scope = &unit->scope;
10344
10345         assert(current_scope == NULL);
10346         scope_push(&unit->scope);
10347
10348         create_gnu_builtins();
10349         if (c_mode & _MS)
10350                 create_microsoft_intrinsics();
10351 }
10352
10353 translation_unit_t *finish_parsing(void)
10354 {
10355         assert(current_scope == &unit->scope);
10356         scope_pop(NULL);
10357
10358         assert(file_scope == &unit->scope);
10359         check_unused_globals();
10360         file_scope = NULL;
10361
10362         DEL_ARR_F(environment_stack);
10363         DEL_ARR_F(label_stack);
10364
10365         translation_unit_t *result = unit;
10366         unit = NULL;
10367         return result;
10368 }
10369
10370 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10371  * are given length one. */
10372 static void complete_incomplete_arrays(void)
10373 {
10374         size_t n = ARR_LEN(incomplete_arrays);
10375         for (size_t i = 0; i != n; ++i) {
10376                 declaration_t *const decl = incomplete_arrays[i];
10377                 type_t        *const type = skip_typeref(decl->type);
10378
10379                 if (!is_type_incomplete(type))
10380                         continue;
10381
10382                 position_t const *const pos = &decl->base.pos;
10383                 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10384
10385                 type_t *const new_type = duplicate_type(type);
10386                 new_type->array.size_constant     = true;
10387                 new_type->array.has_implicit_size = true;
10388                 new_type->array.size              = 1;
10389
10390                 type_t *const result = identify_new_type(new_type);
10391
10392                 decl->type = result;
10393         }
10394 }
10395
10396 static void prepare_main_collect2(entity_t *const entity)
10397 {
10398         PUSH_SCOPE(&entity->function.body->compound.scope);
10399
10400         // create call to __main
10401         symbol_t *symbol         = symbol_table_insert("__main");
10402         entity_t *subsubmain_ent
10403                 = create_implicit_function(symbol, &builtin_position);
10404
10405         expression_t *ref     = allocate_expression_zero(EXPR_REFERENCE);
10406         type_t       *ftype   = subsubmain_ent->declaration.type;
10407         ref->base.pos         = builtin_position;
10408         ref->base.type        = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10409         ref->reference.entity = subsubmain_ent;
10410
10411         expression_t *call  = allocate_expression_zero(EXPR_CALL);
10412         call->base.pos      = builtin_position;
10413         call->base.type     = type_void;
10414         call->call.function = ref;
10415
10416         statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10417         expr_statement->base.pos              = builtin_position;
10418         expr_statement->expression.expression = call;
10419
10420         statement_t *const body = entity->function.body;
10421         assert(body->kind == STATEMENT_COMPOUND);
10422         compound_statement_t *compounds = &body->compound;
10423
10424         expr_statement->base.next = compounds->statements;
10425         compounds->statements     = expr_statement;
10426
10427         POP_SCOPE();
10428 }
10429
10430 void parse(void)
10431 {
10432         lookahead_bufpos = 0;
10433         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10434                 next_token();
10435         }
10436         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10437         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10438         parse_translation_unit();
10439         complete_incomplete_arrays();
10440         DEL_ARR_F(incomplete_arrays);
10441         incomplete_arrays = NULL;
10442 }
10443
10444 /**
10445  * Initialize the parser.
10446  */
10447 void init_parser(void)
10448 {
10449         memset(token_anchor_set, 0, sizeof(token_anchor_set));
10450
10451         init_expression_parsers();
10452         obstack_init(&temp_obst);
10453 }
10454
10455 /**
10456  * Terminate the parser.
10457  */
10458 void exit_parser(void)
10459 {
10460         obstack_free(&temp_obst, NULL);
10461 }