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