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