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