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