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