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