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