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