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