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