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