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