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