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