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