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