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