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