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