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