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