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