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