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