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