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