5ab84186a1996c683142f7fac024f905cb7a0b1e
[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_ADDRESS]         = sizeof(builtin_address_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_ADDRESS:
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                 type_t *parameter_type = parameter->declaration.type;
5536                 if (parameter_type == NULL) {
5537                         if (strict_mode) {
5538                                 errorf(HERE, "no type specified for function parameter '%Y'",
5539                                        parameter->base.symbol);
5540                         } else {
5541                                 if (warning.implicit_int) {
5542                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5543                                                  parameter->base.symbol);
5544                                 }
5545                                 parameter_type              = type_int;
5546                                 parameter->declaration.type = parameter_type;
5547                         }
5548                 }
5549
5550                 semantic_parameter_incomplete(parameter);
5551                 parameter_type = parameter->declaration.type;
5552
5553                 /*
5554                  * we need the default promoted types for the function type
5555                  */
5556                 parameter_type = get_default_promoted_type(parameter_type);
5557
5558                 function_parameter_t *function_parameter
5559                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5560                 memset(function_parameter, 0, sizeof(function_parameter[0]));
5561
5562                 function_parameter->type = parameter_type;
5563                 if (last_parameter != NULL) {
5564                         last_parameter->next = function_parameter;
5565                 } else {
5566                         parameters = function_parameter;
5567                 }
5568                 last_parameter = function_parameter;
5569         }
5570
5571         /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5572          * prototype */
5573         new_type->function.parameters             = parameters;
5574         new_type->function.unspecified_parameters = true;
5575
5576         new_type = identify_new_type(new_type);
5577
5578         entity->declaration.type = new_type;
5579
5580         rem_anchor_token('{');
5581 }
5582
5583 static bool first_err = true;
5584
5585 /**
5586  * When called with first_err set, prints the name of the current function,
5587  * else does noting.
5588  */
5589 static void print_in_function(void)
5590 {
5591         if (first_err) {
5592                 first_err = false;
5593                 diagnosticf("%s: In function '%Y':\n",
5594                             current_function->base.base.source_position.input_name,
5595                             current_function->base.base.symbol);
5596         }
5597 }
5598
5599 /**
5600  * Check if all labels are defined in the current function.
5601  * Check if all labels are used in the current function.
5602  */
5603 static void check_labels(void)
5604 {
5605         for (const goto_statement_t *goto_statement = goto_first;
5606             goto_statement != NULL;
5607             goto_statement = goto_statement->next) {
5608                 /* skip computed gotos */
5609                 if (goto_statement->expression != NULL)
5610                         continue;
5611
5612                 label_t *label = goto_statement->label;
5613
5614                 label->used = true;
5615                 if (label->base.source_position.input_name == NULL) {
5616                         print_in_function();
5617                         errorf(&goto_statement->base.source_position,
5618                                "label '%Y' used but not defined", label->base.symbol);
5619                  }
5620         }
5621
5622         if (warning.unused_label) {
5623                 for (const label_statement_t *label_statement = label_first;
5624                          label_statement != NULL;
5625                          label_statement = label_statement->next) {
5626                         label_t *label = label_statement->label;
5627
5628                         if (! label->used) {
5629                                 print_in_function();
5630                                 warningf(&label_statement->base.source_position,
5631                                          "label '%Y' defined but not used", label->base.symbol);
5632                         }
5633                 }
5634         }
5635 }
5636
5637 static void warn_unused_entity(entity_t *entity, entity_t *last)
5638 {
5639         entity_t const *const end = last != NULL ? last->base.next : NULL;
5640         for (; entity != end; entity = entity->base.next) {
5641                 if (!is_declaration(entity))
5642                         continue;
5643
5644                 declaration_t *declaration = &entity->declaration;
5645                 if (declaration->implicit)
5646                         continue;
5647
5648                 if (!declaration->used) {
5649                         print_in_function();
5650                         const char *what = get_entity_kind_name(entity->kind);
5651                         warningf(&entity->base.source_position, "%s '%Y' is unused",
5652                                  what, entity->base.symbol);
5653                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5654                         print_in_function();
5655                         const char *what = get_entity_kind_name(entity->kind);
5656                         warningf(&entity->base.source_position, "%s '%Y' is never read",
5657                                  what, entity->base.symbol);
5658                 }
5659         }
5660 }
5661
5662 static void check_unused_variables(statement_t *const stmt, void *const env)
5663 {
5664         (void)env;
5665
5666         switch (stmt->kind) {
5667                 case STATEMENT_DECLARATION: {
5668                         declaration_statement_t const *const decls = &stmt->declaration;
5669                         warn_unused_entity(decls->declarations_begin,
5670                                            decls->declarations_end);
5671                         return;
5672                 }
5673
5674                 case STATEMENT_FOR:
5675                         warn_unused_entity(stmt->fors.scope.entities, NULL);
5676                         return;
5677
5678                 default:
5679                         return;
5680         }
5681 }
5682
5683 /**
5684  * Check declarations of current_function for unused entities.
5685  */
5686 static void check_declarations(void)
5687 {
5688         if (warning.unused_parameter) {
5689                 const scope_t *scope = &current_function->parameters;
5690
5691                 /* do not issue unused warnings for main */
5692                 if (!is_sym_main(current_function->base.base.symbol)) {
5693                         warn_unused_entity(scope->entities, NULL);
5694                 }
5695         }
5696         if (warning.unused_variable) {
5697                 walk_statements(current_function->statement, check_unused_variables,
5698                                 NULL);
5699         }
5700 }
5701
5702 static int determine_truth(expression_t const* const cond)
5703 {
5704         return
5705                 !is_constant_expression(cond) ? 0 :
5706                 fold_constant(cond) != 0      ? 1 :
5707                 -1;
5708 }
5709
5710 static void check_reachable(statement_t *);
5711 static bool reaches_end;
5712
5713 static bool expression_returns(expression_t const *const expr)
5714 {
5715         switch (expr->kind) {
5716                 case EXPR_CALL: {
5717                         expression_t const *const func = expr->call.function;
5718                         if (func->kind == EXPR_REFERENCE) {
5719                                 entity_t *entity = func->reference.entity;
5720                                 if (entity->kind == ENTITY_FUNCTION
5721                                                 && entity->declaration.modifiers & DM_NORETURN)
5722                                         return false;
5723                         }
5724
5725                         if (!expression_returns(func))
5726                                 return false;
5727
5728                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5729                                 if (!expression_returns(arg->expression))
5730                                         return false;
5731                         }
5732
5733                         return true;
5734                 }
5735
5736                 case EXPR_REFERENCE:
5737                 case EXPR_REFERENCE_ENUM_VALUE:
5738                 case EXPR_CONST:
5739                 case EXPR_CHARACTER_CONSTANT:
5740                 case EXPR_WIDE_CHARACTER_CONSTANT:
5741                 case EXPR_STRING_LITERAL:
5742                 case EXPR_WIDE_STRING_LITERAL:
5743                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5744                 case EXPR_LABEL_ADDRESS:
5745                 case EXPR_CLASSIFY_TYPE:
5746                 case EXPR_SIZEOF: // TODO handle obscure VLA case
5747                 case EXPR_ALIGNOF:
5748                 case EXPR_FUNCNAME:
5749                 case EXPR_BUILTIN_SYMBOL:
5750                 case EXPR_BUILTIN_CONSTANT_P:
5751                 case EXPR_BUILTIN_ADDRESS:
5752                 case EXPR_BUILTIN_PREFETCH:
5753                 case EXPR_OFFSETOF:
5754                 case EXPR_INVALID:
5755                         return true;
5756
5757                 case EXPR_STATEMENT: {
5758                         bool old_reaches_end = reaches_end;
5759                         reaches_end = false;
5760                         check_reachable(expr->statement.statement);
5761                         bool returns = reaches_end;
5762                         reaches_end = old_reaches_end;
5763                         return returns;
5764                 }
5765
5766                 case EXPR_CONDITIONAL:
5767                         // TODO handle constant expression
5768
5769                         if (!expression_returns(expr->conditional.condition))
5770                                 return false;
5771
5772                         if (expr->conditional.true_expression != NULL
5773                                         && expression_returns(expr->conditional.true_expression))
5774                                 return true;
5775
5776                         return expression_returns(expr->conditional.false_expression);
5777
5778                 case EXPR_SELECT:
5779                         return expression_returns(expr->select.compound);
5780
5781                 case EXPR_ARRAY_ACCESS:
5782                         return
5783                                 expression_returns(expr->array_access.array_ref) &&
5784                                 expression_returns(expr->array_access.index);
5785
5786                 case EXPR_VA_START:
5787                         return expression_returns(expr->va_starte.ap);
5788
5789                 case EXPR_VA_ARG:
5790                         return expression_returns(expr->va_arge.ap);
5791
5792                 EXPR_UNARY_CASES_MANDATORY
5793                         return expression_returns(expr->unary.value);
5794
5795                 case EXPR_UNARY_THROW:
5796                         return false;
5797
5798                 EXPR_BINARY_CASES
5799                         // TODO handle constant lhs of && and ||
5800                         return
5801                                 expression_returns(expr->binary.left) &&
5802                                 expression_returns(expr->binary.right);
5803
5804                 case EXPR_UNKNOWN:
5805                         break;
5806         }
5807
5808         panic("unhandled expression");
5809 }
5810
5811 static bool initializer_returns(initializer_t const *const init)
5812 {
5813         switch (init->kind) {
5814                 case INITIALIZER_VALUE:
5815                         return expression_returns(init->value.value);
5816
5817                 case INITIALIZER_LIST: {
5818                         initializer_t * const*       i       = init->list.initializers;
5819                         initializer_t * const* const end     = i + init->list.len;
5820                         bool                         returns = true;
5821                         for (; i != end; ++i) {
5822                                 if (!initializer_returns(*i))
5823                                         returns = false;
5824                         }
5825                         return returns;
5826                 }
5827
5828                 case INITIALIZER_STRING:
5829                 case INITIALIZER_WIDE_STRING:
5830                 case INITIALIZER_DESIGNATOR: // designators have no payload
5831                         return true;
5832         }
5833         panic("unhandled initializer");
5834 }
5835
5836 static bool noreturn_candidate;
5837
5838 static void check_reachable(statement_t *const stmt)
5839 {
5840         if (stmt->base.reachable)
5841                 return;
5842         if (stmt->kind != STATEMENT_DO_WHILE)
5843                 stmt->base.reachable = true;
5844
5845         statement_t *last = stmt;
5846         statement_t *next;
5847         switch (stmt->kind) {
5848                 case STATEMENT_INVALID:
5849                 case STATEMENT_EMPTY:
5850                 case STATEMENT_ASM:
5851                         next = stmt->base.next;
5852                         break;
5853
5854                 case STATEMENT_DECLARATION: {
5855                         declaration_statement_t const *const decl = &stmt->declaration;
5856                         entity_t                const *      ent  = decl->declarations_begin;
5857                         entity_t                const *const last = decl->declarations_end;
5858                         if (ent != NULL) {
5859                                 for (;; ent = ent->base.next) {
5860                                         if (ent->kind                 == ENTITY_VARIABLE &&
5861                                                         ent->variable.initializer != NULL            &&
5862                                                         !initializer_returns(ent->variable.initializer)) {
5863                                                 return;
5864                                         }
5865                                         if (ent == last)
5866                                                 break;
5867                                 }
5868                         }
5869                         next = stmt->base.next;
5870                         break;
5871                 }
5872
5873                 case STATEMENT_COMPOUND:
5874                         next = stmt->compound.statements;
5875                         if (next == NULL)
5876                                 next = stmt->base.next;
5877                         break;
5878
5879                 case STATEMENT_RETURN: {
5880                         expression_t const *const val = stmt->returns.value;
5881                         if (val == NULL || expression_returns(val))
5882                                 noreturn_candidate = false;
5883                         return;
5884                 }
5885
5886                 case STATEMENT_IF: {
5887                         if_statement_t const *const ifs  = &stmt->ifs;
5888                         expression_t   const *const cond = ifs->condition;
5889
5890                         if (!expression_returns(cond))
5891                                 return;
5892
5893                         int const val = determine_truth(cond);
5894
5895                         if (val >= 0)
5896                                 check_reachable(ifs->true_statement);
5897
5898                         if (val > 0)
5899                                 return;
5900
5901                         if (ifs->false_statement != NULL) {
5902                                 check_reachable(ifs->false_statement);
5903                                 return;
5904                         }
5905
5906                         next = stmt->base.next;
5907                         break;
5908                 }
5909
5910                 case STATEMENT_SWITCH: {
5911                         switch_statement_t const *const switchs = &stmt->switchs;
5912                         expression_t       const *const expr    = switchs->expression;
5913
5914                         if (!expression_returns(expr))
5915                                 return;
5916
5917                         if (is_constant_expression(expr)) {
5918                                 long                    const val      = fold_constant(expr);
5919                                 case_label_statement_t *      defaults = NULL;
5920                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5921                                         if (i->expression == NULL) {
5922                                                 defaults = i;
5923                                                 continue;
5924                                         }
5925
5926                                         if (i->first_case <= val && val <= i->last_case) {
5927                                                 check_reachable((statement_t*)i);
5928                                                 return;
5929                                         }
5930                                 }
5931
5932                                 if (defaults != NULL) {
5933                                         check_reachable((statement_t*)defaults);
5934                                         return;
5935                                 }
5936                         } else {
5937                                 bool has_default = false;
5938                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5939                                         if (i->expression == NULL)
5940                                                 has_default = true;
5941
5942                                         check_reachable((statement_t*)i);
5943                                 }
5944
5945                                 if (has_default)
5946                                         return;
5947                         }
5948
5949                         next = stmt->base.next;
5950                         break;
5951                 }
5952
5953                 case STATEMENT_EXPRESSION: {
5954                         /* Check for noreturn function call */
5955                         expression_t const *const expr = stmt->expression.expression;
5956                         if (!expression_returns(expr))
5957                                 return;
5958
5959                         next = stmt->base.next;
5960                         break;
5961                 }
5962
5963                 case STATEMENT_CONTINUE: {
5964                         statement_t *parent = stmt;
5965                         for (;;) {
5966                                 parent = parent->base.parent;
5967                                 if (parent == NULL) /* continue not within loop */
5968                                         return;
5969
5970                                 next = parent;
5971                                 switch (parent->kind) {
5972                                         case STATEMENT_WHILE:    goto continue_while;
5973                                         case STATEMENT_DO_WHILE: goto continue_do_while;
5974                                         case STATEMENT_FOR:      goto continue_for;
5975
5976                                         default: break;
5977                                 }
5978                         }
5979                 }
5980
5981                 case STATEMENT_BREAK: {
5982                         statement_t *parent = stmt;
5983                         for (;;) {
5984                                 parent = parent->base.parent;
5985                                 if (parent == NULL) /* break not within loop/switch */
5986                                         return;
5987
5988                                 switch (parent->kind) {
5989                                         case STATEMENT_SWITCH:
5990                                         case STATEMENT_WHILE:
5991                                         case STATEMENT_DO_WHILE:
5992                                         case STATEMENT_FOR:
5993                                                 last = parent;
5994                                                 next = parent->base.next;
5995                                                 goto found_break_parent;
5996
5997                                         default: break;
5998                                 }
5999                         }
6000 found_break_parent:
6001                         break;
6002                 }
6003
6004                 case STATEMENT_GOTO:
6005                         if (stmt->gotos.expression) {
6006                                 if (!expression_returns(stmt->gotos.expression))
6007                                         return;
6008
6009                                 statement_t *parent = stmt->base.parent;
6010                                 if (parent == NULL) /* top level goto */
6011                                         return;
6012                                 next = parent;
6013                         } else {
6014                                 next = stmt->gotos.label->statement;
6015                                 if (next == NULL) /* missing label */
6016                                         return;
6017                         }
6018                         break;
6019
6020                 case STATEMENT_LABEL:
6021                         next = stmt->label.statement;
6022                         break;
6023
6024                 case STATEMENT_CASE_LABEL:
6025                         next = stmt->case_label.statement;
6026                         break;
6027
6028                 case STATEMENT_WHILE: {
6029                         while_statement_t const *const whiles = &stmt->whiles;
6030                         expression_t      const *const cond   = whiles->condition;
6031
6032                         if (!expression_returns(cond))
6033                                 return;
6034
6035                         int const val = determine_truth(cond);
6036
6037                         if (val >= 0)
6038                                 check_reachable(whiles->body);
6039
6040                         if (val > 0)
6041                                 return;
6042
6043                         next = stmt->base.next;
6044                         break;
6045                 }
6046
6047                 case STATEMENT_DO_WHILE:
6048                         next = stmt->do_while.body;
6049                         break;
6050
6051                 case STATEMENT_FOR: {
6052                         for_statement_t *const fors = &stmt->fors;
6053
6054                         if (fors->condition_reachable)
6055                                 return;
6056                         fors->condition_reachable = true;
6057
6058                         expression_t const *const cond = fors->condition;
6059
6060                         int val;
6061                         if (cond == NULL) {
6062                                 val = 1;
6063                         } else if (expression_returns(cond)) {
6064                                 val = determine_truth(cond);
6065                         } else {
6066                                 return;
6067                         }
6068
6069                         if (val >= 0)
6070                                 check_reachable(fors->body);
6071
6072                         if (val > 0)
6073                                 return;
6074
6075                         next = stmt->base.next;
6076                         break;
6077                 }
6078
6079                 case STATEMENT_MS_TRY: {
6080                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
6081                         check_reachable(ms_try->try_statement);
6082                         next = ms_try->final_statement;
6083                         break;
6084                 }
6085
6086                 case STATEMENT_LEAVE: {
6087                         statement_t *parent = stmt;
6088                         for (;;) {
6089                                 parent = parent->base.parent;
6090                                 if (parent == NULL) /* __leave not within __try */
6091                                         return;
6092
6093                                 if (parent->kind == STATEMENT_MS_TRY) {
6094                                         last = parent;
6095                                         next = parent->ms_try.final_statement;
6096                                         break;
6097                                 }
6098                         }
6099                         break;
6100                 }
6101
6102                 default:
6103                         panic("invalid statement kind");
6104         }
6105
6106         while (next == NULL) {
6107                 next = last->base.parent;
6108                 if (next == NULL) {
6109                         noreturn_candidate = false;
6110
6111                         type_t *const type = skip_typeref(current_function->base.type);
6112                         assert(is_type_function(type));
6113                         type_t *const ret  = skip_typeref(type->function.return_type);
6114                         if (warning.return_type                    &&
6115                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6116                             is_type_valid(ret)                     &&
6117                             !is_sym_main(current_function->base.base.symbol)) {
6118                                 warningf(&stmt->base.source_position,
6119                                          "control reaches end of non-void function");
6120                         }
6121                         return;
6122                 }
6123
6124                 switch (next->kind) {
6125                         case STATEMENT_INVALID:
6126                         case STATEMENT_EMPTY:
6127                         case STATEMENT_DECLARATION:
6128                         case STATEMENT_EXPRESSION:
6129                         case STATEMENT_ASM:
6130                         case STATEMENT_RETURN:
6131                         case STATEMENT_CONTINUE:
6132                         case STATEMENT_BREAK:
6133                         case STATEMENT_GOTO:
6134                         case STATEMENT_LEAVE:
6135                                 panic("invalid control flow in function");
6136
6137                         case STATEMENT_COMPOUND:
6138                                 if (next->compound.stmt_expr) {
6139                                         reaches_end = true;
6140                                         return;
6141                                 }
6142                                 /* FALLTHROUGH */
6143                         case STATEMENT_IF:
6144                         case STATEMENT_SWITCH:
6145                         case STATEMENT_LABEL:
6146                         case STATEMENT_CASE_LABEL:
6147                                 last = next;
6148                                 next = next->base.next;
6149                                 break;
6150
6151                         case STATEMENT_WHILE: {
6152 continue_while:
6153                                 if (next->base.reachable)
6154                                         return;
6155                                 next->base.reachable = true;
6156
6157                                 while_statement_t const *const whiles = &next->whiles;
6158                                 expression_t      const *const cond   = whiles->condition;
6159
6160                                 if (!expression_returns(cond))
6161                                         return;
6162
6163                                 int const val = determine_truth(cond);
6164
6165                                 if (val >= 0)
6166                                         check_reachable(whiles->body);
6167
6168                                 if (val > 0)
6169                                         return;
6170
6171                                 last = next;
6172                                 next = next->base.next;
6173                                 break;
6174                         }
6175
6176                         case STATEMENT_DO_WHILE: {
6177 continue_do_while:
6178                                 if (next->base.reachable)
6179                                         return;
6180                                 next->base.reachable = true;
6181
6182                                 do_while_statement_t const *const dw   = &next->do_while;
6183                                 expression_t         const *const cond = dw->condition;
6184
6185                                 if (!expression_returns(cond))
6186                                         return;
6187
6188                                 int const val = determine_truth(cond);
6189
6190                                 if (val >= 0)
6191                                         check_reachable(dw->body);
6192
6193                                 if (val > 0)
6194                                         return;
6195
6196                                 last = next;
6197                                 next = next->base.next;
6198                                 break;
6199                         }
6200
6201                         case STATEMENT_FOR: {
6202 continue_for:;
6203                                 for_statement_t *const fors = &next->fors;
6204
6205                                 fors->step_reachable = true;
6206
6207                                 if (fors->condition_reachable)
6208                                         return;
6209                                 fors->condition_reachable = true;
6210
6211                                 expression_t const *const cond = fors->condition;
6212
6213                                 int val;
6214                                 if (cond == NULL) {
6215                                         val = 1;
6216                                 } else if (expression_returns(cond)) {
6217                                         val = determine_truth(cond);
6218                                 } else {
6219                                         return;
6220                                 }
6221
6222                                 if (val >= 0)
6223                                         check_reachable(fors->body);
6224
6225                                 if (val > 0)
6226                                         return;
6227
6228                                 last = next;
6229                                 next = next->base.next;
6230                                 break;
6231                         }
6232
6233                         case STATEMENT_MS_TRY:
6234                                 last = next;
6235                                 next = next->ms_try.final_statement;
6236                                 break;
6237                 }
6238         }
6239
6240         check_reachable(next);
6241 }
6242
6243 static void check_unreachable(statement_t* const stmt, void *const env)
6244 {
6245         (void)env;
6246
6247         switch (stmt->kind) {
6248                 case STATEMENT_DO_WHILE:
6249                         if (!stmt->base.reachable) {
6250                                 expression_t const *const cond = stmt->do_while.condition;
6251                                 if (determine_truth(cond) >= 0) {
6252                                         warningf(&cond->base.source_position,
6253                                                  "condition of do-while-loop is unreachable");
6254                                 }
6255                         }
6256                         return;
6257
6258                 case STATEMENT_FOR: {
6259                         for_statement_t const* const fors = &stmt->fors;
6260
6261                         // if init and step are unreachable, cond is unreachable, too
6262                         if (!stmt->base.reachable && !fors->step_reachable) {
6263                                 warningf(&stmt->base.source_position, "statement is unreachable");
6264                         } else {
6265                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
6266                                         warningf(&fors->initialisation->base.source_position,
6267                                                  "initialisation of for-statement is unreachable");
6268                                 }
6269
6270                                 if (!fors->condition_reachable && fors->condition != NULL) {
6271                                         warningf(&fors->condition->base.source_position,
6272                                                  "condition of for-statement is unreachable");
6273                                 }
6274
6275                                 if (!fors->step_reachable && fors->step != NULL) {
6276                                         warningf(&fors->step->base.source_position,
6277                                                  "step of for-statement is unreachable");
6278                                 }
6279                         }
6280                         return;
6281                 }
6282
6283                 case STATEMENT_COMPOUND:
6284                         if (stmt->compound.statements != NULL)
6285                                 return;
6286                         goto warn_unreachable;
6287
6288                 case STATEMENT_DECLARATION: {
6289                         /* Only warn if there is at least one declarator with an initializer.
6290                          * This typically occurs in switch statements. */
6291                         declaration_statement_t const *const decl = &stmt->declaration;
6292                         entity_t                const *      ent  = decl->declarations_begin;
6293                         entity_t                const *const last = decl->declarations_end;
6294                         if (ent != NULL) {
6295                                 for (;; ent = ent->base.next) {
6296                                         if (ent->kind                 == ENTITY_VARIABLE &&
6297                                                         ent->variable.initializer != NULL) {
6298                                                 goto warn_unreachable;
6299                                         }
6300                                         if (ent == last)
6301                                                 return;
6302                                 }
6303                         }
6304                 }
6305
6306                 default:
6307 warn_unreachable:
6308                         if (!stmt->base.reachable)
6309                                 warningf(&stmt->base.source_position, "statement is unreachable");
6310                         return;
6311         }
6312 }
6313
6314 static void parse_external_declaration(void)
6315 {
6316         /* function-definitions and declarations both start with declaration
6317          * specifiers */
6318         declaration_specifiers_t specifiers;
6319         memset(&specifiers, 0, sizeof(specifiers));
6320
6321         add_anchor_token(';');
6322         parse_declaration_specifiers(&specifiers);
6323         rem_anchor_token(';');
6324
6325         /* must be a declaration */
6326         if (token.type == ';') {
6327                 parse_anonymous_declaration_rest(&specifiers);
6328                 return;
6329         }
6330
6331         add_anchor_token(',');
6332         add_anchor_token('=');
6333         add_anchor_token(';');
6334         add_anchor_token('{');
6335
6336         /* declarator is common to both function-definitions and declarations */
6337         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6338
6339         rem_anchor_token('{');
6340         rem_anchor_token(';');
6341         rem_anchor_token('=');
6342         rem_anchor_token(',');
6343
6344         /* must be a declaration */
6345         switch (token.type) {
6346                 case ',':
6347                 case ';':
6348                 case '=':
6349                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6350                                         DECL_FLAGS_NONE);
6351                         return;
6352         }
6353
6354         /* must be a function definition */
6355         parse_kr_declaration_list(ndeclaration);
6356
6357         if (token.type != '{') {
6358                 parse_error_expected("while parsing function definition", '{', NULL);
6359                 eat_until_matching_token(';');
6360                 return;
6361         }
6362
6363         assert(is_declaration(ndeclaration));
6364         type_t *const orig_type = ndeclaration->declaration.type;
6365         type_t *      type      = skip_typeref(orig_type);
6366
6367         if (!is_type_function(type)) {
6368                 if (is_type_valid(type)) {
6369                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
6370                                type, ndeclaration->base.symbol);
6371                 }
6372                 eat_block();
6373                 return;
6374         } else if (is_typeref(orig_type)) {
6375                 /* §6.9.1:2 */
6376                 errorf(&ndeclaration->base.source_position,
6377                                 "type of function definition '%#T' is a typedef",
6378                                 orig_type, ndeclaration->base.symbol);
6379         }
6380
6381         if (warning.aggregate_return &&
6382             is_type_compound(skip_typeref(type->function.return_type))) {
6383                 warningf(HERE, "function '%Y' returns an aggregate",
6384                          ndeclaration->base.symbol);
6385         }
6386         if (warning.traditional && !type->function.unspecified_parameters) {
6387                 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6388                         ndeclaration->base.symbol);
6389         }
6390         if (warning.old_style_definition && type->function.unspecified_parameters) {
6391                 warningf(HERE, "old-style function definition '%Y'",
6392                         ndeclaration->base.symbol);
6393         }
6394
6395         /* § 6.7.5.3:14 a function definition with () means no
6396          * parameters (and not unspecified parameters) */
6397         if (type->function.unspecified_parameters &&
6398                         type->function.parameters == NULL     &&
6399                         !type->function.kr_style_parameters) {
6400                 type_t *copy                          = duplicate_type(type);
6401                 copy->function.unspecified_parameters = false;
6402                 type                                  = identify_new_type(copy);
6403
6404                 ndeclaration->declaration.type = type;
6405         }
6406
6407         entity_t *const entity = record_entity(ndeclaration, true);
6408         assert(entity->kind == ENTITY_FUNCTION);
6409         assert(ndeclaration->kind == ENTITY_FUNCTION);
6410
6411         function_t *function = &entity->function;
6412         if (ndeclaration != entity) {
6413                 function->parameters = ndeclaration->function.parameters;
6414         }
6415         assert(is_declaration(entity));
6416         type = skip_typeref(entity->declaration.type);
6417
6418         /* push function parameters and switch scope */
6419         size_t const  top       = environment_top();
6420         scope_t      *old_scope = scope_push(&function->parameters);
6421
6422         entity_t *parameter = function->parameters.entities;
6423         for (; parameter != NULL; parameter = parameter->base.next) {
6424                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6425                         parameter->base.parent_scope = current_scope;
6426                 }
6427                 assert(parameter->base.parent_scope == NULL
6428                                 || parameter->base.parent_scope == current_scope);
6429                 parameter->base.parent_scope = current_scope;
6430                 if (parameter->base.symbol == NULL) {
6431                         errorf(&parameter->base.source_position, "parameter name omitted");
6432                         continue;
6433                 }
6434                 environment_push(parameter);
6435         }
6436
6437         if (function->statement != NULL) {
6438                 parser_error_multiple_definition(entity, HERE);
6439                 eat_block();
6440         } else {
6441                 /* parse function body */
6442                 int         label_stack_top      = label_top();
6443                 function_t *old_current_function = current_function;
6444                 current_function                 = function;
6445                 current_parent                   = NULL;
6446
6447                 goto_first   = NULL;
6448                 goto_anchor  = &goto_first;
6449                 label_first  = NULL;
6450                 label_anchor = &label_first;
6451
6452                 statement_t *const body = parse_compound_statement(false);
6453                 function->statement = body;
6454                 first_err = true;
6455                 check_labels();
6456                 check_declarations();
6457                 if (warning.return_type      ||
6458                     warning.unreachable_code ||
6459                     (warning.missing_noreturn
6460                      && !(function->base.modifiers & DM_NORETURN))) {
6461                         noreturn_candidate = true;
6462                         check_reachable(body);
6463                         if (warning.unreachable_code)
6464                                 walk_statements(body, check_unreachable, NULL);
6465                         if (warning.missing_noreturn &&
6466                             noreturn_candidate       &&
6467                             !(function->base.modifiers & DM_NORETURN)) {
6468                                 warningf(&body->base.source_position,
6469                                          "function '%#T' is candidate for attribute 'noreturn'",
6470                                          type, entity->base.symbol);
6471                         }
6472                 }
6473
6474                 assert(current_parent   == NULL);
6475                 assert(current_function == function);
6476                 current_function = old_current_function;
6477                 label_pop_to(label_stack_top);
6478         }
6479
6480         assert(current_scope == &function->parameters);
6481         scope_pop(old_scope);
6482         environment_pop_to(top);
6483 }
6484
6485 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6486                                   source_position_t *source_position,
6487                                   const symbol_t *symbol)
6488 {
6489         type_t *type = allocate_type_zero(TYPE_BITFIELD);
6490
6491         type->bitfield.base_type       = base_type;
6492         type->bitfield.size_expression = size;
6493
6494         il_size_t bit_size;
6495         type_t *skipped_type = skip_typeref(base_type);
6496         if (!is_type_integer(skipped_type)) {
6497                 errorf(HERE, "bitfield base type '%T' is not an integer type",
6498                         base_type);
6499                 bit_size = 0;
6500         } else {
6501                 bit_size = skipped_type->base.size * 8;
6502         }
6503
6504         if (is_constant_expression(size)) {
6505                 long v = fold_constant(size);
6506
6507                 if (v < 0) {
6508                         errorf(source_position, "negative width in bit-field '%Y'", symbol);
6509                 } else if (v == 0) {
6510                         errorf(source_position, "zero width for bit-field '%Y'", symbol);
6511                 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6512                         errorf(source_position, "width of '%Y' exceeds its type", symbol);
6513                 } else {
6514                         type->bitfield.bit_size = v;
6515                 }
6516         }
6517
6518         return type;
6519 }
6520
6521 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6522 {
6523         entity_t *iter = compound->members.entities;
6524         for (; iter != NULL; iter = iter->base.next) {
6525                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6526                         continue;
6527
6528                 if (iter->base.symbol == symbol) {
6529                         return iter;
6530                 } else if (iter->base.symbol == NULL) {
6531                         type_t *type = skip_typeref(iter->declaration.type);
6532                         if (is_type_compound(type)) {
6533                                 entity_t *result
6534                                         = find_compound_entry(type->compound.compound, symbol);
6535                                 if (result != NULL)
6536                                         return result;
6537                         }
6538                         continue;
6539                 }
6540         }
6541
6542         return NULL;
6543 }
6544
6545 static void parse_compound_declarators(compound_t *compound,
6546                 const declaration_specifiers_t *specifiers)
6547 {
6548         while (true) {
6549                 entity_t *entity;
6550
6551                 if (token.type == ':') {
6552                         source_position_t source_position = *HERE;
6553                         next_token();
6554
6555                         type_t *base_type = specifiers->type;
6556                         expression_t *size = parse_constant_expression();
6557
6558                         type_t *type = make_bitfield_type(base_type, size,
6559                                         &source_position, sym_anonymous);
6560
6561                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6562                         entity->base.namespc                       = NAMESPACE_NORMAL;
6563                         entity->base.source_position               = source_position;
6564                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6565                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
6566                         entity->declaration.modifiers              = specifiers->modifiers;
6567                         entity->declaration.type                   = type;
6568                         append_entity(&compound->members, entity);
6569                 } else {
6570                         entity = parse_declarator(specifiers,
6571                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6572                         if (entity->kind == ENTITY_TYPEDEF) {
6573                                 errorf(&entity->base.source_position,
6574                                                 "typedef not allowed as compound member");
6575                         } else {
6576                                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6577
6578                                 /* make sure we don't define a symbol multiple times */
6579                                 symbol_t *symbol = entity->base.symbol;
6580                                 if (symbol != NULL) {
6581                                         entity_t *prev = find_compound_entry(compound, symbol);
6582                                         if (prev != NULL) {
6583                                                 errorf(&entity->base.source_position,
6584                                                                 "multiple declarations of symbol '%Y' (declared %P)",
6585                                                                 symbol, &prev->base.source_position);
6586                                         }
6587                                 }
6588
6589                                 if (token.type == ':') {
6590                                         source_position_t source_position = *HERE;
6591                                         next_token();
6592                                         expression_t *size = parse_constant_expression();
6593
6594                                         type_t *type          = entity->declaration.type;
6595                                         type_t *bitfield_type = make_bitfield_type(type, size,
6596                                                         &source_position, entity->base.symbol);
6597                                         entity->declaration.type = bitfield_type;
6598                                 } else {
6599                                         type_t *orig_type = entity->declaration.type;
6600                                         type_t *type      = skip_typeref(orig_type);
6601                                         if (is_type_function(type)) {
6602                                                 errorf(&entity->base.source_position,
6603                                                                 "compound member '%Y' must not have function type '%T'",
6604                                                                 entity->base.symbol, orig_type);
6605                                         } else if (is_type_incomplete(type)) {
6606                                                 /* §6.7.2.1:16 flexible array member */
6607                                                 if (is_type_array(type) &&
6608                                                                 token.type == ';'   &&
6609                                                                 look_ahead(1)->type == '}') {
6610                                                         compound->has_flexible_member = true;
6611                                                 } else {
6612                                                         errorf(&entity->base.source_position,
6613                                                                         "compound member '%Y' has incomplete type '%T'",
6614                                                                         entity->base.symbol, orig_type);
6615                                                 }
6616                                         }
6617                                 }
6618
6619                                 append_entity(&compound->members, entity);
6620                         }
6621                 }
6622
6623                 if (token.type != ',')
6624                         break;
6625                 next_token();
6626         }
6627         expect(';', end_error);
6628
6629 end_error:
6630         anonymous_entity = NULL;
6631 }
6632
6633 static void parse_compound_type_entries(compound_t *compound)
6634 {
6635         eat('{');
6636         add_anchor_token('}');
6637
6638         while (token.type != '}') {
6639                 if (token.type == T_EOF) {
6640                         errorf(HERE, "EOF while parsing struct");
6641                         break;
6642                 }
6643                 declaration_specifiers_t specifiers;
6644                 memset(&specifiers, 0, sizeof(specifiers));
6645                 parse_declaration_specifiers(&specifiers);
6646
6647                 parse_compound_declarators(compound, &specifiers);
6648         }
6649         rem_anchor_token('}');
6650         next_token();
6651
6652         /* §6.7.2.1:7 */
6653         compound->complete = true;
6654 }
6655
6656 static type_t *parse_typename(void)
6657 {
6658         declaration_specifiers_t specifiers;
6659         memset(&specifiers, 0, sizeof(specifiers));
6660         parse_declaration_specifiers(&specifiers);
6661         if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6662                         specifiers.thread_local) {
6663                 /* TODO: improve error message, user does probably not know what a
6664                  * storage class is...
6665                  */
6666                 errorf(HERE, "typename may not have a storage class");
6667         }
6668
6669         type_t *result = parse_abstract_declarator(specifiers.type);
6670
6671         return result;
6672 }
6673
6674
6675
6676
6677 typedef expression_t* (*parse_expression_function)(void);
6678 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6679
6680 typedef struct expression_parser_function_t expression_parser_function_t;
6681 struct expression_parser_function_t {
6682         parse_expression_function        parser;
6683         precedence_t                     infix_precedence;
6684         parse_expression_infix_function  infix_parser;
6685 };
6686
6687 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6688
6689 /**
6690  * Prints an error message if an expression was expected but not read
6691  */
6692 static expression_t *expected_expression_error(void)
6693 {
6694         /* skip the error message if the error token was read */
6695         if (token.type != T_ERROR) {
6696                 errorf(HERE, "expected expression, got token %K", &token);
6697         }
6698         next_token();
6699
6700         return create_invalid_expression();
6701 }
6702
6703 /**
6704  * Parse a string constant.
6705  */
6706 static expression_t *parse_string_const(void)
6707 {
6708         wide_string_t wres;
6709         if (token.type == T_STRING_LITERAL) {
6710                 string_t res = token.v.string;
6711                 next_token();
6712                 while (token.type == T_STRING_LITERAL) {
6713                         res = concat_strings(&res, &token.v.string);
6714                         next_token();
6715                 }
6716                 if (token.type != T_WIDE_STRING_LITERAL) {
6717                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6718                         /* note: that we use type_char_ptr here, which is already the
6719                          * automatic converted type. revert_automatic_type_conversion
6720                          * will construct the array type */
6721                         cnst->base.type    = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6722                         cnst->string.value = res;
6723                         return cnst;
6724                 }
6725
6726                 wres = concat_string_wide_string(&res, &token.v.wide_string);
6727         } else {
6728                 wres = token.v.wide_string;
6729         }
6730         next_token();
6731
6732         for (;;) {
6733                 switch (token.type) {
6734                         case T_WIDE_STRING_LITERAL:
6735                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
6736                                 break;
6737
6738                         case T_STRING_LITERAL:
6739                                 wres = concat_wide_string_string(&wres, &token.v.string);
6740                                 break;
6741
6742                         default: {
6743                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6744                                 cnst->base.type         = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6745                                 cnst->wide_string.value = wres;
6746                                 return cnst;
6747                         }
6748                 }
6749                 next_token();
6750         }
6751 }
6752
6753 /**
6754  * Parse a boolean constant.
6755  */
6756 static expression_t *parse_bool_const(bool value)
6757 {
6758         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6759         cnst->base.type          = type_bool;
6760         cnst->conste.v.int_value = value;
6761
6762         next_token();
6763
6764         return cnst;
6765 }
6766
6767 /**
6768  * Parse an integer constant.
6769  */
6770 static expression_t *parse_int_const(void)
6771 {
6772         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6773         cnst->base.type          = token.datatype;
6774         cnst->conste.v.int_value = token.v.intvalue;
6775
6776         next_token();
6777
6778         return cnst;
6779 }
6780
6781 /**
6782  * Parse a character constant.
6783  */
6784 static expression_t *parse_character_constant(void)
6785 {
6786         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6787         cnst->base.type          = token.datatype;
6788         cnst->conste.v.character = token.v.string;
6789
6790         if (cnst->conste.v.character.size != 1) {
6791                 if (!GNU_MODE) {
6792                         errorf(HERE, "more than 1 character in character constant");
6793                 } else if (warning.multichar) {
6794                         warningf(HERE, "multi-character character constant");
6795                 }
6796         }
6797         next_token();
6798
6799         return cnst;
6800 }
6801
6802 /**
6803  * Parse a wide character constant.
6804  */
6805 static expression_t *parse_wide_character_constant(void)
6806 {
6807         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6808         cnst->base.type               = token.datatype;
6809         cnst->conste.v.wide_character = token.v.wide_string;
6810
6811         if (cnst->conste.v.wide_character.size != 1) {
6812                 if (!GNU_MODE) {
6813                         errorf(HERE, "more than 1 character in character constant");
6814                 } else if (warning.multichar) {
6815                         warningf(HERE, "multi-character character constant");
6816                 }
6817         }
6818         next_token();
6819
6820         return cnst;
6821 }
6822
6823 /**
6824  * Parse a float constant.
6825  */
6826 static expression_t *parse_float_const(void)
6827 {
6828         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
6829         cnst->base.type            = token.datatype;
6830         cnst->conste.v.float_value = token.v.floatvalue;
6831
6832         next_token();
6833
6834         return cnst;
6835 }
6836
6837 static entity_t *create_implicit_function(symbol_t *symbol,
6838                 const source_position_t *source_position)
6839 {
6840         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
6841         ntype->function.return_type            = type_int;
6842         ntype->function.unspecified_parameters = true;
6843         ntype->function.linkage                = LINKAGE_C;
6844         type_t *type                           = identify_new_type(ntype);
6845
6846         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6847         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
6848         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6849         entity->declaration.type                   = type;
6850         entity->declaration.implicit               = true;
6851         entity->base.symbol                        = symbol;
6852         entity->base.source_position               = *source_position;
6853
6854         bool strict_prototypes_old = warning.strict_prototypes;
6855         warning.strict_prototypes  = false;
6856         record_entity(entity, false);
6857         warning.strict_prototypes = strict_prototypes_old;
6858
6859         return entity;
6860 }
6861
6862 /**
6863  * Creates a return_type (func)(argument_type) function type if not
6864  * already exists.
6865  */
6866 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6867                                     type_t *argument_type2)
6868 {
6869         function_parameter_t *parameter2
6870                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6871         memset(parameter2, 0, sizeof(parameter2[0]));
6872         parameter2->type = argument_type2;
6873
6874         function_parameter_t *parameter1
6875                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6876         memset(parameter1, 0, sizeof(parameter1[0]));
6877         parameter1->type = argument_type1;
6878         parameter1->next = parameter2;
6879
6880         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6881         type->function.return_type = return_type;
6882         type->function.parameters  = parameter1;
6883
6884         return identify_new_type(type);
6885 }
6886
6887 /**
6888  * Creates a return_type (func)(argument_type) function type if not
6889  * already exists.
6890  *
6891  * @param return_type    the return type
6892  * @param argument_type  the argument type
6893  */
6894 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6895 {
6896         function_parameter_t *parameter
6897                 = obstack_alloc(type_obst, sizeof(parameter[0]));
6898         memset(parameter, 0, sizeof(parameter[0]));
6899         parameter->type = argument_type;
6900
6901         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6902         type->function.return_type = return_type;
6903         type->function.parameters  = parameter;
6904
6905         return identify_new_type(type);
6906 }
6907
6908 static type_t *make_function_0_type(type_t *return_type)
6909 {
6910         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6911         type->function.return_type = return_type;
6912         type->function.parameters  = NULL;
6913
6914         return identify_new_type(type);
6915 }
6916
6917 /**
6918  * Creates a function type for some function like builtins.
6919  *
6920  * @param symbol   the symbol describing the builtin
6921  */
6922 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6923 {
6924         switch (symbol->ID) {
6925         case T___builtin_alloca:
6926                 return make_function_1_type(type_void_ptr, type_size_t);
6927         case T___builtin_huge_val:
6928                 return make_function_0_type(type_double);
6929         case T___builtin_inf:
6930                 return make_function_0_type(type_double);
6931         case T___builtin_inff:
6932                 return make_function_0_type(type_float);
6933         case T___builtin_infl:
6934                 return make_function_0_type(type_long_double);
6935         case T___builtin_nan:
6936                 return make_function_1_type(type_double, type_char_ptr);
6937         case T___builtin_nanf:
6938                 return make_function_1_type(type_float, type_char_ptr);
6939         case T___builtin_nanl:
6940                 return make_function_1_type(type_long_double, type_char_ptr);
6941         case T___builtin_va_end:
6942                 return make_function_1_type(type_void, type_valist);
6943         case T___builtin_expect:
6944                 return make_function_2_type(type_long, type_long, type_long);
6945         case T___builtin_return_address:
6946         case T___builtin_frame_address:
6947                 return make_function_1_type(type_void_ptr, type_unsigned_int);
6948         default:
6949                 internal_errorf(HERE, "not implemented builtin identifier found");
6950         }
6951 }
6952
6953 /**
6954  * Performs automatic type cast as described in § 6.3.2.1.
6955  *
6956  * @param orig_type  the original type
6957  */
6958 static type_t *automatic_type_conversion(type_t *orig_type)
6959 {
6960         type_t *type = skip_typeref(orig_type);
6961         if (is_type_array(type)) {
6962                 array_type_t *array_type   = &type->array;
6963                 type_t       *element_type = array_type->element_type;
6964                 unsigned      qualifiers   = array_type->base.qualifiers;
6965
6966                 return make_pointer_type(element_type, qualifiers);
6967         }
6968
6969         if (is_type_function(type)) {
6970                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6971         }
6972
6973         return orig_type;
6974 }
6975
6976 /**
6977  * reverts the automatic casts of array to pointer types and function
6978  * to function-pointer types as defined § 6.3.2.1
6979  */
6980 type_t *revert_automatic_type_conversion(const expression_t *expression)
6981 {
6982         switch (expression->kind) {
6983                 case EXPR_REFERENCE: {
6984                         entity_t *entity = expression->reference.entity;
6985                         if (is_declaration(entity)) {
6986                                 return entity->declaration.type;
6987                         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6988                                 return entity->enum_value.enum_type;
6989                         } else {
6990                                 panic("no declaration or enum in reference");
6991                         }
6992                 }
6993
6994                 case EXPR_SELECT: {
6995                         entity_t *entity = expression->select.compound_entry;
6996                         assert(is_declaration(entity));
6997                         type_t   *type   = entity->declaration.type;
6998                         return get_qualified_type(type,
6999                                         expression->base.type->base.qualifiers);
7000                 }
7001
7002                 case EXPR_UNARY_DEREFERENCE: {
7003                         const expression_t *const value = expression->unary.value;
7004                         type_t             *const type  = skip_typeref(value->base.type);
7005                         if (!is_type_pointer(type))
7006                                 return type_error_type;
7007                         return type->pointer.points_to;
7008                 }
7009
7010                 case EXPR_BUILTIN_SYMBOL:
7011                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
7012
7013                 case EXPR_ARRAY_ACCESS: {
7014                         const expression_t *array_ref = expression->array_access.array_ref;
7015                         type_t             *type_left = skip_typeref(array_ref->base.type);
7016                         if (!is_type_pointer(type_left))
7017                                 return type_error_type;
7018                         return type_left->pointer.points_to;
7019                 }
7020
7021                 case EXPR_STRING_LITERAL: {
7022                         size_t size = expression->string.value.size;
7023                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7024                 }
7025
7026                 case EXPR_WIDE_STRING_LITERAL: {
7027                         size_t size = expression->wide_string.value.size;
7028                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7029                 }
7030
7031                 case EXPR_COMPOUND_LITERAL:
7032                         return expression->compound_literal.type;
7033
7034                 default:
7035                         return expression->base.type;
7036         }
7037 }
7038
7039 static expression_t *parse_reference(void)
7040 {
7041         symbol_t *const symbol = token.v.symbol;
7042
7043         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7044
7045         if (entity == NULL) {
7046                 if (!strict_mode && look_ahead(1)->type == '(') {
7047                         /* an implicitly declared function */
7048                         if (warning.error_implicit_function_declaration) {
7049                                 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7050                         } else if (warning.implicit_function_declaration) {
7051                                 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7052                         }
7053
7054                         entity = create_implicit_function(symbol, HERE);
7055                 } else {
7056                         errorf(HERE, "unknown identifier '%Y' found.", symbol);
7057                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
7058                 }
7059         }
7060
7061         type_t *orig_type;
7062
7063         if (is_declaration(entity)) {
7064                 orig_type = entity->declaration.type;
7065         } else if (entity->kind == ENTITY_ENUM_VALUE) {
7066                 orig_type = entity->enum_value.enum_type;
7067         } else if (entity->kind == ENTITY_TYPEDEF) {
7068                 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7069                         symbol);
7070                 next_token();
7071                 return create_invalid_expression();
7072         } else {
7073                 panic("expected declaration or enum value in reference");
7074         }
7075
7076         /* we always do the auto-type conversions; the & and sizeof parser contains
7077          * code to revert this! */
7078         type_t *type = automatic_type_conversion(orig_type);
7079
7080         expression_kind_t kind = EXPR_REFERENCE;
7081         if (entity->kind == ENTITY_ENUM_VALUE)
7082                 kind = EXPR_REFERENCE_ENUM_VALUE;
7083
7084         expression_t *expression     = allocate_expression_zero(kind);
7085         expression->reference.entity = entity;
7086         expression->base.type        = type;
7087
7088         /* this declaration is used */
7089         if (is_declaration(entity)) {
7090                 entity->declaration.used = true;
7091         }
7092
7093         if (entity->base.parent_scope != file_scope
7094                 && entity->base.parent_scope->depth < current_function->parameters.depth
7095                 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7096                 if (entity->kind == ENTITY_VARIABLE) {
7097                         /* access of a variable from an outer function */
7098                         entity->variable.address_taken = true;
7099                 } else if (entity->kind == ENTITY_PARAMETER) {
7100                         entity->parameter.address_taken = true;
7101                 }
7102                 current_function->need_closure = true;
7103         }
7104
7105         /* check for deprecated functions */
7106         if (warning.deprecated_declarations
7107                 && is_declaration(entity)
7108                 && entity->declaration.modifiers & DM_DEPRECATED) {
7109                 declaration_t *declaration = &entity->declaration;
7110
7111                 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7112                         "function" : "variable";
7113
7114                 if (declaration->deprecated_string != NULL) {
7115                         warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7116                                  prefix, entity->base.symbol, &entity->base.source_position,
7117                                  declaration->deprecated_string);
7118                 } else {
7119                         warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7120                                  entity->base.symbol, &entity->base.source_position);
7121                 }
7122         }
7123
7124         if (warning.init_self && entity == current_init_decl && !in_type_prop
7125             && entity->kind == ENTITY_VARIABLE) {
7126                 current_init_decl = NULL;
7127                 warningf(HERE, "variable '%#T' is initialized by itself",
7128                          entity->declaration.type, entity->base.symbol);
7129         }
7130
7131         next_token();
7132         return expression;
7133 }
7134
7135 static bool semantic_cast(expression_t *cast)
7136 {
7137         expression_t            *expression      = cast->unary.value;
7138         type_t                  *orig_dest_type  = cast->base.type;
7139         type_t                  *orig_type_right = expression->base.type;
7140         type_t            const *dst_type        = skip_typeref(orig_dest_type);
7141         type_t            const *src_type        = skip_typeref(orig_type_right);
7142         source_position_t const *pos             = &cast->base.source_position;
7143
7144         /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7145         if (dst_type == type_void)
7146                 return true;
7147
7148         /* only integer and pointer can be casted to pointer */
7149         if (is_type_pointer(dst_type)  &&
7150             !is_type_pointer(src_type) &&
7151             !is_type_integer(src_type) &&
7152             is_type_valid(src_type)) {
7153                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7154                 return false;
7155         }
7156
7157         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7158                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7159                 return false;
7160         }
7161
7162         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7163                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7164                 return false;
7165         }
7166
7167         if (warning.cast_qual &&
7168             is_type_pointer(src_type) &&
7169             is_type_pointer(dst_type)) {
7170                 type_t *src = skip_typeref(src_type->pointer.points_to);
7171                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7172                 unsigned missing_qualifiers =
7173                         src->base.qualifiers & ~dst->base.qualifiers;
7174                 if (missing_qualifiers != 0) {
7175                         warningf(pos,
7176                                  "cast discards qualifiers '%Q' in pointer target type of '%T'",
7177                                  missing_qualifiers, orig_type_right);
7178                 }
7179         }
7180         return true;
7181 }
7182
7183 static expression_t *parse_compound_literal(type_t *type)
7184 {
7185         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7186
7187         parse_initializer_env_t env;
7188         env.type             = type;
7189         env.entity           = NULL;
7190         env.must_be_constant = false;
7191         initializer_t *initializer = parse_initializer(&env);
7192         type = env.type;
7193
7194         expression->compound_literal.initializer = initializer;
7195         expression->compound_literal.type        = type;
7196         expression->base.type                    = automatic_type_conversion(type);
7197
7198         return expression;
7199 }
7200
7201 /**
7202  * Parse a cast expression.
7203  */
7204 static expression_t *parse_cast(void)
7205 {
7206         add_anchor_token(')');
7207
7208         source_position_t source_position = token.source_position;
7209
7210         type_t *type = parse_typename();
7211
7212         rem_anchor_token(')');
7213         expect(')', end_error);
7214
7215         if (token.type == '{') {
7216                 return parse_compound_literal(type);
7217         }
7218
7219         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7220         cast->base.source_position = source_position;
7221
7222         expression_t *value = parse_sub_expression(PREC_CAST);
7223         cast->base.type   = type;
7224         cast->unary.value = value;
7225
7226         if (! semantic_cast(cast)) {
7227                 /* TODO: record the error in the AST. else it is impossible to detect it */
7228         }
7229
7230         return cast;
7231 end_error:
7232         return create_invalid_expression();
7233 }
7234
7235 /**
7236  * Parse a statement expression.
7237  */
7238 static expression_t *parse_statement_expression(void)
7239 {
7240         add_anchor_token(')');
7241
7242         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7243
7244         statement_t *statement          = parse_compound_statement(true);
7245         statement->compound.stmt_expr   = true;
7246         expression->statement.statement = statement;
7247
7248         /* find last statement and use its type */
7249         type_t *type = type_void;
7250         const statement_t *stmt = statement->compound.statements;
7251         if (stmt != NULL) {
7252                 while (stmt->base.next != NULL)
7253                         stmt = stmt->base.next;
7254
7255                 if (stmt->kind == STATEMENT_EXPRESSION) {
7256                         type = stmt->expression.expression->base.type;
7257                 }
7258         } else if (warning.other) {
7259                 warningf(&expression->base.source_position, "empty statement expression ({})");
7260         }
7261         expression->base.type = type;
7262
7263         rem_anchor_token(')');
7264         expect(')', end_error);
7265
7266 end_error:
7267         return expression;
7268 }
7269
7270 /**
7271  * Parse a parenthesized expression.
7272  */
7273 static expression_t *parse_parenthesized_expression(void)
7274 {
7275         eat('(');
7276
7277         switch (token.type) {
7278         case '{':
7279                 /* gcc extension: a statement expression */
7280                 return parse_statement_expression();
7281
7282         TYPE_QUALIFIERS
7283         TYPE_SPECIFIERS
7284                 return parse_cast();
7285         case T_IDENTIFIER:
7286                 if (is_typedef_symbol(token.v.symbol)) {
7287                         return parse_cast();
7288                 }
7289         }
7290
7291         add_anchor_token(')');
7292         expression_t *result = parse_expression();
7293         result->base.parenthesized = true;
7294         rem_anchor_token(')');
7295         expect(')', end_error);
7296
7297 end_error:
7298         return result;
7299 }
7300
7301 static expression_t *parse_function_keyword(void)
7302 {
7303         /* TODO */
7304
7305         if (current_function == NULL) {
7306                 errorf(HERE, "'__func__' used outside of a function");
7307         }
7308
7309         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7310         expression->base.type     = type_char_ptr;
7311         expression->funcname.kind = FUNCNAME_FUNCTION;
7312
7313         next_token();
7314
7315         return expression;
7316 }
7317
7318 static expression_t *parse_pretty_function_keyword(void)
7319 {
7320         if (current_function == NULL) {
7321                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7322         }
7323
7324         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7325         expression->base.type     = type_char_ptr;
7326         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7327
7328         eat(T___PRETTY_FUNCTION__);
7329
7330         return expression;
7331 }
7332
7333 static expression_t *parse_funcsig_keyword(void)
7334 {
7335         if (current_function == NULL) {
7336                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7337         }
7338
7339         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7340         expression->base.type     = type_char_ptr;
7341         expression->funcname.kind = FUNCNAME_FUNCSIG;
7342
7343         eat(T___FUNCSIG__);
7344
7345         return expression;
7346 }
7347
7348 static expression_t *parse_funcdname_keyword(void)
7349 {
7350         if (current_function == NULL) {
7351                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7352         }
7353
7354         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7355         expression->base.type     = type_char_ptr;
7356         expression->funcname.kind = FUNCNAME_FUNCDNAME;
7357
7358         eat(T___FUNCDNAME__);
7359
7360         return expression;
7361 }
7362
7363 static designator_t *parse_designator(void)
7364 {
7365         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
7366         result->source_position = *HERE;
7367
7368         if (token.type != T_IDENTIFIER) {
7369                 parse_error_expected("while parsing member designator",
7370                                      T_IDENTIFIER, NULL);
7371                 return NULL;
7372         }
7373         result->symbol = token.v.symbol;
7374         next_token();
7375
7376         designator_t *last_designator = result;
7377         while (true) {
7378                 if (token.type == '.') {
7379                         next_token();
7380                         if (token.type != T_IDENTIFIER) {
7381                                 parse_error_expected("while parsing member designator",
7382                                                      T_IDENTIFIER, NULL);
7383                                 return NULL;
7384                         }
7385                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7386                         designator->source_position = *HERE;
7387                         designator->symbol          = token.v.symbol;
7388                         next_token();
7389
7390                         last_designator->next = designator;
7391                         last_designator       = designator;
7392                         continue;
7393                 }
7394                 if (token.type == '[') {
7395                         next_token();
7396                         add_anchor_token(']');
7397                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7398                         designator->source_position = *HERE;
7399                         designator->array_index     = parse_expression();
7400                         rem_anchor_token(']');
7401                         expect(']', end_error);
7402                         if (designator->array_index == NULL) {
7403                                 return NULL;
7404                         }
7405
7406                         last_designator->next = designator;
7407                         last_designator       = designator;
7408                         continue;
7409                 }
7410                 break;
7411         }
7412
7413         return result;
7414 end_error:
7415         return NULL;
7416 }
7417
7418 /**
7419  * Parse the __builtin_offsetof() expression.
7420  */
7421 static expression_t *parse_offsetof(void)
7422 {
7423         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7424         expression->base.type    = type_size_t;
7425
7426         eat(T___builtin_offsetof);
7427
7428         expect('(', end_error);
7429         add_anchor_token(',');
7430         type_t *type = parse_typename();
7431         rem_anchor_token(',');
7432         expect(',', end_error);
7433         add_anchor_token(')');
7434         designator_t *designator = parse_designator();
7435         rem_anchor_token(')');
7436         expect(')', end_error);
7437
7438         expression->offsetofe.type       = type;
7439         expression->offsetofe.designator = designator;
7440
7441         type_path_t path;
7442         memset(&path, 0, sizeof(path));
7443         path.top_type = type;
7444         path.path     = NEW_ARR_F(type_path_entry_t, 0);
7445
7446         descend_into_subtype(&path);
7447
7448         if (!walk_designator(&path, designator, true)) {
7449                 return create_invalid_expression();
7450         }
7451
7452         DEL_ARR_F(path.path);
7453
7454         return expression;
7455 end_error:
7456         return create_invalid_expression();
7457 }
7458
7459 /**
7460  * Parses a _builtin_va_start() expression.
7461  */
7462 static expression_t *parse_va_start(void)
7463 {
7464         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7465
7466         eat(T___builtin_va_start);
7467
7468         expect('(', end_error);
7469         add_anchor_token(',');
7470         expression->va_starte.ap = parse_assignment_expression();
7471         rem_anchor_token(',');
7472         expect(',', end_error);
7473         expression_t *const expr = parse_assignment_expression();
7474         if (expr->kind == EXPR_REFERENCE) {
7475                 entity_t *const entity = expr->reference.entity;
7476                 if (entity->base.parent_scope != &current_function->parameters
7477                                 || entity->base.next != NULL
7478                                 || entity->kind != ENTITY_PARAMETER) {
7479                         errorf(&expr->base.source_position,
7480                                "second argument of 'va_start' must be last parameter of the current function");
7481                 } else {
7482                         expression->va_starte.parameter = &entity->variable;
7483                 }
7484                 expect(')', end_error);
7485                 return expression;
7486         }
7487         expect(')', end_error);
7488 end_error:
7489         return create_invalid_expression();
7490 }
7491
7492 /**
7493  * Parses a _builtin_va_arg() expression.
7494  */
7495 static expression_t *parse_va_arg(void)
7496 {
7497         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7498
7499         eat(T___builtin_va_arg);
7500
7501         expect('(', end_error);
7502         expression->va_arge.ap = parse_assignment_expression();
7503         expect(',', end_error);
7504         expression->base.type = parse_typename();
7505         expect(')', end_error);
7506
7507         return expression;
7508 end_error:
7509         return create_invalid_expression();
7510 }
7511
7512 static expression_t *parse_builtin_symbol(void)
7513 {
7514         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7515
7516         symbol_t *symbol = token.v.symbol;
7517
7518         expression->builtin_symbol.symbol = symbol;
7519         next_token();
7520
7521         type_t *type = get_builtin_symbol_type(symbol);
7522         type = automatic_type_conversion(type);
7523
7524         expression->base.type = type;
7525         return expression;
7526 }
7527
7528 /**
7529  * Parses a __builtin_constant() expression.
7530  */
7531 static expression_t *parse_builtin_constant(void)
7532 {
7533         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7534
7535         eat(T___builtin_constant_p);
7536
7537         expect('(', end_error);
7538         add_anchor_token(')');
7539         expression->builtin_constant.value = parse_assignment_expression();
7540         rem_anchor_token(')');
7541         expect(')', end_error);
7542         expression->base.type = type_int;
7543
7544         return expression;
7545 end_error:
7546         return create_invalid_expression();
7547 }
7548
7549 /**
7550  * Parses a __builtin_prefetch() expression.
7551  */
7552 static expression_t *parse_builtin_prefetch(void)
7553 {
7554         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7555
7556         eat(T___builtin_prefetch);
7557
7558         expect('(', end_error);
7559         add_anchor_token(')');
7560         expression->builtin_prefetch.adr = parse_assignment_expression();
7561         if (token.type == ',') {
7562                 next_token();
7563                 expression->builtin_prefetch.rw = parse_assignment_expression();
7564         }
7565         if (token.type == ',') {
7566                 next_token();
7567                 expression->builtin_prefetch.locality = parse_assignment_expression();
7568         }
7569         rem_anchor_token(')');
7570         expect(')', end_error);
7571         expression->base.type = type_void;
7572
7573         return expression;
7574 end_error:
7575         return create_invalid_expression();
7576 }
7577
7578 /**
7579  * Parses a __buildin_return_address of a __builtin_frame_address() expression.
7580  *
7581  * @param tok_type  either T___buildin_return_address or T___builtin_frame_address
7582  */
7583 static expression_t *parse_builtin_address(int tok_type)
7584 {
7585         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_ADDRESS);
7586
7587         expression->builtin_address.kind = tok_type == T___builtin_return_address ?
7588                 builtin_return_address : builtin_frame_address;
7589
7590         eat(tok_type);
7591
7592         expect('(', end_error);
7593         add_anchor_token(')');
7594         expression->builtin_address.value = parse_constant_expression();
7595         rem_anchor_token(')');
7596         expect(')', end_error);
7597         expression->base.type = type_void_ptr;
7598
7599         return expression;
7600 end_error:
7601         return create_invalid_expression();
7602 }
7603
7604 /**
7605  * Parses a __builtin_is_*() compare expression.
7606  */
7607 static expression_t *parse_compare_builtin(void)
7608 {
7609         expression_t *expression;
7610
7611         switch (token.type) {
7612         case T___builtin_isgreater:
7613                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7614                 break;
7615         case T___builtin_isgreaterequal:
7616                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7617                 break;
7618         case T___builtin_isless:
7619                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7620                 break;
7621         case T___builtin_islessequal:
7622                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7623                 break;
7624         case T___builtin_islessgreater:
7625                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7626                 break;
7627         case T___builtin_isunordered:
7628                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7629                 break;
7630         default:
7631                 internal_errorf(HERE, "invalid compare builtin found");
7632         }
7633         expression->base.source_position = *HERE;
7634         next_token();
7635
7636         expect('(', end_error);
7637         expression->binary.left = parse_assignment_expression();
7638         expect(',', end_error);
7639         expression->binary.right = parse_assignment_expression();
7640         expect(')', end_error);
7641
7642         type_t *const orig_type_left  = expression->binary.left->base.type;
7643         type_t *const orig_type_right = expression->binary.right->base.type;
7644
7645         type_t *const type_left  = skip_typeref(orig_type_left);
7646         type_t *const type_right = skip_typeref(orig_type_right);
7647         if (!is_type_float(type_left) && !is_type_float(type_right)) {
7648                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7649                         type_error_incompatible("invalid operands in comparison",
7650                                 &expression->base.source_position, orig_type_left, orig_type_right);
7651                 }
7652         } else {
7653                 semantic_comparison(&expression->binary);
7654         }
7655
7656         return expression;
7657 end_error:
7658         return create_invalid_expression();
7659 }
7660
7661 #if 0
7662 /**
7663  * Parses a __builtin_expect(, end_error) expression.
7664  */
7665 static expression_t *parse_builtin_expect(void, end_error)
7666 {
7667         expression_t *expression
7668                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7669
7670         eat(T___builtin_expect);
7671
7672         expect('(', end_error);
7673         expression->binary.left = parse_assignment_expression();
7674         expect(',', end_error);
7675         expression->binary.right = parse_constant_expression();
7676         expect(')', end_error);
7677
7678         expression->base.type = expression->binary.left->base.type;
7679
7680         return expression;
7681 end_error:
7682         return create_invalid_expression();
7683 }
7684 #endif
7685
7686 /**
7687  * Parses a MS assume() expression.
7688  */
7689 static expression_t *parse_assume(void)
7690 {
7691         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7692
7693         eat(T__assume);
7694
7695         expect('(', end_error);
7696         add_anchor_token(')');
7697         expression->unary.value = parse_assignment_expression();
7698         rem_anchor_token(')');
7699         expect(')', end_error);
7700
7701         expression->base.type = type_void;
7702         return expression;
7703 end_error:
7704         return create_invalid_expression();
7705 }
7706
7707 /**
7708  * Return the declaration for a given label symbol or create a new one.
7709  *
7710  * @param symbol  the symbol of the label
7711  */
7712 static label_t *get_label(symbol_t *symbol)
7713 {
7714         entity_t *label;
7715         assert(current_function != NULL);
7716
7717         label = get_entity(symbol, NAMESPACE_LABEL);
7718         /* if we found a local label, we already created the declaration */
7719         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7720                 if (label->base.parent_scope != current_scope) {
7721                         assert(label->base.parent_scope->depth < current_scope->depth);
7722                         current_function->goto_to_outer = true;
7723                 }
7724                 return &label->label;
7725         }
7726
7727         label = get_entity(symbol, NAMESPACE_LABEL);
7728         /* if we found a label in the same function, then we already created the
7729          * declaration */
7730         if (label != NULL
7731                         && label->base.parent_scope == &current_function->parameters) {
7732                 return &label->label;
7733         }
7734
7735         /* otherwise we need to create a new one */
7736         label               = allocate_entity_zero(ENTITY_LABEL);
7737         label->base.namespc = NAMESPACE_LABEL;
7738         label->base.symbol  = symbol;
7739
7740         label_push(label);
7741
7742         return &label->label;
7743 }
7744
7745 /**
7746  * Parses a GNU && label address expression.
7747  */
7748 static expression_t *parse_label_address(void)
7749 {
7750         source_position_t source_position = token.source_position;
7751         eat(T_ANDAND);
7752         if (token.type != T_IDENTIFIER) {
7753                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7754                 goto end_error;
7755         }
7756         symbol_t *symbol = token.v.symbol;
7757         next_token();
7758
7759         label_t *label       = get_label(symbol);
7760         label->used          = true;
7761         label->address_taken = true;
7762
7763         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7764         expression->base.source_position = source_position;
7765
7766         /* label address is threaten as a void pointer */
7767         expression->base.type           = type_void_ptr;
7768         expression->label_address.label = label;
7769         return expression;
7770 end_error:
7771         return create_invalid_expression();
7772 }
7773
7774 /**
7775  * Parse a microsoft __noop expression.
7776  */
7777 static expression_t *parse_noop_expression(void)
7778 {
7779         /* the result is a (int)0 */
7780         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
7781         cnst->base.type            = type_int;
7782         cnst->conste.v.int_value   = 0;
7783         cnst->conste.is_ms_noop    = true;
7784
7785         eat(T___noop);
7786
7787         if (token.type == '(') {
7788                 /* parse arguments */
7789                 eat('(');
7790                 add_anchor_token(')');
7791                 add_anchor_token(',');
7792
7793                 if (token.type != ')') {
7794                         while (true) {
7795                                 (void)parse_assignment_expression();
7796                                 if (token.type != ',')
7797                                         break;
7798                                 next_token();
7799                         }
7800                 }
7801         }
7802         rem_anchor_token(',');
7803         rem_anchor_token(')');
7804         expect(')', end_error);
7805
7806 end_error:
7807         return cnst;
7808 }
7809
7810 /**
7811  * Parses a primary expression.
7812  */
7813 static expression_t *parse_primary_expression(void)
7814 {
7815         switch (token.type) {
7816                 case T_false:                    return parse_bool_const(false);
7817                 case T_true:                     return parse_bool_const(true);
7818                 case T_INTEGER:                  return parse_int_const();
7819                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
7820                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
7821                 case T_FLOATINGPOINT:            return parse_float_const();
7822                 case T_STRING_LITERAL:
7823                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
7824                 case T_IDENTIFIER:               return parse_reference();
7825                 case T___FUNCTION__:
7826                 case T___func__:                 return parse_function_keyword();
7827                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
7828                 case T___FUNCSIG__:              return parse_funcsig_keyword();
7829                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
7830                 case T___builtin_offsetof:       return parse_offsetof();
7831                 case T___builtin_va_start:       return parse_va_start();
7832                 case T___builtin_va_arg:         return parse_va_arg();
7833                 case T___builtin_expect:
7834                 case T___builtin_alloca:
7835                 case T___builtin_inf:
7836                 case T___builtin_inff:
7837                 case T___builtin_infl:
7838                 case T___builtin_nan:
7839                 case T___builtin_nanf:
7840                 case T___builtin_nanl:
7841                 case T___builtin_huge_val:
7842                 case T___builtin_va_end:         return parse_builtin_symbol();
7843                 case T___builtin_isgreater:
7844                 case T___builtin_isgreaterequal:
7845                 case T___builtin_isless:
7846                 case T___builtin_islessequal:
7847                 case T___builtin_islessgreater:
7848                 case T___builtin_isunordered:    return parse_compare_builtin();
7849                 case T___builtin_constant_p:     return parse_builtin_constant();
7850                 case T___builtin_prefetch:       return parse_builtin_prefetch();
7851                 case T___builtin_return_address: return parse_builtin_address(T___builtin_return_address);
7852                 case T___builtin_frame_address:  return parse_builtin_address(T___builtin_frame_address);
7853                 case T__assume:                  return parse_assume();
7854                 case T_ANDAND:
7855                         if (GNU_MODE)
7856                                 return parse_label_address();
7857                         break;
7858
7859                 case '(':                        return parse_parenthesized_expression();
7860                 case T___noop:                   return parse_noop_expression();
7861         }
7862
7863         errorf(HERE, "unexpected token %K, expected an expression", &token);
7864         return create_invalid_expression();
7865 }
7866
7867 /**
7868  * Check if the expression has the character type and issue a warning then.
7869  */
7870 static void check_for_char_index_type(const expression_t *expression)
7871 {
7872         type_t       *const type      = expression->base.type;
7873         const type_t *const base_type = skip_typeref(type);
7874
7875         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7876                         warning.char_subscripts) {
7877                 warningf(&expression->base.source_position,
7878                          "array subscript has type '%T'", type);
7879         }
7880 }
7881
7882 static expression_t *parse_array_expression(expression_t *left)
7883 {
7884         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7885
7886         eat('[');
7887         add_anchor_token(']');
7888
7889         expression_t *inside = parse_expression();
7890
7891         type_t *const orig_type_left   = left->base.type;
7892         type_t *const orig_type_inside = inside->base.type;
7893
7894         type_t *const type_left   = skip_typeref(orig_type_left);
7895         type_t *const type_inside = skip_typeref(orig_type_inside);
7896
7897         type_t                    *return_type;
7898         array_access_expression_t *array_access = &expression->array_access;
7899         if (is_type_pointer(type_left)) {
7900                 return_type             = type_left->pointer.points_to;
7901                 array_access->array_ref = left;
7902                 array_access->index     = inside;
7903                 check_for_char_index_type(inside);
7904         } else if (is_type_pointer(type_inside)) {
7905                 return_type             = type_inside->pointer.points_to;
7906                 array_access->array_ref = inside;
7907                 array_access->index     = left;
7908                 array_access->flipped   = true;
7909                 check_for_char_index_type(left);
7910         } else {
7911                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7912                         errorf(HERE,
7913                                 "array access on object with non-pointer types '%T', '%T'",
7914                                 orig_type_left, orig_type_inside);
7915                 }
7916                 return_type             = type_error_type;
7917                 array_access->array_ref = left;
7918                 array_access->index     = inside;
7919         }
7920
7921         expression->base.type = automatic_type_conversion(return_type);
7922
7923         rem_anchor_token(']');
7924         expect(']', end_error);
7925 end_error:
7926         return expression;
7927 }
7928
7929 static expression_t *parse_typeprop(expression_kind_t const kind)
7930 {
7931         expression_t  *tp_expression = allocate_expression_zero(kind);
7932         tp_expression->base.type     = type_size_t;
7933
7934         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7935
7936         /* we only refer to a type property, mark this case */
7937         bool old     = in_type_prop;
7938         in_type_prop = true;
7939
7940         type_t       *orig_type;
7941         expression_t *expression;
7942         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7943                 next_token();
7944                 add_anchor_token(')');
7945                 orig_type = parse_typename();
7946                 rem_anchor_token(')');
7947                 expect(')', end_error);
7948
7949                 if (token.type == '{') {
7950                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7951                          * starting with a compound literal */
7952                         expression = parse_compound_literal(orig_type);
7953                         goto typeprop_expression;
7954                 }
7955         } else {
7956                 expression = parse_sub_expression(PREC_UNARY);
7957
7958 typeprop_expression:
7959                 tp_expression->typeprop.tp_expression = expression;
7960
7961                 orig_type = revert_automatic_type_conversion(expression);
7962                 expression->base.type = orig_type;
7963         }
7964
7965         tp_expression->typeprop.type   = orig_type;
7966         type_t const* const type       = skip_typeref(orig_type);
7967         char   const* const wrong_type =
7968                 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL                  :
7969                 is_type_incomplete(type)                           ? "incomplete"          :
7970                 type->kind == TYPE_FUNCTION                        ? "function designator" :
7971                 type->kind == TYPE_BITFIELD                        ? "bitfield"            :
7972                 NULL;
7973         if (wrong_type != NULL) {
7974                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7975                 errorf(&tp_expression->base.source_position,
7976                                 "operand of %s expression must not be of %s type '%T'",
7977                                 what, wrong_type, orig_type);
7978         }
7979
7980 end_error:
7981         in_type_prop = old;
7982         return tp_expression;
7983 }
7984
7985 static expression_t *parse_sizeof(void)
7986 {
7987         return parse_typeprop(EXPR_SIZEOF);
7988 }
7989
7990 static expression_t *parse_alignof(void)
7991 {
7992         return parse_typeprop(EXPR_ALIGNOF);
7993 }
7994
7995 static expression_t *parse_select_expression(expression_t *compound)
7996 {
7997         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
7998         select->select.compound = compound;
7999
8000         assert(token.type == '.' || token.type == T_MINUSGREATER);
8001         bool is_pointer = (token.type == T_MINUSGREATER);
8002         next_token();
8003
8004         if (token.type != T_IDENTIFIER) {
8005                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
8006                 return select;
8007         }
8008         symbol_t *symbol = token.v.symbol;
8009         next_token();
8010
8011         type_t *const orig_type = compound->base.type;
8012         type_t *const type      = skip_typeref(orig_type);
8013
8014         type_t *type_left;
8015         bool    saw_error = false;
8016         if (is_type_pointer(type)) {
8017                 if (!is_pointer) {
8018                         errorf(HERE,
8019                                "request for member '%Y' in something not a struct or union, but '%T'",
8020                                symbol, orig_type);
8021                         saw_error = true;
8022                 }
8023                 type_left = skip_typeref(type->pointer.points_to);
8024         } else {
8025                 if (is_pointer && is_type_valid(type)) {
8026                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
8027                         saw_error = true;
8028                 }
8029                 type_left = type;
8030         }
8031
8032         entity_t *entry;
8033         if (type_left->kind == TYPE_COMPOUND_STRUCT ||
8034             type_left->kind == TYPE_COMPOUND_UNION) {
8035                 compound_t *compound = type_left->compound.compound;
8036
8037                 if (!compound->complete) {
8038                         errorf(HERE, "request for member '%Y' of incomplete type '%T'",
8039                                symbol, type_left);
8040                         goto create_error_entry;
8041                 }
8042
8043                 entry = find_compound_entry(compound, symbol);
8044                 if (entry == NULL) {
8045                         errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
8046                         goto create_error_entry;
8047                 }
8048         } else {
8049                 if (is_type_valid(type_left) && !saw_error) {
8050                         errorf(HERE,
8051                                "request for member '%Y' in something not a struct or union, but '%T'",
8052                                symbol, type_left);
8053                 }
8054 create_error_entry:
8055                 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8056         }
8057
8058         assert(is_declaration(entry));
8059         select->select.compound_entry = entry;
8060
8061         type_t *entry_type = entry->declaration.type;
8062         type_t *res_type
8063                 = get_qualified_type(entry_type, type_left->base.qualifiers);
8064
8065         /* we always do the auto-type conversions; the & and sizeof parser contains
8066          * code to revert this! */
8067         select->base.type = automatic_type_conversion(res_type);
8068
8069         type_t *skipped = skip_typeref(res_type);
8070         if (skipped->kind == TYPE_BITFIELD) {
8071                 select->base.type = skipped->bitfield.base_type;
8072         }
8073
8074         return select;
8075 }
8076
8077 static void check_call_argument(const function_parameter_t *parameter,
8078                                 call_argument_t *argument, unsigned pos)
8079 {
8080         type_t         *expected_type      = parameter->type;
8081         type_t         *expected_type_skip = skip_typeref(expected_type);
8082         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
8083         expression_t   *arg_expr           = argument->expression;
8084         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
8085
8086         /* handle transparent union gnu extension */
8087         if (is_type_union(expected_type_skip)
8088                         && (expected_type_skip->base.modifiers
8089                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8090                 compound_t *union_decl  = expected_type_skip->compound.compound;
8091                 type_t     *best_type   = NULL;
8092                 entity_t   *entry       = union_decl->members.entities;
8093                 for ( ; entry != NULL; entry = entry->base.next) {
8094                         assert(is_declaration(entry));
8095                         type_t *decl_type = entry->declaration.type;
8096                         error = semantic_assign(decl_type, arg_expr);
8097                         if (error == ASSIGN_ERROR_INCOMPATIBLE
8098                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8099                                 continue;
8100
8101                         if (error == ASSIGN_SUCCESS) {
8102                                 best_type = decl_type;
8103                         } else if (best_type == NULL) {
8104                                 best_type = decl_type;
8105                         }
8106                 }
8107
8108                 if (best_type != NULL) {
8109                         expected_type = best_type;
8110                 }
8111         }
8112
8113         error                = semantic_assign(expected_type, arg_expr);
8114         argument->expression = create_implicit_cast(argument->expression,
8115                                                     expected_type);
8116
8117         if (error != ASSIGN_SUCCESS) {
8118                 /* report exact scope in error messages (like "in argument 3") */
8119                 char buf[64];
8120                 snprintf(buf, sizeof(buf), "call argument %u", pos);
8121                 report_assign_error(error, expected_type, arg_expr,     buf,
8122                                                         &arg_expr->base.source_position);
8123         } else if (warning.traditional || warning.conversion) {
8124                 type_t *const promoted_type = get_default_promoted_type(arg_type);
8125                 if (!types_compatible(expected_type_skip, promoted_type) &&
8126                     !types_compatible(expected_type_skip, type_void_ptr) &&
8127                     !types_compatible(type_void_ptr,      promoted_type)) {
8128                         /* Deliberately show the skipped types in this warning */
8129                         warningf(&arg_expr->base.source_position,
8130                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
8131                                 pos, expected_type_skip, promoted_type);
8132                 }
8133         }
8134 }
8135
8136 /**
8137  * Parse a call expression, ie. expression '( ... )'.
8138  *
8139  * @param expression  the function address
8140  */
8141 static expression_t *parse_call_expression(expression_t *expression)
8142 {
8143         expression_t      *result = allocate_expression_zero(EXPR_CALL);
8144         call_expression_t *call   = &result->call;
8145         call->function            = expression;
8146
8147         type_t *const orig_type = expression->base.type;
8148         type_t *const type      = skip_typeref(orig_type);
8149
8150         function_type_t *function_type = NULL;
8151         if (is_type_pointer(type)) {
8152                 type_t *const to_type = skip_typeref(type->pointer.points_to);
8153
8154                 if (is_type_function(to_type)) {
8155                         function_type   = &to_type->function;
8156                         call->base.type = function_type->return_type;
8157                 }
8158         }
8159
8160         if (function_type == NULL && is_type_valid(type)) {
8161                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8162         }
8163
8164         /* parse arguments */
8165         eat('(');
8166         add_anchor_token(')');
8167         add_anchor_token(',');
8168
8169         if (token.type != ')') {
8170                 call_argument_t *last_argument = NULL;
8171
8172                 while (true) {
8173                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8174
8175                         argument->expression = parse_assignment_expression();
8176                         if (last_argument == NULL) {
8177                                 call->arguments = argument;
8178                         } else {
8179                                 last_argument->next = argument;
8180                         }
8181                         last_argument = argument;
8182
8183                         if (token.type != ',')
8184                                 break;
8185                         next_token();
8186                 }
8187         }
8188         rem_anchor_token(',');
8189         rem_anchor_token(')');
8190         expect(')', end_error);
8191
8192         if (function_type == NULL)
8193                 return result;
8194
8195         function_parameter_t *parameter = function_type->parameters;
8196         call_argument_t      *argument  = call->arguments;
8197         if (!function_type->unspecified_parameters) {
8198                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8199                                 parameter = parameter->next, argument = argument->next) {
8200                         check_call_argument(parameter, argument, ++pos);
8201                 }
8202
8203                 if (parameter != NULL) {
8204                         errorf(HERE, "too few arguments to function '%E'", expression);
8205                 } else if (argument != NULL && !function_type->variadic) {
8206                         errorf(HERE, "too many arguments to function '%E'", expression);
8207                 }
8208         }
8209
8210         /* do default promotion */
8211         for (; argument != NULL; argument = argument->next) {
8212                 type_t *type = argument->expression->base.type;
8213
8214                 type = get_default_promoted_type(type);
8215
8216                 argument->expression
8217                         = create_implicit_cast(argument->expression, type);
8218         }
8219
8220         check_format(&result->call);
8221
8222         if (warning.aggregate_return &&
8223             is_type_compound(skip_typeref(function_type->return_type))) {
8224                 warningf(&result->base.source_position,
8225                          "function call has aggregate value");
8226         }
8227
8228 end_error:
8229         return result;
8230 }
8231
8232 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8233
8234 static bool same_compound_type(const type_t *type1, const type_t *type2)
8235 {
8236         return
8237                 is_type_compound(type1) &&
8238                 type1->kind == type2->kind &&
8239                 type1->compound.compound == type2->compound.compound;
8240 }
8241
8242 static expression_t const *get_reference_address(expression_t const *expr)
8243 {
8244         bool regular_take_address = true;
8245         for (;;) {
8246                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8247                         expr = expr->unary.value;
8248                 } else {
8249                         regular_take_address = false;
8250                 }
8251
8252                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8253                         break;
8254
8255                 expr = expr->unary.value;
8256         }
8257
8258         if (expr->kind != EXPR_REFERENCE)
8259                 return NULL;
8260
8261         /* special case for functions which are automatically converted to a
8262          * pointer to function without an extra TAKE_ADDRESS operation */
8263         if (!regular_take_address &&
8264                         expr->reference.entity->kind != ENTITY_FUNCTION) {
8265                 return NULL;
8266         }
8267
8268         return expr;
8269 }
8270
8271 static void warn_reference_address_as_bool(expression_t const* expr)
8272 {
8273         if (!warning.address)
8274                 return;
8275
8276         expr = get_reference_address(expr);
8277         if (expr != NULL) {
8278                 warningf(&expr->base.source_position,
8279                          "the address of '%Y' will always evaluate as 'true'",
8280                          expr->reference.entity->base.symbol);
8281         }
8282 }
8283
8284 static void warn_assignment_in_condition(const expression_t *const expr)
8285 {
8286         if (!warning.parentheses)
8287                 return;
8288         if (expr->base.kind != EXPR_BINARY_ASSIGN)
8289                 return;
8290         if (expr->base.parenthesized)
8291                 return;
8292         warningf(&expr->base.source_position,
8293                         "suggest parentheses around assignment used as truth value");
8294 }
8295
8296 static void semantic_condition(expression_t const *const expr,
8297                                char const *const context)
8298 {
8299         type_t *const type = skip_typeref(expr->base.type);
8300         if (is_type_scalar(type)) {
8301                 warn_reference_address_as_bool(expr);
8302                 warn_assignment_in_condition(expr);
8303         } else if (is_type_valid(type)) {
8304                 errorf(&expr->base.source_position,
8305                                 "%s must have scalar type", context);
8306         }
8307 }
8308
8309 /**
8310  * Parse a conditional expression, ie. 'expression ? ... : ...'.
8311  *
8312  * @param expression  the conditional expression
8313  */
8314 static expression_t *parse_conditional_expression(expression_t *expression)
8315 {
8316         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8317
8318         conditional_expression_t *conditional = &result->conditional;
8319         conditional->condition                = expression;
8320
8321         eat('?');
8322         add_anchor_token(':');
8323
8324         /* §6.5.15:2  The first operand shall have scalar type. */
8325         semantic_condition(expression, "condition of conditional operator");
8326
8327         expression_t *true_expression = expression;
8328         bool          gnu_cond = false;
8329         if (GNU_MODE && token.type == ':') {
8330                 gnu_cond = true;
8331         } else {
8332                 true_expression = parse_expression();
8333         }
8334         rem_anchor_token(':');
8335         expect(':', end_error);
8336 end_error:;
8337         expression_t *false_expression =
8338                 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8339
8340         type_t *const orig_true_type  = true_expression->base.type;
8341         type_t *const orig_false_type = false_expression->base.type;
8342         type_t *const true_type       = skip_typeref(orig_true_type);
8343         type_t *const false_type      = skip_typeref(orig_false_type);
8344
8345         /* 6.5.15.3 */
8346         type_t *result_type;
8347         if (is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8348                         is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8349                 /* ISO/IEC 14882:1998(E) §5.16:2 */
8350                 if (true_expression->kind == EXPR_UNARY_THROW) {
8351                         result_type = false_type;
8352                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8353                         result_type = true_type;
8354                 } else {
8355                         if (warning.other && (
8356                                                 !is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8357                                                 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8358                                         )) {
8359                                 warningf(&conditional->base.source_position,
8360                                                 "ISO C forbids conditional expression with only one void side");
8361                         }
8362                         result_type = type_void;
8363                 }
8364         } else if (is_type_arithmetic(true_type)
8365                    && is_type_arithmetic(false_type)) {
8366                 result_type = semantic_arithmetic(true_type, false_type);
8367
8368                 true_expression  = create_implicit_cast(true_expression, result_type);
8369                 false_expression = create_implicit_cast(false_expression, result_type);
8370
8371                 conditional->true_expression  = true_expression;
8372                 conditional->false_expression = false_expression;
8373                 conditional->base.type        = result_type;
8374         } else if (same_compound_type(true_type, false_type)) {
8375                 /* just take 1 of the 2 types */
8376                 result_type = true_type;
8377         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8378                 type_t *pointer_type;
8379                 type_t *other_type;
8380                 expression_t *other_expression;
8381                 if (is_type_pointer(true_type) &&
8382                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8383                         pointer_type     = true_type;
8384                         other_type       = false_type;
8385                         other_expression = false_expression;
8386                 } else {
8387                         pointer_type     = false_type;
8388                         other_type       = true_type;
8389                         other_expression = true_expression;
8390                 }
8391
8392                 if (is_null_pointer_constant(other_expression)) {
8393                         result_type = pointer_type;
8394                 } else if (is_type_pointer(other_type)) {
8395                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8396                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
8397
8398                         type_t *to;
8399                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8400                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8401                                 to = type_void;
8402                         } else if (types_compatible(get_unqualified_type(to1),
8403                                                     get_unqualified_type(to2))) {
8404                                 to = to1;
8405                         } else {
8406                                 if (warning.other) {
8407                                         warningf(&conditional->base.source_position,
8408                                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
8409                                                         true_type, false_type);
8410                                 }
8411                                 to = type_void;
8412                         }
8413
8414                         type_t *const type =
8415                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8416                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8417                 } else if (is_type_integer(other_type)) {
8418                         if (warning.other) {
8419                                 warningf(&conditional->base.source_position,
8420                                                 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8421                         }
8422                         result_type = pointer_type;
8423                 } else {
8424                         if (is_type_valid(other_type)) {
8425                                 type_error_incompatible("while parsing conditional",
8426                                                 &expression->base.source_position, true_type, false_type);
8427                         }
8428                         result_type = type_error_type;
8429                 }
8430         } else {
8431                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8432                         type_error_incompatible("while parsing conditional",
8433                                                 &conditional->base.source_position, true_type,
8434                                                 false_type);
8435                 }
8436                 result_type = type_error_type;
8437         }
8438
8439         conditional->true_expression
8440                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8441         conditional->false_expression
8442                 = create_implicit_cast(false_expression, result_type);
8443         conditional->base.type = result_type;
8444         return result;
8445 }
8446
8447 /**
8448  * Parse an extension expression.
8449  */
8450 static expression_t *parse_extension(void)
8451 {
8452         eat(T___extension__);
8453
8454         bool old_gcc_extension   = in_gcc_extension;
8455         in_gcc_extension         = true;
8456         expression_t *expression = parse_sub_expression(PREC_UNARY);
8457         in_gcc_extension         = old_gcc_extension;
8458         return expression;
8459 }
8460
8461 /**
8462  * Parse a __builtin_classify_type() expression.
8463  */
8464 static expression_t *parse_builtin_classify_type(void)
8465 {
8466         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8467         result->base.type    = type_int;
8468
8469         eat(T___builtin_classify_type);
8470
8471         expect('(', end_error);
8472         add_anchor_token(')');
8473         expression_t *expression = parse_expression();
8474         rem_anchor_token(')');
8475         expect(')', end_error);
8476         result->classify_type.type_expression = expression;
8477
8478         return result;
8479 end_error:
8480         return create_invalid_expression();
8481 }
8482
8483 /**
8484  * Parse a delete expression
8485  * ISO/IEC 14882:1998(E) §5.3.5
8486  */
8487 static expression_t *parse_delete(void)
8488 {
8489         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8490         result->base.type          = type_void;
8491
8492         eat(T_delete);
8493
8494         if (token.type == '[') {
8495                 next_token();
8496                 result->kind = EXPR_UNARY_DELETE_ARRAY;
8497                 expect(']', end_error);
8498 end_error:;
8499         }
8500
8501         expression_t *const value = parse_sub_expression(PREC_CAST);
8502         result->unary.value = value;
8503
8504         type_t *const type = skip_typeref(value->base.type);
8505         if (!is_type_pointer(type)) {
8506                 if (is_type_valid(type)) {
8507                         errorf(&value->base.source_position,
8508                                         "operand of delete must have pointer type");
8509                 }
8510         } else if (warning.other &&
8511                         is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8512                 warningf(&value->base.source_position,
8513                                 "deleting 'void*' is undefined");
8514         }
8515
8516         return result;
8517 }
8518
8519 /**
8520  * Parse a throw expression
8521  * ISO/IEC 14882:1998(E) §15:1
8522  */
8523 static expression_t *parse_throw(void)
8524 {
8525         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8526         result->base.type          = type_void;
8527
8528         eat(T_throw);
8529
8530         expression_t *value = NULL;
8531         switch (token.type) {
8532                 EXPRESSION_START {
8533                         value = parse_assignment_expression();
8534                         /* ISO/IEC 14882:1998(E) §15.1:3 */
8535                         type_t *const orig_type = value->base.type;
8536                         type_t *const type      = skip_typeref(orig_type);
8537                         if (is_type_incomplete(type)) {
8538                                 errorf(&value->base.source_position,
8539                                                 "cannot throw object of incomplete type '%T'", orig_type);
8540                         } else if (is_type_pointer(type)) {
8541                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
8542                                 if (is_type_incomplete(points_to) &&
8543                                                 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8544                                         errorf(&value->base.source_position,
8545                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
8546                                 }
8547                         }
8548                 }
8549
8550                 default:
8551                         break;
8552         }
8553         result->unary.value = value;
8554
8555         return result;
8556 }
8557
8558 static bool check_pointer_arithmetic(const source_position_t *source_position,
8559                                      type_t *pointer_type,
8560                                      type_t *orig_pointer_type)
8561 {
8562         type_t *points_to = pointer_type->pointer.points_to;
8563         points_to = skip_typeref(points_to);
8564
8565         if (is_type_incomplete(points_to)) {
8566                 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8567                         errorf(source_position,
8568                                "arithmetic with pointer to incomplete type '%T' not allowed",
8569                                orig_pointer_type);
8570                         return false;
8571                 } else if (warning.pointer_arith) {
8572                         warningf(source_position,
8573                                  "pointer of type '%T' used in arithmetic",
8574                                  orig_pointer_type);
8575                 }
8576         } else if (is_type_function(points_to)) {
8577                 if (!GNU_MODE) {
8578                         errorf(source_position,
8579                                "arithmetic with pointer to function type '%T' not allowed",
8580                                orig_pointer_type);
8581                         return false;
8582                 } else if (warning.pointer_arith) {
8583                         warningf(source_position,
8584                                  "pointer to a function '%T' used in arithmetic",
8585                                  orig_pointer_type);
8586                 }
8587         }
8588         return true;
8589 }
8590
8591 static bool is_lvalue(const expression_t *expression)
8592 {
8593         /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8594         switch (expression->kind) {
8595         case EXPR_ARRAY_ACCESS:
8596         case EXPR_COMPOUND_LITERAL:
8597         case EXPR_REFERENCE:
8598         case EXPR_SELECT:
8599         case EXPR_UNARY_DEREFERENCE:
8600                 return true;
8601
8602         default: {
8603           type_t *type = skip_typeref(expression->base.type);
8604           return
8605                 /* ISO/IEC 14882:1998(E) §3.10:3 */
8606                 is_type_reference(type) ||
8607                 /* Claim it is an lvalue, if the type is invalid.  There was a parse
8608                  * error before, which maybe prevented properly recognizing it as
8609                  * lvalue. */
8610                 !is_type_valid(type);
8611         }
8612         }
8613 }
8614
8615 static void semantic_incdec(unary_expression_t *expression)
8616 {
8617         type_t *const orig_type = expression->value->base.type;
8618         type_t *const type      = skip_typeref(orig_type);
8619         if (is_type_pointer(type)) {
8620                 if (!check_pointer_arithmetic(&expression->base.source_position,
8621                                               type, orig_type)) {
8622                         return;
8623                 }
8624         } else if (!is_type_real(type) && is_type_valid(type)) {
8625                 /* TODO: improve error message */
8626                 errorf(&expression->base.source_position,
8627                        "operation needs an arithmetic or pointer type");
8628                 return;
8629         }
8630         if (!is_lvalue(expression->value)) {
8631                 /* TODO: improve error message */
8632                 errorf(&expression->base.source_position, "lvalue required as operand");
8633         }
8634         expression->base.type = orig_type;
8635 }
8636
8637 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8638 {
8639         type_t *const orig_type = expression->value->base.type;
8640         type_t *const type      = skip_typeref(orig_type);
8641         if (!is_type_arithmetic(type)) {
8642                 if (is_type_valid(type)) {
8643                         /* TODO: improve error message */
8644                         errorf(&expression->base.source_position,
8645                                 "operation needs an arithmetic type");
8646                 }
8647                 return;
8648         }
8649
8650         expression->base.type = orig_type;
8651 }
8652
8653 static void semantic_unexpr_plus(unary_expression_t *expression)
8654 {
8655         semantic_unexpr_arithmetic(expression);
8656         if (warning.traditional)
8657                 warningf(&expression->base.source_position,
8658                         "traditional C rejects the unary plus operator");
8659 }
8660
8661 static void semantic_not(unary_expression_t *expression)
8662 {
8663         /* §6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
8664         semantic_condition(expression->value, "operand of !");
8665         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8666 }
8667
8668 static void semantic_unexpr_integer(unary_expression_t *expression)
8669 {
8670         type_t *const orig_type = expression->value->base.type;
8671         type_t *const type      = skip_typeref(orig_type);
8672         if (!is_type_integer(type)) {
8673                 if (is_type_valid(type)) {
8674                         errorf(&expression->base.source_position,
8675                                "operand of ~ must be of integer type");
8676                 }
8677                 return;
8678         }
8679
8680         expression->base.type = orig_type;
8681 }
8682
8683 static void semantic_dereference(unary_expression_t *expression)
8684 {
8685         type_t *const orig_type = expression->value->base.type;
8686         type_t *const type      = skip_typeref(orig_type);
8687         if (!is_type_pointer(type)) {
8688                 if (is_type_valid(type)) {
8689                         errorf(&expression->base.source_position,
8690                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8691                 }
8692                 return;
8693         }
8694
8695         type_t *result_type   = type->pointer.points_to;
8696         result_type           = automatic_type_conversion(result_type);
8697         expression->base.type = result_type;
8698 }
8699
8700 /**
8701  * Record that an address is taken (expression represents an lvalue).
8702  *
8703  * @param expression       the expression
8704  * @param may_be_register  if true, the expression might be an register
8705  */
8706 static void set_address_taken(expression_t *expression, bool may_be_register)
8707 {
8708         if (expression->kind != EXPR_REFERENCE)
8709                 return;
8710
8711         entity_t *const entity = expression->reference.entity;
8712
8713         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8714                 return;
8715
8716         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8717                         && !may_be_register) {
8718                 errorf(&expression->base.source_position,
8719                                 "address of register %s '%Y' requested",
8720                                 get_entity_kind_name(entity->kind),     entity->base.symbol);
8721         }
8722
8723         if (entity->kind == ENTITY_VARIABLE) {
8724                 entity->variable.address_taken = true;
8725         } else {
8726                 assert(entity->kind == ENTITY_PARAMETER);
8727                 entity->parameter.address_taken = true;
8728         }
8729 }
8730
8731 /**
8732  * Check the semantic of the address taken expression.
8733  */
8734 static void semantic_take_addr(unary_expression_t *expression)
8735 {
8736         expression_t *value = expression->value;
8737         value->base.type    = revert_automatic_type_conversion(value);
8738
8739         type_t *orig_type = value->base.type;
8740         type_t *type      = skip_typeref(orig_type);
8741         if (!is_type_valid(type))
8742                 return;
8743
8744         /* §6.5.3.2 */
8745         if (!is_lvalue(value)) {
8746                 errorf(&expression->base.source_position, "'&' requires an lvalue");
8747         }
8748         if (type->kind == TYPE_BITFIELD) {
8749                 errorf(&expression->base.source_position,
8750                        "'&' not allowed on object with bitfield type '%T'",
8751                        type);
8752         }
8753
8754         set_address_taken(value, false);
8755
8756         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8757 }
8758
8759 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8760 static expression_t *parse_##unexpression_type(void)                         \
8761 {                                                                            \
8762         expression_t *unary_expression                                           \
8763                 = allocate_expression_zero(unexpression_type);                       \
8764         eat(token_type);                                                         \
8765         unary_expression->unary.value = parse_sub_expression(PREC_UNARY);        \
8766                                                                                  \
8767         sfunc(&unary_expression->unary);                                         \
8768                                                                                  \
8769         return unary_expression;                                                 \
8770 }
8771
8772 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8773                                semantic_unexpr_arithmetic)
8774 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8775                                semantic_unexpr_plus)
8776 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8777                                semantic_not)
8778 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8779                                semantic_dereference)
8780 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8781                                semantic_take_addr)
8782 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8783                                semantic_unexpr_integer)
8784 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
8785                                semantic_incdec)
8786 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8787                                semantic_incdec)
8788
8789 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8790                                                sfunc)                         \
8791 static expression_t *parse_##unexpression_type(expression_t *left)            \
8792 {                                                                             \
8793         expression_t *unary_expression                                            \
8794                 = allocate_expression_zero(unexpression_type);                        \
8795         eat(token_type);                                                          \
8796         unary_expression->unary.value = left;                                     \
8797                                                                                   \
8798         sfunc(&unary_expression->unary);                                          \
8799                                                                               \
8800         return unary_expression;                                                  \
8801 }
8802
8803 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8804                                        EXPR_UNARY_POSTFIX_INCREMENT,
8805                                        semantic_incdec)
8806 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8807                                        EXPR_UNARY_POSTFIX_DECREMENT,
8808                                        semantic_incdec)
8809
8810 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8811 {
8812         /* TODO: handle complex + imaginary types */
8813
8814         type_left  = get_unqualified_type(type_left);
8815         type_right = get_unqualified_type(type_right);
8816
8817         /* § 6.3.1.8 Usual arithmetic conversions */
8818         if (type_left == type_long_double || type_right == type_long_double) {
8819                 return type_long_double;
8820         } else if (type_left == type_double || type_right == type_double) {
8821                 return type_double;
8822         } else if (type_left == type_float || type_right == type_float) {
8823                 return type_float;
8824         }
8825
8826         type_left  = promote_integer(type_left);
8827         type_right = promote_integer(type_right);
8828
8829         if (type_left == type_right)
8830                 return type_left;
8831
8832         bool const signed_left  = is_type_signed(type_left);
8833         bool const signed_right = is_type_signed(type_right);
8834         int const  rank_left    = get_rank(type_left);
8835         int const  rank_right   = get_rank(type_right);
8836
8837         if (signed_left == signed_right)
8838                 return rank_left >= rank_right ? type_left : type_right;
8839
8840         int     s_rank;
8841         int     u_rank;
8842         type_t *s_type;
8843         type_t *u_type;
8844         if (signed_left) {
8845                 s_rank = rank_left;
8846                 s_type = type_left;
8847                 u_rank = rank_right;
8848                 u_type = type_right;
8849         } else {
8850                 s_rank = rank_right;
8851                 s_type = type_right;
8852                 u_rank = rank_left;
8853                 u_type = type_left;
8854         }
8855
8856         if (u_rank >= s_rank)
8857                 return u_type;
8858
8859         /* casting rank to atomic_type_kind is a bit hacky, but makes things
8860          * easier here... */
8861         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8862                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
8863                 return s_type;
8864
8865         switch (s_rank) {
8866                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
8867                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
8868                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8869
8870                 default: panic("invalid atomic type");
8871         }
8872 }
8873
8874 /**
8875  * Check the semantic restrictions for a binary expression.
8876  */
8877 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8878 {
8879         expression_t *const left            = expression->left;
8880         expression_t *const right           = expression->right;
8881         type_t       *const orig_type_left  = left->base.type;
8882         type_t       *const orig_type_right = right->base.type;
8883         type_t       *const type_left       = skip_typeref(orig_type_left);
8884         type_t       *const type_right      = skip_typeref(orig_type_right);
8885
8886         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8887                 /* TODO: improve error message */
8888                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8889                         errorf(&expression->base.source_position,
8890                                "operation needs arithmetic types");
8891                 }
8892                 return;
8893         }
8894
8895         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8896         expression->left      = create_implicit_cast(left, arithmetic_type);
8897         expression->right     = create_implicit_cast(right, arithmetic_type);
8898         expression->base.type = arithmetic_type;
8899 }
8900
8901 static void warn_div_by_zero(binary_expression_t const *const expression)
8902 {
8903         if (!warning.div_by_zero ||
8904             !is_type_integer(expression->base.type))
8905                 return;
8906
8907         expression_t const *const right = expression->right;
8908         /* The type of the right operand can be different for /= */
8909         if (is_type_integer(right->base.type) &&
8910             is_constant_expression(right)     &&
8911             fold_constant(right) == 0) {
8912                 warningf(&expression->base.source_position, "division by zero");
8913         }
8914 }
8915
8916 /**
8917  * Check the semantic restrictions for a div/mod expression.
8918  */
8919 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8920 {
8921         semantic_binexpr_arithmetic(expression);
8922         warn_div_by_zero(expression);
8923 }
8924
8925 static void warn_addsub_in_shift(const expression_t *const expr)
8926 {
8927         if (expr->base.parenthesized)
8928                 return;
8929
8930         char op;
8931         switch (expr->kind) {
8932                 case EXPR_BINARY_ADD: op = '+'; break;
8933                 case EXPR_BINARY_SUB: op = '-'; break;
8934                 default:              return;
8935         }
8936
8937         warningf(&expr->base.source_position,
8938                         "suggest parentheses around '%c' inside shift", op);
8939 }
8940
8941 static void semantic_shift_op(binary_expression_t *expression)
8942 {
8943         expression_t *const left            = expression->left;
8944         expression_t *const right           = expression->right;
8945         type_t       *const orig_type_left  = left->base.type;
8946         type_t       *const orig_type_right = right->base.type;
8947         type_t       *      type_left       = skip_typeref(orig_type_left);
8948         type_t       *      type_right      = skip_typeref(orig_type_right);
8949
8950         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8951                 /* TODO: improve error message */
8952                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8953                         errorf(&expression->base.source_position,
8954                                "operands of shift operation must have integer types");
8955                 }
8956                 return;
8957         }
8958
8959         if (warning.parentheses) {
8960                 warn_addsub_in_shift(left);
8961                 warn_addsub_in_shift(right);
8962         }
8963
8964         type_left  = promote_integer(type_left);
8965         type_right = promote_integer(type_right);
8966
8967         expression->left      = create_implicit_cast(left, type_left);
8968         expression->right     = create_implicit_cast(right, type_right);
8969         expression->base.type = type_left;
8970 }
8971
8972 static void semantic_add(binary_expression_t *expression)
8973 {
8974         expression_t *const left            = expression->left;
8975         expression_t *const right           = expression->right;
8976         type_t       *const orig_type_left  = left->base.type;
8977         type_t       *const orig_type_right = right->base.type;
8978         type_t       *const type_left       = skip_typeref(orig_type_left);
8979         type_t       *const type_right      = skip_typeref(orig_type_right);
8980
8981         /* § 6.5.6 */
8982         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8983                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8984                 expression->left  = create_implicit_cast(left, arithmetic_type);
8985                 expression->right = create_implicit_cast(right, arithmetic_type);
8986                 expression->base.type = arithmetic_type;
8987         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8988                 check_pointer_arithmetic(&expression->base.source_position,
8989                                          type_left, orig_type_left);
8990                 expression->base.type = type_left;
8991         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8992                 check_pointer_arithmetic(&expression->base.source_position,
8993                                          type_right, orig_type_right);
8994                 expression->base.type = type_right;
8995         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8996                 errorf(&expression->base.source_position,
8997                        "invalid operands to binary + ('%T', '%T')",
8998                        orig_type_left, orig_type_right);
8999         }
9000 }
9001
9002 static void semantic_sub(binary_expression_t *expression)
9003 {
9004         expression_t            *const left            = expression->left;
9005         expression_t            *const right           = expression->right;
9006         type_t                  *const orig_type_left  = left->base.type;
9007         type_t                  *const orig_type_right = right->base.type;
9008         type_t                  *const type_left       = skip_typeref(orig_type_left);
9009         type_t                  *const type_right      = skip_typeref(orig_type_right);
9010         source_position_t const *const pos             = &expression->base.source_position;
9011
9012         /* § 5.6.5 */
9013         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9014                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9015                 expression->left        = create_implicit_cast(left, arithmetic_type);
9016                 expression->right       = create_implicit_cast(right, arithmetic_type);
9017                 expression->base.type =  arithmetic_type;
9018         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9019                 check_pointer_arithmetic(&expression->base.source_position,
9020                                          type_left, orig_type_left);
9021                 expression->base.type = type_left;
9022         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9023                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
9024                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
9025                 if (!types_compatible(unqual_left, unqual_right)) {
9026                         errorf(pos,
9027                                "subtracting pointers to incompatible types '%T' and '%T'",
9028                                orig_type_left, orig_type_right);
9029                 } else if (!is_type_object(unqual_left)) {
9030                         if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
9031                                 errorf(pos, "subtracting pointers to non-object types '%T'",
9032                                        orig_type_left);
9033                         } else if (warning.other) {
9034                                 warningf(pos, "subtracting pointers to void");
9035                         }
9036                 }
9037                 expression->base.type = type_ptrdiff_t;
9038         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9039                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9040                        orig_type_left, orig_type_right);
9041         }
9042 }
9043
9044 static void warn_string_literal_address(expression_t const* expr)
9045 {
9046         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9047                 expr = expr->unary.value;
9048                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9049                         return;
9050                 expr = expr->unary.value;
9051         }
9052
9053         if (expr->kind == EXPR_STRING_LITERAL ||
9054             expr->kind == EXPR_WIDE_STRING_LITERAL) {
9055                 warningf(&expr->base.source_position,
9056                         "comparison with string literal results in unspecified behaviour");
9057         }
9058 }
9059
9060 static void warn_comparison_in_comparison(const expression_t *const expr)
9061 {
9062         if (expr->base.parenthesized)
9063                 return;
9064         switch (expr->base.kind) {
9065                 case EXPR_BINARY_LESS:
9066                 case EXPR_BINARY_GREATER:
9067                 case EXPR_BINARY_LESSEQUAL:
9068                 case EXPR_BINARY_GREATEREQUAL:
9069                 case EXPR_BINARY_NOTEQUAL:
9070                 case EXPR_BINARY_EQUAL:
9071                         warningf(&expr->base.source_position,
9072                                         "comparisons like 'x <= y < z' do not have their mathematical meaning");
9073                         break;
9074                 default:
9075                         break;
9076         }
9077 }
9078
9079 static bool maybe_negative(expression_t const *const expr)
9080 {
9081         return
9082                 !is_constant_expression(expr) ||
9083                 fold_constant(expr) < 0;
9084 }
9085
9086 /**
9087  * Check the semantics of comparison expressions.
9088  *
9089  * @param expression   The expression to check.
9090  */
9091 static void semantic_comparison(binary_expression_t *expression)
9092 {
9093         expression_t *left  = expression->left;
9094         expression_t *right = expression->right;
9095
9096         if (warning.address) {
9097                 warn_string_literal_address(left);
9098                 warn_string_literal_address(right);
9099
9100                 expression_t const* const func_left = get_reference_address(left);
9101                 if (func_left != NULL && is_null_pointer_constant(right)) {
9102                         warningf(&expression->base.source_position,
9103                                  "the address of '%Y' will never be NULL",
9104                                  func_left->reference.entity->base.symbol);
9105                 }
9106
9107                 expression_t const* const func_right = get_reference_address(right);
9108                 if (func_right != NULL && is_null_pointer_constant(right)) {
9109                         warningf(&expression->base.source_position,
9110                                  "the address of '%Y' will never be NULL",
9111                                  func_right->reference.entity->base.symbol);
9112                 }
9113         }
9114
9115         if (warning.parentheses) {
9116                 warn_comparison_in_comparison(left);
9117                 warn_comparison_in_comparison(right);
9118         }
9119
9120         type_t *orig_type_left  = left->base.type;
9121         type_t *orig_type_right = right->base.type;
9122         type_t *type_left       = skip_typeref(orig_type_left);
9123         type_t *type_right      = skip_typeref(orig_type_right);
9124
9125         /* TODO non-arithmetic types */
9126         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9127                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9128
9129                 /* test for signed vs unsigned compares */
9130                 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9131                         bool const signed_left  = is_type_signed(type_left);
9132                         bool const signed_right = is_type_signed(type_right);
9133                         if (signed_left != signed_right) {
9134                                 /* FIXME long long needs better const folding magic */
9135                                 /* TODO check whether constant value can be represented by other type */
9136                                 if ((signed_left  && maybe_negative(left)) ||
9137                                                 (signed_right && maybe_negative(right))) {
9138                                         warningf(&expression->base.source_position,
9139                                                         "comparison between signed and unsigned");
9140                                 }
9141                         }
9142                 }
9143
9144                 expression->left        = create_implicit_cast(left, arithmetic_type);
9145                 expression->right       = create_implicit_cast(right, arithmetic_type);
9146                 expression->base.type   = arithmetic_type;
9147                 if (warning.float_equal &&
9148                     (expression->base.kind == EXPR_BINARY_EQUAL ||
9149                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9150                     is_type_float(arithmetic_type)) {
9151                         warningf(&expression->base.source_position,
9152                                  "comparing floating point with == or != is unsafe");
9153                 }
9154         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9155                 /* TODO check compatibility */
9156         } else if (is_type_pointer(type_left)) {
9157                 expression->right = create_implicit_cast(right, type_left);
9158         } else if (is_type_pointer(type_right)) {
9159                 expression->left = create_implicit_cast(left, type_right);
9160         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9161                 type_error_incompatible("invalid operands in comparison",
9162                                         &expression->base.source_position,
9163                                         type_left, type_right);
9164         }
9165         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9166 }
9167
9168 /**
9169  * Checks if a compound type has constant fields.
9170  */
9171 static bool has_const_fields(const compound_type_t *type)
9172 {
9173         compound_t *compound = type->compound;
9174         entity_t   *entry    = compound->members.entities;
9175
9176         for (; entry != NULL; entry = entry->base.next) {
9177                 if (!is_declaration(entry))
9178                         continue;
9179
9180                 const type_t *decl_type = skip_typeref(entry->declaration.type);
9181                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9182                         return true;
9183         }
9184
9185         return false;
9186 }
9187
9188 static bool is_valid_assignment_lhs(expression_t const* const left)
9189 {
9190         type_t *const orig_type_left = revert_automatic_type_conversion(left);
9191         type_t *const type_left      = skip_typeref(orig_type_left);
9192
9193         if (!is_lvalue(left)) {
9194                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9195                        left);
9196                 return false;
9197         }
9198
9199         if (left->kind == EXPR_REFERENCE
9200                         && left->reference.entity->kind == ENTITY_FUNCTION) {
9201                 errorf(HERE, "cannot assign to function '%E'", left);
9202                 return false;
9203         }
9204
9205         if (is_type_array(type_left)) {
9206                 errorf(HERE, "cannot assign to array '%E'", left);
9207                 return false;
9208         }
9209         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9210                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9211                        orig_type_left);
9212                 return false;
9213         }
9214         if (is_type_incomplete(type_left)) {
9215                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9216                        left, orig_type_left);
9217                 return false;
9218         }
9219         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9220                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9221                        left, orig_type_left);
9222                 return false;
9223         }
9224
9225         return true;
9226 }
9227
9228 static void semantic_arithmetic_assign(binary_expression_t *expression)
9229 {
9230         expression_t *left            = expression->left;
9231         expression_t *right           = expression->right;
9232         type_t       *orig_type_left  = left->base.type;
9233         type_t       *orig_type_right = right->base.type;
9234
9235         if (!is_valid_assignment_lhs(left))
9236                 return;
9237
9238         type_t *type_left  = skip_typeref(orig_type_left);
9239         type_t *type_right = skip_typeref(orig_type_right);
9240
9241         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9242                 /* TODO: improve error message */
9243                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9244                         errorf(&expression->base.source_position,
9245                                "operation needs arithmetic types");
9246                 }
9247                 return;
9248         }
9249
9250         /* combined instructions are tricky. We can't create an implicit cast on
9251          * the left side, because we need the uncasted form for the store.
9252          * The ast2firm pass has to know that left_type must be right_type
9253          * for the arithmetic operation and create a cast by itself */
9254         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9255         expression->right       = create_implicit_cast(right, arithmetic_type);
9256         expression->base.type   = type_left;
9257 }
9258
9259 static void semantic_divmod_assign(binary_expression_t *expression)
9260 {
9261         semantic_arithmetic_assign(expression);
9262         warn_div_by_zero(expression);
9263 }
9264
9265 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9266 {
9267         expression_t *const left            = expression->left;
9268         expression_t *const right           = expression->right;
9269         type_t       *const orig_type_left  = left->base.type;
9270         type_t       *const orig_type_right = right->base.type;
9271         type_t       *const type_left       = skip_typeref(orig_type_left);
9272         type_t       *const type_right      = skip_typeref(orig_type_right);
9273
9274         if (!is_valid_assignment_lhs(left))
9275                 return;
9276
9277         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9278                 /* combined instructions are tricky. We can't create an implicit cast on
9279                  * the left side, because we need the uncasted form for the store.
9280                  * The ast2firm pass has to know that left_type must be right_type
9281                  * for the arithmetic operation and create a cast by itself */
9282                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9283                 expression->right     = create_implicit_cast(right, arithmetic_type);
9284                 expression->base.type = type_left;
9285         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9286                 check_pointer_arithmetic(&expression->base.source_position,
9287                                          type_left, orig_type_left);
9288                 expression->base.type = type_left;
9289         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9290                 errorf(&expression->base.source_position,
9291                        "incompatible types '%T' and '%T' in assignment",
9292                        orig_type_left, orig_type_right);
9293         }
9294 }
9295
9296 static void warn_logical_and_within_or(const expression_t *const expr)
9297 {
9298         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9299                 return;
9300         if (expr->base.parenthesized)
9301                 return;
9302         warningf(&expr->base.source_position,
9303                         "suggest parentheses around && within ||");
9304 }
9305
9306 /**
9307  * Check the semantic restrictions of a logical expression.
9308  */
9309 static void semantic_logical_op(binary_expression_t *expression)
9310 {
9311         /* §6.5.13:2  Each of the operands shall have scalar type.
9312          * §6.5.14:2  Each of the operands shall have scalar type. */
9313         semantic_condition(expression->left,   "left operand of logical operator");
9314         semantic_condition(expression->right, "right operand of logical operator");
9315         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9316                         warning.parentheses) {
9317                 warn_logical_and_within_or(expression->left);
9318                 warn_logical_and_within_or(expression->right);
9319         }
9320         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9321 }
9322
9323 /**
9324  * Check the semantic restrictions of a binary assign expression.
9325  */
9326 static void semantic_binexpr_assign(binary_expression_t *expression)
9327 {
9328         expression_t *left           = expression->left;
9329         type_t       *orig_type_left = left->base.type;
9330
9331         if (!is_valid_assignment_lhs(left))
9332                 return;
9333
9334         assign_error_t error = semantic_assign(orig_type_left, expression->right);
9335         report_assign_error(error, orig_type_left, expression->right,
9336                         "assignment", &left->base.source_position);
9337         expression->right = create_implicit_cast(expression->right, orig_type_left);
9338         expression->base.type = orig_type_left;
9339 }
9340
9341 /**
9342  * Determine if the outermost operation (or parts thereof) of the given
9343  * expression has no effect in order to generate a warning about this fact.
9344  * Therefore in some cases this only examines some of the operands of the
9345  * expression (see comments in the function and examples below).
9346  * Examples:
9347  *   f() + 23;    // warning, because + has no effect
9348  *   x || f();    // no warning, because x controls execution of f()
9349  *   x ? y : f(); // warning, because y has no effect
9350  *   (void)x;     // no warning to be able to suppress the warning
9351  * This function can NOT be used for an "expression has definitely no effect"-
9352  * analysis. */
9353 static bool expression_has_effect(const expression_t *const expr)
9354 {
9355         switch (expr->kind) {
9356                 case EXPR_UNKNOWN:                   break;
9357                 case EXPR_INVALID:                   return true; /* do NOT warn */
9358                 case EXPR_REFERENCE:                 return false;
9359                 case EXPR_REFERENCE_ENUM_VALUE:      return false;
9360                 /* suppress the warning for microsoft __noop operations */
9361                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
9362                 case EXPR_CHARACTER_CONSTANT:        return false;
9363                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
9364                 case EXPR_STRING_LITERAL:            return false;
9365                 case EXPR_WIDE_STRING_LITERAL:       return false;
9366                 case EXPR_LABEL_ADDRESS:             return false;
9367
9368                 case EXPR_CALL: {
9369                         const call_expression_t *const call = &expr->call;
9370                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9371                                 return true;
9372
9373                         switch (call->function->builtin_symbol.symbol->ID) {
9374                                 case T___builtin_va_end: return true;
9375                                 default:                 return false;
9376                         }
9377                 }
9378
9379                 /* Generate the warning if either the left or right hand side of a
9380                  * conditional expression has no effect */
9381                 case EXPR_CONDITIONAL: {
9382                         const conditional_expression_t *const cond = &expr->conditional;
9383                         return
9384                                 expression_has_effect(cond->true_expression) &&
9385                                 expression_has_effect(cond->false_expression);
9386                 }
9387
9388                 case EXPR_SELECT:                    return false;
9389                 case EXPR_ARRAY_ACCESS:              return false;
9390                 case EXPR_SIZEOF:                    return false;
9391                 case EXPR_CLASSIFY_TYPE:             return false;
9392                 case EXPR_ALIGNOF:                   return false;
9393
9394                 case EXPR_FUNCNAME:                  return false;
9395                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
9396                 case EXPR_BUILTIN_CONSTANT_P:        return false;
9397                 case EXPR_BUILTIN_PREFETCH:          return true;
9398                 case EXPR_OFFSETOF:                  return false;
9399                 case EXPR_VA_START:                  return true;
9400                 case EXPR_VA_ARG:                    return true;
9401                 case EXPR_STATEMENT:                 return true; // TODO
9402                 case EXPR_COMPOUND_LITERAL:          return false;
9403
9404                 case EXPR_UNARY_NEGATE:              return false;
9405                 case EXPR_UNARY_PLUS:                return false;
9406                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
9407                 case EXPR_UNARY_NOT:                 return false;
9408                 case EXPR_UNARY_DEREFERENCE:         return false;
9409                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
9410                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
9411                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
9412                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
9413                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
9414
9415                 /* Treat void casts as if they have an effect in order to being able to
9416                  * suppress the warning */
9417                 case EXPR_UNARY_CAST: {
9418                         type_t *const type = skip_typeref(expr->base.type);
9419                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
9420                 }
9421
9422                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
9423                 case EXPR_UNARY_ASSUME:              return true;
9424                 case EXPR_UNARY_DELETE:              return true;
9425                 case EXPR_UNARY_DELETE_ARRAY:        return true;
9426                 case EXPR_UNARY_THROW:               return true;
9427
9428                 case EXPR_BINARY_ADD:                return false;
9429                 case EXPR_BINARY_SUB:                return false;
9430                 case EXPR_BINARY_MUL:                return false;
9431                 case EXPR_BINARY_DIV:                return false;
9432                 case EXPR_BINARY_MOD:                return false;
9433                 case EXPR_BINARY_EQUAL:              return false;
9434                 case EXPR_BINARY_NOTEQUAL:           return false;
9435                 case EXPR_BINARY_LESS:               return false;
9436                 case EXPR_BINARY_LESSEQUAL:          return false;
9437                 case EXPR_BINARY_GREATER:            return false;
9438                 case EXPR_BINARY_GREATEREQUAL:       return false;
9439                 case EXPR_BINARY_BITWISE_AND:        return false;
9440                 case EXPR_BINARY_BITWISE_OR:         return false;
9441                 case EXPR_BINARY_BITWISE_XOR:        return false;
9442                 case EXPR_BINARY_SHIFTLEFT:          return false;
9443                 case EXPR_BINARY_SHIFTRIGHT:         return false;
9444                 case EXPR_BINARY_ASSIGN:             return true;
9445                 case EXPR_BINARY_MUL_ASSIGN:         return true;
9446                 case EXPR_BINARY_DIV_ASSIGN:         return true;
9447                 case EXPR_BINARY_MOD_ASSIGN:         return true;
9448                 case EXPR_BINARY_ADD_ASSIGN:         return true;
9449                 case EXPR_BINARY_SUB_ASSIGN:         return true;
9450                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
9451                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
9452                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9453                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9454                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
9455
9456                 /* Only examine the right hand side of && and ||, because the left hand
9457                  * side already has the effect of controlling the execution of the right
9458                  * hand side */
9459                 case EXPR_BINARY_LOGICAL_AND:
9460                 case EXPR_BINARY_LOGICAL_OR:
9461                 /* Only examine the right hand side of a comma expression, because the left
9462                  * hand side has a separate warning */
9463                 case EXPR_BINARY_COMMA:
9464                         return expression_has_effect(expr->binary.right);
9465
9466                 case EXPR_BINARY_ISGREATER:          return false;
9467                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
9468                 case EXPR_BINARY_ISLESS:             return false;
9469                 case EXPR_BINARY_ISLESSEQUAL:        return false;
9470                 case EXPR_BINARY_ISLESSGREATER:      return false;
9471                 case EXPR_BINARY_ISUNORDERED:        return false;
9472         }
9473
9474         internal_errorf(HERE, "unexpected expression");
9475 }
9476
9477 static void semantic_comma(binary_expression_t *expression)
9478 {
9479         if (warning.unused_value) {
9480                 const expression_t *const left = expression->left;
9481                 if (!expression_has_effect(left)) {
9482                         warningf(&left->base.source_position,
9483                                  "left-hand operand of comma expression has no effect");
9484                 }
9485         }
9486         expression->base.type = expression->right->base.type;
9487 }
9488
9489 /**
9490  * @param prec_r precedence of the right operand
9491  */
9492 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9493 static expression_t *parse_##binexpression_type(expression_t *left)          \
9494 {                                                                            \
9495         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
9496         binexpr->binary.left  = left;                                            \
9497         eat(token_type);                                                         \
9498                                                                              \
9499         expression_t *right = parse_sub_expression(prec_r);                      \
9500                                                                              \
9501         binexpr->binary.right = right;                                           \
9502         sfunc(&binexpr->binary);                                                 \
9503                                                                              \
9504         return binexpr;                                                          \
9505 }
9506
9507 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
9508 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
9509 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
9510 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
9511 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
9512 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
9513 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
9514 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
9515 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
9516 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
9517 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
9518 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
9519 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
9520 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_arithmetic)
9521 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_arithmetic)
9522 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_arithmetic)
9523 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
9524 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
9525 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
9526 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9527 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9528 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9529 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9530 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9531 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9532 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9533 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9534 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9535 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9536 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
9537
9538
9539 static expression_t *parse_sub_expression(precedence_t precedence)
9540 {
9541         if (token.type < 0) {
9542                 return expected_expression_error();
9543         }
9544
9545         expression_parser_function_t *parser
9546                 = &expression_parsers[token.type];
9547         source_position_t             source_position = token.source_position;
9548         expression_t                 *left;
9549
9550         if (parser->parser != NULL) {
9551                 left = parser->parser();
9552         } else {
9553                 left = parse_primary_expression();
9554         }
9555         assert(left != NULL);
9556         left->base.source_position = source_position;
9557
9558         while (true) {
9559                 if (token.type < 0) {
9560                         return expected_expression_error();
9561                 }
9562
9563                 parser = &expression_parsers[token.type];
9564                 if (parser->infix_parser == NULL)
9565                         break;
9566                 if (parser->infix_precedence < precedence)
9567                         break;
9568
9569                 left = parser->infix_parser(left);
9570
9571                 assert(left != NULL);
9572                 assert(left->kind != EXPR_UNKNOWN);
9573                 left->base.source_position = source_position;
9574         }
9575
9576         return left;
9577 }
9578
9579 /**
9580  * Parse an expression.
9581  */
9582 static expression_t *parse_expression(void)
9583 {
9584         return parse_sub_expression(PREC_EXPRESSION);
9585 }
9586
9587 /**
9588  * Register a parser for a prefix-like operator.
9589  *
9590  * @param parser      the parser function
9591  * @param token_type  the token type of the prefix token
9592  */
9593 static void register_expression_parser(parse_expression_function parser,
9594                                        int token_type)
9595 {
9596         expression_parser_function_t *entry = &expression_parsers[token_type];
9597
9598         if (entry->parser != NULL) {
9599                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9600                 panic("trying to register multiple expression parsers for a token");
9601         }
9602         entry->parser = parser;
9603 }
9604
9605 /**
9606  * Register a parser for an infix operator with given precedence.
9607  *
9608  * @param parser      the parser function
9609  * @param token_type  the token type of the infix operator
9610  * @param precedence  the precedence of the operator
9611  */
9612 static void register_infix_parser(parse_expression_infix_function parser,
9613                 int token_type, precedence_t precedence)
9614 {
9615         expression_parser_function_t *entry = &expression_parsers[token_type];
9616
9617         if (entry->infix_parser != NULL) {
9618                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9619                 panic("trying to register multiple infix expression parsers for a "
9620                       "token");
9621         }
9622         entry->infix_parser     = parser;
9623         entry->infix_precedence = precedence;
9624 }
9625
9626 /**
9627  * Initialize the expression parsers.
9628  */
9629 static void init_expression_parsers(void)
9630 {
9631         memset(&expression_parsers, 0, sizeof(expression_parsers));
9632
9633         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
9634         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
9635         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
9636         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
9637         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
9638         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
9639         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
9640         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
9641         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
9642         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
9643         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
9644         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
9645         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
9646         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
9647         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
9648         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
9649         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
9650         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
9651         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9652         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
9653         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
9654         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
9655         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
9656         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
9657         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
9658         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
9659         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
9660         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
9661         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
9662         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
9663         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
9664         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
9665         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
9666         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
9667         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
9668         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
9669         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
9670
9671         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
9672         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
9673         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
9674         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
9675         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
9676         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
9677         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9678         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9679         register_expression_parser(parse_sizeof,                      T_sizeof);
9680         register_expression_parser(parse_alignof,                     T___alignof__);
9681         register_expression_parser(parse_extension,                   T___extension__);
9682         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
9683         register_expression_parser(parse_delete,                      T_delete);
9684         register_expression_parser(parse_throw,                       T_throw);
9685 }
9686
9687 /**
9688  * Parse a asm statement arguments specification.
9689  */
9690 static asm_argument_t *parse_asm_arguments(bool is_out)
9691 {
9692         asm_argument_t  *result = NULL;
9693         asm_argument_t **anchor = &result;
9694
9695         while (token.type == T_STRING_LITERAL || token.type == '[') {
9696                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9697                 memset(argument, 0, sizeof(argument[0]));
9698
9699                 if (token.type == '[') {
9700                         eat('[');
9701                         if (token.type != T_IDENTIFIER) {
9702                                 parse_error_expected("while parsing asm argument",
9703                                                      T_IDENTIFIER, NULL);
9704                                 return NULL;
9705                         }
9706                         argument->symbol = token.v.symbol;
9707
9708                         expect(']', end_error);
9709                 }
9710
9711                 argument->constraints = parse_string_literals();
9712                 expect('(', end_error);
9713                 add_anchor_token(')');
9714                 expression_t *expression = parse_expression();
9715                 rem_anchor_token(')');
9716                 if (is_out) {
9717                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
9718                          * change size or type representation (e.g. int -> long is ok, but
9719                          * int -> float is not) */
9720                         if (expression->kind == EXPR_UNARY_CAST) {
9721                                 type_t      *const type = expression->base.type;
9722                                 type_kind_t  const kind = type->kind;
9723                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9724                                         unsigned flags;
9725                                         unsigned size;
9726                                         if (kind == TYPE_ATOMIC) {
9727                                                 atomic_type_kind_t const akind = type->atomic.akind;
9728                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9729                                                 size  = get_atomic_type_size(akind);
9730                                         } else {
9731                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9732                                                 size  = get_atomic_type_size(get_intptr_kind());
9733                                         }
9734
9735                                         do {
9736                                                 expression_t *const value      = expression->unary.value;
9737                                                 type_t       *const value_type = value->base.type;
9738                                                 type_kind_t   const value_kind = value_type->kind;
9739
9740                                                 unsigned value_flags;
9741                                                 unsigned value_size;
9742                                                 if (value_kind == TYPE_ATOMIC) {
9743                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
9744                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9745                                                         value_size  = get_atomic_type_size(value_akind);
9746                                                 } else if (value_kind == TYPE_POINTER) {
9747                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9748                                                         value_size  = get_atomic_type_size(get_intptr_kind());
9749                                                 } else {
9750                                                         break;
9751                                                 }
9752
9753                                                 if (value_flags != flags || value_size != size)
9754                                                         break;
9755
9756                                                 expression = value;
9757                                         } while (expression->kind == EXPR_UNARY_CAST);
9758                                 }
9759                         }
9760
9761                         if (!is_lvalue(expression)) {
9762                                 errorf(&expression->base.source_position,
9763                                        "asm output argument is not an lvalue");
9764                         }
9765
9766                         if (argument->constraints.begin[0] == '+')
9767                                 mark_vars_read(expression, NULL);
9768                 } else {
9769                         mark_vars_read(expression, NULL);
9770                 }
9771                 argument->expression = expression;
9772                 expect(')', end_error);
9773
9774                 set_address_taken(expression, true);
9775
9776                 *anchor = argument;
9777                 anchor  = &argument->next;
9778
9779                 if (token.type != ',')
9780                         break;
9781                 eat(',');
9782         }
9783
9784         return result;
9785 end_error:
9786         return NULL;
9787 }
9788
9789 /**
9790  * Parse a asm statement clobber specification.
9791  */
9792 static asm_clobber_t *parse_asm_clobbers(void)
9793 {
9794         asm_clobber_t *result = NULL;
9795         asm_clobber_t *last   = NULL;
9796
9797         while (token.type == T_STRING_LITERAL) {
9798                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9799                 clobber->clobber       = parse_string_literals();
9800
9801                 if (last != NULL) {
9802                         last->next = clobber;
9803                 } else {
9804                         result = clobber;
9805                 }
9806                 last = clobber;
9807
9808                 if (token.type != ',')
9809                         break;
9810                 eat(',');
9811         }
9812
9813         return result;
9814 }
9815
9816 /**
9817  * Parse an asm statement.
9818  */
9819 static statement_t *parse_asm_statement(void)
9820 {
9821         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
9822         asm_statement_t *asm_statement = &statement->asms;
9823
9824         eat(T_asm);
9825
9826         if (token.type == T_volatile) {
9827                 next_token();
9828                 asm_statement->is_volatile = true;
9829         }
9830
9831         expect('(', end_error);
9832         add_anchor_token(')');
9833         add_anchor_token(':');
9834         asm_statement->asm_text = parse_string_literals();
9835
9836         if (token.type != ':') {
9837                 rem_anchor_token(':');
9838                 goto end_of_asm;
9839         }
9840         eat(':');
9841
9842         asm_statement->outputs = parse_asm_arguments(true);
9843         if (token.type != ':') {
9844                 rem_anchor_token(':');
9845                 goto end_of_asm;
9846         }
9847         eat(':');
9848
9849         asm_statement->inputs = parse_asm_arguments(false);
9850         if (token.type != ':') {
9851                 rem_anchor_token(':');
9852                 goto end_of_asm;
9853         }
9854         rem_anchor_token(':');
9855         eat(':');
9856
9857         asm_statement->clobbers = parse_asm_clobbers();
9858
9859 end_of_asm:
9860         rem_anchor_token(')');
9861         expect(')', end_error);
9862         expect(';', end_error);
9863
9864         if (asm_statement->outputs == NULL) {
9865                 /* GCC: An 'asm' instruction without any output operands will be treated
9866                  * identically to a volatile 'asm' instruction. */
9867                 asm_statement->is_volatile = true;
9868         }
9869
9870         return statement;
9871 end_error:
9872         return create_invalid_statement();
9873 }
9874
9875 /**
9876  * Parse a case statement.
9877  */
9878 static statement_t *parse_case_statement(void)
9879 {
9880         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9881         source_position_t *const pos       = &statement->base.source_position;
9882
9883         eat(T_case);
9884
9885         expression_t *const expression   = parse_expression();
9886         statement->case_label.expression = expression;
9887         if (!is_constant_expression(expression)) {
9888                 /* This check does not prevent the error message in all cases of an
9889                  * prior error while parsing the expression.  At least it catches the
9890                  * common case of a mistyped enum entry. */
9891                 if (is_type_valid(skip_typeref(expression->base.type))) {
9892                         errorf(pos, "case label does not reduce to an integer constant");
9893                 }
9894                 statement->case_label.is_bad = true;
9895         } else {
9896                 long const val = fold_constant(expression);
9897                 statement->case_label.first_case = val;
9898                 statement->case_label.last_case  = val;
9899         }
9900
9901         if (GNU_MODE) {
9902                 if (token.type == T_DOTDOTDOT) {
9903                         next_token();
9904                         expression_t *const end_range   = parse_expression();
9905                         statement->case_label.end_range = end_range;
9906                         if (!is_constant_expression(end_range)) {
9907                                 /* This check does not prevent the error message in all cases of an
9908                                  * prior error while parsing the expression.  At least it catches the
9909                                  * common case of a mistyped enum entry. */
9910                                 if (is_type_valid(skip_typeref(end_range->base.type))) {
9911                                         errorf(pos, "case range does not reduce to an integer constant");
9912                                 }
9913                                 statement->case_label.is_bad = true;
9914                         } else {
9915                                 long const val = fold_constant(end_range);
9916                                 statement->case_label.last_case = val;
9917
9918                                 if (warning.other && val < statement->case_label.first_case) {
9919                                         statement->case_label.is_empty_range = true;
9920                                         warningf(pos, "empty range specified");
9921                                 }
9922                         }
9923                 }
9924         }
9925
9926         PUSH_PARENT(statement);
9927
9928         expect(':', end_error);
9929 end_error:
9930
9931         if (current_switch != NULL) {
9932                 if (! statement->case_label.is_bad) {
9933                         /* Check for duplicate case values */
9934                         case_label_statement_t *c = &statement->case_label;
9935                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9936                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9937                                         continue;
9938
9939                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9940                                         continue;
9941
9942                                 errorf(pos, "duplicate case value (previously used %P)",
9943                                        &l->base.source_position);
9944                                 break;
9945                         }
9946                 }
9947                 /* link all cases into the switch statement */
9948                 if (current_switch->last_case == NULL) {
9949                         current_switch->first_case      = &statement->case_label;
9950                 } else {
9951                         current_switch->last_case->next = &statement->case_label;
9952                 }
9953                 current_switch->last_case = &statement->case_label;
9954         } else {
9955                 errorf(pos, "case label not within a switch statement");
9956         }
9957
9958         statement_t *const inner_stmt = parse_statement();
9959         statement->case_label.statement = inner_stmt;
9960         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9961                 errorf(&inner_stmt->base.source_position, "declaration after case label");
9962         }
9963
9964         POP_PARENT;
9965         return statement;
9966 }
9967
9968 /**
9969  * Parse a default statement.
9970  */
9971 static statement_t *parse_default_statement(void)
9972 {
9973         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9974
9975         eat(T_default);
9976
9977         PUSH_PARENT(statement);
9978
9979         expect(':', end_error);
9980         if (current_switch != NULL) {
9981                 const case_label_statement_t *def_label = current_switch->default_label;
9982                 if (def_label != NULL) {
9983                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9984                                &def_label->base.source_position);
9985                 } else {
9986                         current_switch->default_label = &statement->case_label;
9987
9988                         /* link all cases into the switch statement */
9989                         if (current_switch->last_case == NULL) {
9990                                 current_switch->first_case      = &statement->case_label;
9991                         } else {
9992                                 current_switch->last_case->next = &statement->case_label;
9993                         }
9994                         current_switch->last_case = &statement->case_label;
9995                 }
9996         } else {
9997                 errorf(&statement->base.source_position,
9998                         "'default' label not within a switch statement");
9999         }
10000
10001         statement_t *const inner_stmt = parse_statement();
10002         statement->case_label.statement = inner_stmt;
10003         if (inner_stmt->kind == STATEMENT_DECLARATION) {
10004                 errorf(&inner_stmt->base.source_position, "declaration after default label");
10005         }
10006
10007         POP_PARENT;
10008         return statement;
10009 end_error:
10010         POP_PARENT;
10011         return create_invalid_statement();
10012 }
10013
10014 /**
10015  * Parse a label statement.
10016  */
10017 static statement_t *parse_label_statement(void)
10018 {
10019         assert(token.type == T_IDENTIFIER);
10020         symbol_t *symbol = token.v.symbol;
10021         label_t  *label  = get_label(symbol);
10022
10023         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
10024         statement->label.label       = label;
10025
10026         next_token();
10027
10028         PUSH_PARENT(statement);
10029
10030         /* if statement is already set then the label is defined twice,
10031          * otherwise it was just mentioned in a goto/local label declaration so far
10032          */
10033         if (label->statement != NULL) {
10034                 errorf(HERE, "duplicate label '%Y' (declared %P)",
10035                        symbol, &label->base.source_position);
10036         } else {
10037                 label->base.source_position = token.source_position;
10038                 label->statement            = statement;
10039         }
10040
10041         eat(':');
10042
10043         if (token.type == '}') {
10044                 /* TODO only warn? */
10045                 if (warning.other && false) {
10046                         warningf(HERE, "label at end of compound statement");
10047                         statement->label.statement = create_empty_statement();
10048                 } else {
10049                         errorf(HERE, "label at end of compound statement");
10050                         statement->label.statement = create_invalid_statement();
10051                 }
10052         } else if (token.type == ';') {
10053                 /* Eat an empty statement here, to avoid the warning about an empty
10054                  * statement after a label.  label:; is commonly used to have a label
10055                  * before a closing brace. */
10056                 statement->label.statement = create_empty_statement();
10057                 next_token();
10058         } else {
10059                 statement_t *const inner_stmt = parse_statement();
10060                 statement->label.statement = inner_stmt;
10061                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10062                         errorf(&inner_stmt->base.source_position, "declaration after label");
10063                 }
10064         }
10065
10066         /* remember the labels in a list for later checking */
10067         *label_anchor = &statement->label;
10068         label_anchor  = &statement->label.next;
10069
10070         POP_PARENT;
10071         return statement;
10072 }
10073
10074 /**
10075  * Parse an if statement.
10076  */
10077 static statement_t *parse_if(void)
10078 {
10079         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10080
10081         eat(T_if);
10082
10083         PUSH_PARENT(statement);
10084
10085         add_anchor_token('{');
10086
10087         expect('(', end_error);
10088         add_anchor_token(')');
10089         expression_t *const expr = parse_expression();
10090         statement->ifs.condition = expr;
10091         /* §6.8.4.1:1  The controlling expression of an if statement shall have
10092          *             scalar type. */
10093         semantic_condition(expr, "condition of 'if'-statment");
10094         mark_vars_read(expr, NULL);
10095         rem_anchor_token(')');
10096         expect(')', end_error);
10097
10098 end_error:
10099         rem_anchor_token('{');
10100
10101         add_anchor_token(T_else);
10102         statement_t *const true_stmt = parse_statement();
10103         statement->ifs.true_statement = true_stmt;
10104         rem_anchor_token(T_else);
10105
10106         if (token.type == T_else) {
10107                 next_token();
10108                 statement->ifs.false_statement = parse_statement();
10109         } else if (warning.parentheses &&
10110                         true_stmt->kind == STATEMENT_IF &&
10111                         true_stmt->ifs.false_statement != NULL) {
10112                 warningf(&true_stmt->base.source_position,
10113                                 "suggest explicit braces to avoid ambiguous 'else'");
10114         }
10115
10116         POP_PARENT;
10117         return statement;
10118 }
10119
10120 /**
10121  * Check that all enums are handled in a switch.
10122  *
10123  * @param statement  the switch statement to check
10124  */
10125 static void check_enum_cases(const switch_statement_t *statement)
10126 {
10127         const type_t *type = skip_typeref(statement->expression->base.type);
10128         if (! is_type_enum(type))
10129                 return;
10130         const enum_type_t *enumt = &type->enumt;
10131
10132         /* if we have a default, no warnings */
10133         if (statement->default_label != NULL)
10134                 return;
10135
10136         /* FIXME: calculation of value should be done while parsing */
10137         /* TODO: quadratic algorithm here. Change to an n log n one */
10138         long            last_value = -1;
10139         const entity_t *entry      = enumt->enume->base.next;
10140         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10141              entry = entry->base.next) {
10142                 const expression_t *expression = entry->enum_value.value;
10143                 long                value      = expression != NULL ? fold_constant(expression) : last_value + 1;
10144                 bool                found      = false;
10145                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10146                         if (l->expression == NULL)
10147                                 continue;
10148                         if (l->first_case <= value && value <= l->last_case) {
10149                                 found = true;
10150                                 break;
10151                         }
10152                 }
10153                 if (! found) {
10154                         warningf(&statement->base.source_position,
10155                                  "enumeration value '%Y' not handled in switch",
10156                                  entry->base.symbol);
10157                 }
10158                 last_value = value;
10159         }
10160 }
10161
10162 /**
10163  * Parse a switch statement.
10164  */
10165 static statement_t *parse_switch(void)
10166 {
10167         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10168
10169         eat(T_switch);
10170
10171         PUSH_PARENT(statement);
10172
10173         expect('(', end_error);
10174         add_anchor_token(')');
10175         expression_t *const expr = parse_expression();
10176         mark_vars_read(expr, NULL);
10177         type_t       *      type = skip_typeref(expr->base.type);
10178         if (is_type_integer(type)) {
10179                 type = promote_integer(type);
10180                 if (warning.traditional) {
10181                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10182                                 warningf(&expr->base.source_position,
10183                                         "'%T' switch expression not converted to '%T' in ISO C",
10184                                         type, type_int);
10185                         }
10186                 }
10187         } else if (is_type_valid(type)) {
10188                 errorf(&expr->base.source_position,
10189                        "switch quantity is not an integer, but '%T'", type);
10190                 type = type_error_type;
10191         }
10192         statement->switchs.expression = create_implicit_cast(expr, type);
10193         expect(')', end_error);
10194         rem_anchor_token(')');
10195
10196         switch_statement_t *rem = current_switch;
10197         current_switch          = &statement->switchs;
10198         statement->switchs.body = parse_statement();
10199         current_switch          = rem;
10200
10201         if (warning.switch_default &&
10202             statement->switchs.default_label == NULL) {
10203                 warningf(&statement->base.source_position, "switch has no default case");
10204         }
10205         if (warning.switch_enum)
10206                 check_enum_cases(&statement->switchs);
10207
10208         POP_PARENT;
10209         return statement;
10210 end_error:
10211         POP_PARENT;
10212         return create_invalid_statement();
10213 }
10214
10215 static statement_t *parse_loop_body(statement_t *const loop)
10216 {
10217         statement_t *const rem = current_loop;
10218         current_loop = loop;
10219
10220         statement_t *const body = parse_statement();
10221
10222         current_loop = rem;
10223         return body;
10224 }
10225
10226 /**
10227  * Parse a while statement.
10228  */
10229 static statement_t *parse_while(void)
10230 {
10231         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10232
10233         eat(T_while);
10234
10235         PUSH_PARENT(statement);
10236
10237         expect('(', end_error);
10238         add_anchor_token(')');
10239         expression_t *const cond = parse_expression();
10240         statement->whiles.condition = cond;
10241         /* §6.8.5:2    The controlling expression of an iteration statement shall
10242          *             have scalar type. */
10243         semantic_condition(cond, "condition of 'while'-statement");
10244         mark_vars_read(cond, NULL);
10245         rem_anchor_token(')');
10246         expect(')', end_error);
10247
10248         statement->whiles.body = parse_loop_body(statement);
10249
10250         POP_PARENT;
10251         return statement;
10252 end_error:
10253         POP_PARENT;
10254         return create_invalid_statement();
10255 }
10256
10257 /**
10258  * Parse a do statement.
10259  */
10260 static statement_t *parse_do(void)
10261 {
10262         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10263
10264         eat(T_do);
10265
10266         PUSH_PARENT(statement);
10267
10268         add_anchor_token(T_while);
10269         statement->do_while.body = parse_loop_body(statement);
10270         rem_anchor_token(T_while);
10271
10272         expect(T_while, end_error);
10273         expect('(', end_error);
10274         add_anchor_token(')');
10275         expression_t *const cond = parse_expression();
10276         statement->do_while.condition = cond;
10277         /* §6.8.5:2    The controlling expression of an iteration statement shall
10278          *             have scalar type. */
10279         semantic_condition(cond, "condition of 'do-while'-statement");
10280         mark_vars_read(cond, NULL);
10281         rem_anchor_token(')');
10282         expect(')', end_error);
10283         expect(';', end_error);
10284
10285         POP_PARENT;
10286         return statement;
10287 end_error:
10288         POP_PARENT;
10289         return create_invalid_statement();
10290 }
10291
10292 /**
10293  * Parse a for statement.
10294  */
10295 static statement_t *parse_for(void)
10296 {
10297         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10298
10299         eat(T_for);
10300
10301         expect('(', end_error1);
10302         add_anchor_token(')');
10303
10304         PUSH_PARENT(statement);
10305
10306         size_t const  top       = environment_top();
10307         scope_t      *old_scope = scope_push(&statement->fors.scope);
10308
10309         if (token.type == ';') {
10310                 next_token();
10311         } else if (is_declaration_specifier(&token, false)) {
10312                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10313         } else {
10314                 add_anchor_token(';');
10315                 expression_t *const init = parse_expression();
10316                 statement->fors.initialisation = init;
10317                 mark_vars_read(init, ENT_ANY);
10318                 if (warning.unused_value && !expression_has_effect(init)) {
10319                         warningf(&init->base.source_position,
10320                                         "initialisation of 'for'-statement has no effect");
10321                 }
10322                 rem_anchor_token(';');
10323                 expect(';', end_error2);
10324         }
10325
10326         if (token.type != ';') {
10327                 add_anchor_token(';');
10328                 expression_t *const cond = parse_expression();
10329                 statement->fors.condition = cond;
10330                 /* §6.8.5:2    The controlling expression of an iteration statement
10331                  *             shall have scalar type. */
10332                 semantic_condition(cond, "condition of 'for'-statement");
10333                 mark_vars_read(cond, NULL);
10334                 rem_anchor_token(';');
10335         }
10336         expect(';', end_error2);
10337         if (token.type != ')') {
10338                 expression_t *const step = parse_expression();
10339                 statement->fors.step = step;
10340                 mark_vars_read(step, ENT_ANY);
10341                 if (warning.unused_value && !expression_has_effect(step)) {
10342                         warningf(&step->base.source_position,
10343                                  "step of 'for'-statement has no effect");
10344                 }
10345         }
10346         expect(')', end_error2);
10347         rem_anchor_token(')');
10348         statement->fors.body = parse_loop_body(statement);
10349
10350         assert(current_scope == &statement->fors.scope);
10351         scope_pop(old_scope);
10352         environment_pop_to(top);
10353
10354         POP_PARENT;
10355         return statement;
10356
10357 end_error2:
10358         POP_PARENT;
10359         rem_anchor_token(')');
10360         assert(current_scope == &statement->fors.scope);
10361         scope_pop(old_scope);
10362         environment_pop_to(top);
10363         /* fallthrough */
10364
10365 end_error1:
10366         return create_invalid_statement();
10367 }
10368
10369 /**
10370  * Parse a goto statement.
10371  */
10372 static statement_t *parse_goto(void)
10373 {
10374         statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10375         eat(T_goto);
10376
10377         if (GNU_MODE && token.type == '*') {
10378                 next_token();
10379                 expression_t *expression = parse_expression();
10380                 mark_vars_read(expression, NULL);
10381
10382                 /* Argh: although documentation says the expression must be of type void*,
10383                  * gcc accepts anything that can be casted into void* without error */
10384                 type_t *type = expression->base.type;
10385
10386                 if (type != type_error_type) {
10387                         if (!is_type_pointer(type) && !is_type_integer(type)) {
10388                                 errorf(&expression->base.source_position,
10389                                         "cannot convert to a pointer type");
10390                         } else if (warning.other && type != type_void_ptr) {
10391                                 warningf(&expression->base.source_position,
10392                                         "type of computed goto expression should be 'void*' not '%T'", type);
10393                         }
10394                         expression = create_implicit_cast(expression, type_void_ptr);
10395                 }
10396
10397                 statement->gotos.expression = expression;
10398         } else {
10399                 if (token.type != T_IDENTIFIER) {
10400                         if (GNU_MODE)
10401                                 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10402                         else
10403                                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10404                         eat_until_anchor();
10405                         goto end_error;
10406                 }
10407                 symbol_t *symbol = token.v.symbol;
10408                 next_token();
10409
10410                 statement->gotos.label = get_label(symbol);
10411         }
10412
10413         /* remember the goto's in a list for later checking */
10414         *goto_anchor = &statement->gotos;
10415         goto_anchor  = &statement->gotos.next;
10416
10417         expect(';', end_error);
10418
10419         return statement;
10420 end_error:
10421         return create_invalid_statement();
10422 }
10423
10424 /**
10425  * Parse a continue statement.
10426  */
10427 static statement_t *parse_continue(void)
10428 {
10429         if (current_loop == NULL) {
10430                 errorf(HERE, "continue statement not within loop");
10431         }
10432
10433         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10434
10435         eat(T_continue);
10436         expect(';', end_error);
10437
10438 end_error:
10439         return statement;
10440 }
10441
10442 /**
10443  * Parse a break statement.
10444  */
10445 static statement_t *parse_break(void)
10446 {
10447         if (current_switch == NULL && current_loop == NULL) {
10448                 errorf(HERE, "break statement not within loop or switch");
10449         }
10450
10451         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10452
10453         eat(T_break);
10454         expect(';', end_error);
10455
10456 end_error:
10457         return statement;
10458 }
10459
10460 /**
10461  * Parse a __leave statement.
10462  */
10463 static statement_t *parse_leave_statement(void)
10464 {
10465         if (current_try == NULL) {
10466                 errorf(HERE, "__leave statement not within __try");
10467         }
10468
10469         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10470
10471         eat(T___leave);
10472         expect(';', end_error);
10473
10474 end_error:
10475         return statement;
10476 }
10477
10478 /**
10479  * Check if a given entity represents a local variable.
10480  */
10481 static bool is_local_variable(const entity_t *entity)
10482 {
10483         if (entity->kind != ENTITY_VARIABLE)
10484                 return false;
10485
10486         switch ((storage_class_tag_t) entity->declaration.storage_class) {
10487         case STORAGE_CLASS_AUTO:
10488         case STORAGE_CLASS_REGISTER: {
10489                 const type_t *type = skip_typeref(entity->declaration.type);
10490                 if (is_type_function(type)) {
10491                         return false;
10492                 } else {
10493                         return true;
10494                 }
10495         }
10496         default:
10497                 return false;
10498         }
10499 }
10500
10501 /**
10502  * Check if a given expression represents a local variable.
10503  */
10504 static bool expression_is_local_variable(const expression_t *expression)
10505 {
10506         if (expression->base.kind != EXPR_REFERENCE) {
10507                 return false;
10508         }
10509         const entity_t *entity = expression->reference.entity;
10510         return is_local_variable(entity);
10511 }
10512
10513 /**
10514  * Check if a given expression represents a local variable and
10515  * return its declaration then, else return NULL.
10516  */
10517 entity_t *expression_is_variable(const expression_t *expression)
10518 {
10519         if (expression->base.kind != EXPR_REFERENCE) {
10520                 return NULL;
10521         }
10522         entity_t *entity = expression->reference.entity;
10523         if (entity->kind != ENTITY_VARIABLE)
10524                 return NULL;
10525
10526         return entity;
10527 }
10528
10529 /**
10530  * Parse a return statement.
10531  */
10532 static statement_t *parse_return(void)
10533 {
10534         eat(T_return);
10535
10536         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10537
10538         expression_t *return_value = NULL;
10539         if (token.type != ';') {
10540                 return_value = parse_expression();
10541                 mark_vars_read(return_value, NULL);
10542         }
10543
10544         const type_t *const func_type = skip_typeref(current_function->base.type);
10545         assert(is_type_function(func_type));
10546         type_t *const return_type = skip_typeref(func_type->function.return_type);
10547
10548         source_position_t const *const pos = &statement->base.source_position;
10549         if (return_value != NULL) {
10550                 type_t *return_value_type = skip_typeref(return_value->base.type);
10551
10552                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10553                         if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10554                                 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10555                                 /* Only warn in C mode, because GCC does the same */
10556                                 if (c_mode & _CXX || strict_mode) {
10557                                         errorf(pos,
10558                                                         "'return' with a value, in function returning 'void'");
10559                                 } else if (warning.other) {
10560                                         warningf(pos,
10561                                                         "'return' with a value, in function returning 'void'");
10562                                 }
10563                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10564                                 /* Only warn in C mode, because GCC does the same */
10565                                 if (strict_mode) {
10566                                         errorf(pos,
10567                                                         "'return' with expression in function return 'void'");
10568                                 } else if (warning.other) {
10569                                         warningf(pos,
10570                                                         "'return' with expression in function return 'void'");
10571                                 }
10572                         }
10573                 } else {
10574                         assign_error_t error = semantic_assign(return_type, return_value);
10575                         report_assign_error(error, return_type, return_value, "'return'",
10576                                         pos);
10577                 }
10578                 return_value = create_implicit_cast(return_value, return_type);
10579                 /* check for returning address of a local var */
10580                 if (warning.other && return_value != NULL
10581                                 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10582                         const expression_t *expression = return_value->unary.value;
10583                         if (expression_is_local_variable(expression)) {
10584                                 warningf(pos, "function returns address of local variable");
10585                         }
10586                 }
10587         } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10588                 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10589                 if (c_mode & _CXX || strict_mode) {
10590                         errorf(pos,
10591                                         "'return' without value, in function returning non-void");
10592                 } else {
10593                         warningf(pos,
10594                                         "'return' without value, in function returning non-void");
10595                 }
10596         }
10597         statement->returns.value = return_value;
10598
10599         expect(';', end_error);
10600
10601 end_error:
10602         return statement;
10603 }
10604
10605 /**
10606  * Parse a declaration statement.
10607  */
10608 static statement_t *parse_declaration_statement(void)
10609 {
10610         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10611
10612         entity_t *before = current_scope->last_entity;
10613         if (GNU_MODE) {
10614                 parse_external_declaration();
10615         } else {
10616                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10617         }
10618
10619         declaration_statement_t *const decl  = &statement->declaration;
10620         entity_t                *const begin =
10621                 before != NULL ? before->base.next : current_scope->entities;
10622         decl->declarations_begin = begin;
10623         decl->declarations_end   = begin != NULL ? current_scope->last_entity : NULL;
10624
10625         return statement;
10626 }
10627
10628 /**
10629  * Parse an expression statement, ie. expr ';'.
10630  */
10631 static statement_t *parse_expression_statement(void)
10632 {
10633         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10634
10635         expression_t *const expr         = parse_expression();
10636         statement->expression.expression = expr;
10637         mark_vars_read(expr, ENT_ANY);
10638
10639         expect(';', end_error);
10640
10641 end_error:
10642         return statement;
10643 }
10644
10645 /**
10646  * Parse a microsoft __try { } __finally { } or
10647  * __try{ } __except() { }
10648  */
10649 static statement_t *parse_ms_try_statment(void)
10650 {
10651         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10652         eat(T___try);
10653
10654         PUSH_PARENT(statement);
10655
10656         ms_try_statement_t *rem = current_try;
10657         current_try = &statement->ms_try;
10658         statement->ms_try.try_statement = parse_compound_statement(false);
10659         current_try = rem;
10660
10661         POP_PARENT;
10662
10663         if (token.type == T___except) {
10664                 eat(T___except);
10665                 expect('(', end_error);
10666                 add_anchor_token(')');
10667                 expression_t *const expr = parse_expression();
10668                 mark_vars_read(expr, NULL);
10669                 type_t       *      type = skip_typeref(expr->base.type);
10670                 if (is_type_integer(type)) {
10671                         type = promote_integer(type);
10672                 } else if (is_type_valid(type)) {
10673                         errorf(&expr->base.source_position,
10674                                "__expect expression is not an integer, but '%T'", type);
10675                         type = type_error_type;
10676                 }
10677                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10678                 rem_anchor_token(')');
10679                 expect(')', end_error);
10680                 statement->ms_try.final_statement = parse_compound_statement(false);
10681         } else if (token.type == T__finally) {
10682                 eat(T___finally);
10683                 statement->ms_try.final_statement = parse_compound_statement(false);
10684         } else {
10685                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10686                 return create_invalid_statement();
10687         }
10688         return statement;
10689 end_error:
10690         return create_invalid_statement();
10691 }
10692
10693 static statement_t *parse_empty_statement(void)
10694 {
10695         if (warning.empty_statement) {
10696                 warningf(HERE, "statement is empty");
10697         }
10698         statement_t *const statement = create_empty_statement();
10699         eat(';');
10700         return statement;
10701 }
10702
10703 static statement_t *parse_local_label_declaration(void)
10704 {
10705         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10706
10707         eat(T___label__);
10708
10709         entity_t *begin = NULL, *end = NULL;
10710
10711         while (true) {
10712                 if (token.type != T_IDENTIFIER) {
10713                         parse_error_expected("while parsing local label declaration",
10714                                 T_IDENTIFIER, NULL);
10715                         goto end_error;
10716                 }
10717                 symbol_t *symbol = token.v.symbol;
10718                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10719                 if (entity != NULL && entity->base.parent_scope == current_scope) {
10720                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10721                                symbol, &entity->base.source_position);
10722                 } else {
10723                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10724
10725                         entity->base.parent_scope    = current_scope;
10726                         entity->base.namespc         = NAMESPACE_LABEL;
10727                         entity->base.source_position = token.source_position;
10728                         entity->base.symbol          = symbol;
10729
10730                         if (end != NULL)
10731                                 end->base.next = entity;
10732                         end = entity;
10733                         if (begin == NULL)
10734                                 begin = entity;
10735
10736                         environment_push(entity);
10737                 }
10738                 next_token();
10739
10740                 if (token.type != ',')
10741                         break;
10742                 next_token();
10743         }
10744         eat(';');
10745 end_error:
10746         statement->declaration.declarations_begin = begin;
10747         statement->declaration.declarations_end   = end;
10748         return statement;
10749 }
10750
10751 static void parse_namespace_definition(void)
10752 {
10753         eat(T_namespace);
10754
10755         entity_t *entity = NULL;
10756         symbol_t *symbol = NULL;
10757
10758         if (token.type == T_IDENTIFIER) {
10759                 symbol = token.v.symbol;
10760                 next_token();
10761
10762                 entity = get_entity(symbol, NAMESPACE_NORMAL);
10763                 if (entity       != NULL             &&
10764                                 entity->kind != ENTITY_NAMESPACE &&
10765                                 entity->base.parent_scope == current_scope) {
10766                         if (!is_error_entity(entity)) {
10767                                 error_redefined_as_different_kind(&token.source_position,
10768                                                 entity, ENTITY_NAMESPACE);
10769                         }
10770                         entity = NULL;
10771                 }
10772         }
10773
10774         if (entity == NULL) {
10775                 entity                       = allocate_entity_zero(ENTITY_NAMESPACE);
10776                 entity->base.symbol          = symbol;
10777                 entity->base.source_position = token.source_position;
10778                 entity->base.namespc         = NAMESPACE_NORMAL;
10779                 entity->base.parent_scope    = current_scope;
10780         }
10781
10782         if (token.type == '=') {
10783                 /* TODO: parse namespace alias */
10784                 panic("namespace alias definition not supported yet");
10785         }
10786
10787         environment_push(entity);
10788         append_entity(current_scope, entity);
10789
10790         size_t const  top       = environment_top();
10791         scope_t      *old_scope = scope_push(&entity->namespacee.members);
10792
10793         expect('{', end_error);
10794         parse_externals();
10795         expect('}', end_error);
10796
10797 end_error:
10798         assert(current_scope == &entity->namespacee.members);
10799         scope_pop(old_scope);
10800         environment_pop_to(top);
10801 }
10802
10803 /**
10804  * Parse a statement.
10805  * There's also parse_statement() which additionally checks for
10806  * "statement has no effect" warnings
10807  */
10808 static statement_t *intern_parse_statement(void)
10809 {
10810         statement_t *statement = NULL;
10811
10812         /* declaration or statement */
10813         add_anchor_token(';');
10814         switch (token.type) {
10815         case T_IDENTIFIER: {
10816                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10817                 if (la1_type == ':') {
10818                         statement = parse_label_statement();
10819                 } else if (is_typedef_symbol(token.v.symbol)) {
10820                         statement = parse_declaration_statement();
10821                 } else {
10822                         /* it's an identifier, the grammar says this must be an
10823                          * expression statement. However it is common that users mistype
10824                          * declaration types, so we guess a bit here to improve robustness
10825                          * for incorrect programs */
10826                         switch (la1_type) {
10827                         case '&':
10828                         case '*':
10829                                 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10830                                         goto expression_statment;
10831                                 /* FALLTHROUGH */
10832
10833                         DECLARATION_START
10834                         case T_IDENTIFIER:
10835                                 statement = parse_declaration_statement();
10836                                 break;
10837
10838                         default:
10839 expression_statment:
10840                                 statement = parse_expression_statement();
10841                                 break;
10842                         }
10843                 }
10844                 break;
10845         }
10846
10847         case T___extension__:
10848                 /* This can be a prefix to a declaration or an expression statement.
10849                  * We simply eat it now and parse the rest with tail recursion. */
10850                 do {
10851                         next_token();
10852                 } while (token.type == T___extension__);
10853                 bool old_gcc_extension = in_gcc_extension;
10854                 in_gcc_extension       = true;
10855                 statement = intern_parse_statement();
10856                 in_gcc_extension = old_gcc_extension;
10857                 break;
10858
10859         DECLARATION_START
10860                 statement = parse_declaration_statement();
10861                 break;
10862
10863         case T___label__:
10864                 statement = parse_local_label_declaration();
10865                 break;
10866
10867         case ';':         statement = parse_empty_statement();         break;
10868         case '{':         statement = parse_compound_statement(false); break;
10869         case T___leave:   statement = parse_leave_statement();         break;
10870         case T___try:     statement = parse_ms_try_statment();         break;
10871         case T_asm:       statement = parse_asm_statement();           break;
10872         case T_break:     statement = parse_break();                   break;
10873         case T_case:      statement = parse_case_statement();          break;
10874         case T_continue:  statement = parse_continue();                break;
10875         case T_default:   statement = parse_default_statement();       break;
10876         case T_do:        statement = parse_do();                      break;
10877         case T_for:       statement = parse_for();                     break;
10878         case T_goto:      statement = parse_goto();                    break;
10879         case T_if:        statement = parse_if();                      break;
10880         case T_return:    statement = parse_return();                  break;
10881         case T_switch:    statement = parse_switch();                  break;
10882         case T_while:     statement = parse_while();                   break;
10883
10884         EXPRESSION_START
10885                 statement = parse_expression_statement();
10886                 break;
10887
10888         default:
10889                 errorf(HERE, "unexpected token %K while parsing statement", &token);
10890                 statement = create_invalid_statement();
10891                 if (!at_anchor())
10892                         next_token();
10893                 break;
10894         }
10895         rem_anchor_token(';');
10896
10897         assert(statement != NULL
10898                         && statement->base.source_position.input_name != NULL);
10899
10900         return statement;
10901 }
10902
10903 /**
10904  * parse a statement and emits "statement has no effect" warning if needed
10905  * (This is really a wrapper around intern_parse_statement with check for 1
10906  *  single warning. It is needed, because for statement expressions we have
10907  *  to avoid the warning on the last statement)
10908  */
10909 static statement_t *parse_statement(void)
10910 {
10911         statement_t *statement = intern_parse_statement();
10912
10913         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10914                 expression_t *expression = statement->expression.expression;
10915                 if (!expression_has_effect(expression)) {
10916                         warningf(&expression->base.source_position,
10917                                         "statement has no effect");
10918                 }
10919         }
10920
10921         return statement;
10922 }
10923
10924 /**
10925  * Parse a compound statement.
10926  */
10927 static statement_t *parse_compound_statement(bool inside_expression_statement)
10928 {
10929         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10930
10931         PUSH_PARENT(statement);
10932
10933         eat('{');
10934         add_anchor_token('}');
10935         /* tokens, which can start a statement */
10936         /* TODO MS, __builtin_FOO */
10937         add_anchor_token('!');
10938         add_anchor_token('&');
10939         add_anchor_token('(');
10940         add_anchor_token('*');
10941         add_anchor_token('+');
10942         add_anchor_token('-');
10943         add_anchor_token('{');
10944         add_anchor_token('~');
10945         add_anchor_token(T_CHARACTER_CONSTANT);
10946         add_anchor_token(T_COLONCOLON);
10947         add_anchor_token(T_FLOATINGPOINT);
10948         add_anchor_token(T_IDENTIFIER);
10949         add_anchor_token(T_INTEGER);
10950         add_anchor_token(T_MINUSMINUS);
10951         add_anchor_token(T_PLUSPLUS);
10952         add_anchor_token(T_STRING_LITERAL);
10953         add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10954         add_anchor_token(T_WIDE_STRING_LITERAL);
10955         add_anchor_token(T__Bool);
10956         add_anchor_token(T__Complex);
10957         add_anchor_token(T__Imaginary);
10958         add_anchor_token(T___FUNCTION__);
10959         add_anchor_token(T___PRETTY_FUNCTION__);
10960         add_anchor_token(T___alignof__);
10961         add_anchor_token(T___attribute__);
10962         add_anchor_token(T___builtin_va_start);
10963         add_anchor_token(T___extension__);
10964         add_anchor_token(T___func__);
10965         add_anchor_token(T___imag__);
10966         add_anchor_token(T___label__);
10967         add_anchor_token(T___real__);
10968         add_anchor_token(T___thread);
10969         add_anchor_token(T_asm);
10970         add_anchor_token(T_auto);
10971         add_anchor_token(T_bool);
10972         add_anchor_token(T_break);
10973         add_anchor_token(T_case);
10974         add_anchor_token(T_char);
10975         add_anchor_token(T_class);
10976         add_anchor_token(T_const);
10977         add_anchor_token(T_const_cast);
10978         add_anchor_token(T_continue);
10979         add_anchor_token(T_default);
10980         add_anchor_token(T_delete);
10981         add_anchor_token(T_double);
10982         add_anchor_token(T_do);
10983         add_anchor_token(T_dynamic_cast);
10984         add_anchor_token(T_enum);
10985         add_anchor_token(T_extern);
10986         add_anchor_token(T_false);
10987         add_anchor_token(T_float);
10988         add_anchor_token(T_for);
10989         add_anchor_token(T_goto);
10990         add_anchor_token(T_if);
10991         add_anchor_token(T_inline);
10992         add_anchor_token(T_int);
10993         add_anchor_token(T_long);
10994         add_anchor_token(T_new);
10995         add_anchor_token(T_operator);
10996         add_anchor_token(T_register);
10997         add_anchor_token(T_reinterpret_cast);
10998         add_anchor_token(T_restrict);
10999         add_anchor_token(T_return);
11000         add_anchor_token(T_short);
11001         add_anchor_token(T_signed);
11002         add_anchor_token(T_sizeof);
11003         add_anchor_token(T_static);
11004         add_anchor_token(T_static_cast);
11005         add_anchor_token(T_struct);
11006         add_anchor_token(T_switch);
11007         add_anchor_token(T_template);
11008         add_anchor_token(T_this);
11009         add_anchor_token(T_throw);
11010         add_anchor_token(T_true);
11011         add_anchor_token(T_try);
11012         add_anchor_token(T_typedef);
11013         add_anchor_token(T_typeid);
11014         add_anchor_token(T_typename);
11015         add_anchor_token(T_typeof);
11016         add_anchor_token(T_union);
11017         add_anchor_token(T_unsigned);
11018         add_anchor_token(T_using);
11019         add_anchor_token(T_void);
11020         add_anchor_token(T_volatile);
11021         add_anchor_token(T_wchar_t);
11022         add_anchor_token(T_while);
11023
11024         size_t const  top       = environment_top();
11025         scope_t      *old_scope = scope_push(&statement->compound.scope);
11026
11027         statement_t **anchor            = &statement->compound.statements;
11028         bool          only_decls_so_far = true;
11029         while (token.type != '}') {
11030                 if (token.type == T_EOF) {
11031                         errorf(&statement->base.source_position,
11032                                "EOF while parsing compound statement");
11033                         break;
11034                 }
11035                 statement_t *sub_statement = intern_parse_statement();
11036                 if (is_invalid_statement(sub_statement)) {
11037                         /* an error occurred. if we are at an anchor, return */
11038                         if (at_anchor())
11039                                 goto end_error;
11040                         continue;
11041                 }
11042
11043                 if (warning.declaration_after_statement) {
11044                         if (sub_statement->kind != STATEMENT_DECLARATION) {
11045                                 only_decls_so_far = false;
11046                         } else if (!only_decls_so_far) {
11047                                 warningf(&sub_statement->base.source_position,
11048                                          "ISO C90 forbids mixed declarations and code");
11049                         }
11050                 }
11051
11052                 *anchor = sub_statement;
11053
11054                 while (sub_statement->base.next != NULL)
11055                         sub_statement = sub_statement->base.next;
11056
11057                 anchor = &sub_statement->base.next;
11058         }
11059         next_token();
11060
11061         /* look over all statements again to produce no effect warnings */
11062         if (warning.unused_value) {
11063                 statement_t *sub_statement = statement->compound.statements;
11064                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11065                         if (sub_statement->kind != STATEMENT_EXPRESSION)
11066                                 continue;
11067                         /* don't emit a warning for the last expression in an expression
11068                          * statement as it has always an effect */
11069                         if (inside_expression_statement && sub_statement->base.next == NULL)
11070                                 continue;
11071
11072                         expression_t *expression = sub_statement->expression.expression;
11073                         if (!expression_has_effect(expression)) {
11074                                 warningf(&expression->base.source_position,
11075                                          "statement has no effect");
11076                         }
11077                 }
11078         }
11079
11080 end_error:
11081         rem_anchor_token(T_while);
11082         rem_anchor_token(T_wchar_t);
11083         rem_anchor_token(T_volatile);
11084         rem_anchor_token(T_void);
11085         rem_anchor_token(T_using);
11086         rem_anchor_token(T_unsigned);
11087         rem_anchor_token(T_union);
11088         rem_anchor_token(T_typeof);
11089         rem_anchor_token(T_typename);
11090         rem_anchor_token(T_typeid);
11091         rem_anchor_token(T_typedef);
11092         rem_anchor_token(T_try);
11093         rem_anchor_token(T_true);
11094         rem_anchor_token(T_throw);
11095         rem_anchor_token(T_this);
11096         rem_anchor_token(T_template);
11097         rem_anchor_token(T_switch);
11098         rem_anchor_token(T_struct);
11099         rem_anchor_token(T_static_cast);
11100         rem_anchor_token(T_static);
11101         rem_anchor_token(T_sizeof);
11102         rem_anchor_token(T_signed);
11103         rem_anchor_token(T_short);
11104         rem_anchor_token(T_return);
11105         rem_anchor_token(T_restrict);
11106         rem_anchor_token(T_reinterpret_cast);
11107         rem_anchor_token(T_register);
11108         rem_anchor_token(T_operator);
11109         rem_anchor_token(T_new);
11110         rem_anchor_token(T_long);
11111         rem_anchor_token(T_int);
11112         rem_anchor_token(T_inline);
11113         rem_anchor_token(T_if);
11114         rem_anchor_token(T_goto);
11115         rem_anchor_token(T_for);
11116         rem_anchor_token(T_float);
11117         rem_anchor_token(T_false);
11118         rem_anchor_token(T_extern);
11119         rem_anchor_token(T_enum);
11120         rem_anchor_token(T_dynamic_cast);
11121         rem_anchor_token(T_do);
11122         rem_anchor_token(T_double);
11123         rem_anchor_token(T_delete);
11124         rem_anchor_token(T_default);
11125         rem_anchor_token(T_continue);
11126         rem_anchor_token(T_const_cast);
11127         rem_anchor_token(T_const);
11128         rem_anchor_token(T_class);
11129         rem_anchor_token(T_char);
11130         rem_anchor_token(T_case);
11131         rem_anchor_token(T_break);
11132         rem_anchor_token(T_bool);
11133         rem_anchor_token(T_auto);
11134         rem_anchor_token(T_asm);
11135         rem_anchor_token(T___thread);
11136         rem_anchor_token(T___real__);
11137         rem_anchor_token(T___label__);
11138         rem_anchor_token(T___imag__);
11139         rem_anchor_token(T___func__);
11140         rem_anchor_token(T___extension__);
11141         rem_anchor_token(T___builtin_va_start);
11142         rem_anchor_token(T___attribute__);
11143         rem_anchor_token(T___alignof__);
11144         rem_anchor_token(T___PRETTY_FUNCTION__);
11145         rem_anchor_token(T___FUNCTION__);
11146         rem_anchor_token(T__Imaginary);
11147         rem_anchor_token(T__Complex);
11148         rem_anchor_token(T__Bool);
11149         rem_anchor_token(T_WIDE_STRING_LITERAL);
11150         rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11151         rem_anchor_token(T_STRING_LITERAL);
11152         rem_anchor_token(T_PLUSPLUS);
11153         rem_anchor_token(T_MINUSMINUS);
11154         rem_anchor_token(T_INTEGER);
11155         rem_anchor_token(T_IDENTIFIER);
11156         rem_anchor_token(T_FLOATINGPOINT);
11157         rem_anchor_token(T_COLONCOLON);
11158         rem_anchor_token(T_CHARACTER_CONSTANT);
11159         rem_anchor_token('~');
11160         rem_anchor_token('{');
11161         rem_anchor_token('-');
11162         rem_anchor_token('+');
11163         rem_anchor_token('*');
11164         rem_anchor_token('(');
11165         rem_anchor_token('&');
11166         rem_anchor_token('!');
11167         rem_anchor_token('}');
11168         assert(current_scope == &statement->compound.scope);
11169         scope_pop(old_scope);
11170         environment_pop_to(top);
11171
11172         POP_PARENT;
11173         return statement;
11174 }
11175
11176 /**
11177  * Check for unused global static functions and variables
11178  */
11179 static void check_unused_globals(void)
11180 {
11181         if (!warning.unused_function && !warning.unused_variable)
11182                 return;
11183
11184         for (const entity_t *entity = file_scope->entities; entity != NULL;
11185              entity = entity->base.next) {
11186                 if (!is_declaration(entity))
11187                         continue;
11188
11189                 const declaration_t *declaration = &entity->declaration;
11190                 if (declaration->used                  ||
11191                     declaration->modifiers & DM_UNUSED ||
11192                     declaration->modifiers & DM_USED   ||
11193                     declaration->storage_class != STORAGE_CLASS_STATIC)
11194                         continue;
11195
11196                 type_t *const type = declaration->type;
11197                 const char *s;
11198                 if (entity->kind == ENTITY_FUNCTION) {
11199                         /* inhibit warning for static inline functions */
11200                         if (entity->function.is_inline)
11201                                 continue;
11202
11203                         s = entity->function.statement != NULL ? "defined" : "declared";
11204                 } else {
11205                         s = "defined";
11206                 }
11207
11208                 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11209                         type, declaration->base.symbol, s);
11210         }
11211 }
11212
11213 static void parse_global_asm(void)
11214 {
11215         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11216
11217         eat(T_asm);
11218         expect('(', end_error);
11219
11220         statement->asms.asm_text = parse_string_literals();
11221         statement->base.next     = unit->global_asm;
11222         unit->global_asm         = statement;
11223
11224         expect(')', end_error);
11225         expect(';', end_error);
11226
11227 end_error:;
11228 }
11229
11230 static void parse_linkage_specification(void)
11231 {
11232         eat(T_extern);
11233         assert(token.type == T_STRING_LITERAL);
11234
11235         const char *linkage = parse_string_literals().begin;
11236
11237         linkage_kind_t old_linkage = current_linkage;
11238         linkage_kind_t new_linkage;
11239         if (strcmp(linkage, "C") == 0) {
11240                 new_linkage = LINKAGE_C;
11241         } else if (strcmp(linkage, "C++") == 0) {
11242                 new_linkage = LINKAGE_CXX;
11243         } else {
11244                 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11245                 new_linkage = LINKAGE_INVALID;
11246         }
11247         current_linkage = new_linkage;
11248
11249         if (token.type == '{') {
11250                 next_token();
11251                 parse_externals();
11252                 expect('}', end_error);
11253         } else {
11254                 parse_external();
11255         }
11256
11257 end_error:
11258         assert(current_linkage == new_linkage);
11259         current_linkage = old_linkage;
11260 }
11261
11262 static void parse_external(void)
11263 {
11264         switch (token.type) {
11265                 DECLARATION_START_NO_EXTERN
11266                 case T_IDENTIFIER:
11267                 case T___extension__:
11268                 /* tokens below are for implicit int */
11269                 case '&': /* & x; -> int& x; (and error later, because C++ has no
11270                              implicit int) */
11271                 case '*': /* * x; -> int* x; */
11272                 case '(': /* (x); -> int (x); */
11273                         parse_external_declaration();
11274                         return;
11275
11276                 case T_extern:
11277                         if (look_ahead(1)->type == T_STRING_LITERAL) {
11278                                 parse_linkage_specification();
11279                         } else {
11280                                 parse_external_declaration();
11281                         }
11282                         return;
11283
11284                 case T_asm:
11285                         parse_global_asm();
11286                         return;
11287
11288                 case T_namespace:
11289                         parse_namespace_definition();
11290                         return;
11291
11292                 case ';':
11293                         if (!strict_mode) {
11294                                 if (warning.other)
11295                                         warningf(HERE, "stray ';' outside of function");
11296                                 next_token();
11297                                 return;
11298                         }
11299                         /* FALLTHROUGH */
11300
11301                 default:
11302                         errorf(HERE, "stray %K outside of function", &token);
11303                         if (token.type == '(' || token.type == '{' || token.type == '[')
11304                                 eat_until_matching_token(token.type);
11305                         next_token();
11306                         return;
11307         }
11308 }
11309
11310 static void parse_externals(void)
11311 {
11312         add_anchor_token('}');
11313         add_anchor_token(T_EOF);
11314
11315 #ifndef NDEBUG
11316         unsigned char token_anchor_copy[T_LAST_TOKEN];
11317         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11318 #endif
11319
11320         while (token.type != T_EOF && token.type != '}') {
11321 #ifndef NDEBUG
11322                 bool anchor_leak = false;
11323                 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11324                         unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11325                         if (count != 0) {
11326                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11327                                 anchor_leak = true;
11328                         }
11329                 }
11330                 if (in_gcc_extension) {
11331                         errorf(HERE, "Leaked __extension__");
11332                         anchor_leak = true;
11333                 }
11334
11335                 if (anchor_leak)
11336                         abort();
11337 #endif
11338
11339                 parse_external();
11340         }
11341
11342         rem_anchor_token(T_EOF);
11343         rem_anchor_token('}');
11344 }
11345
11346 /**
11347  * Parse a translation unit.
11348  */
11349 static void parse_translation_unit(void)
11350 {
11351         add_anchor_token(T_EOF);
11352
11353         while (true) {
11354                 parse_externals();
11355
11356                 if (token.type == T_EOF)
11357                         break;
11358
11359                 errorf(HERE, "stray %K outside of function", &token);
11360                 if (token.type == '(' || token.type == '{' || token.type == '[')
11361                         eat_until_matching_token(token.type);
11362                 next_token();
11363         }
11364 }
11365
11366 /**
11367  * Parse the input.
11368  *
11369  * @return  the translation unit or NULL if errors occurred.
11370  */
11371 void start_parsing(void)
11372 {
11373         environment_stack = NEW_ARR_F(stack_entry_t, 0);
11374         label_stack       = NEW_ARR_F(stack_entry_t, 0);
11375         diagnostic_count  = 0;
11376         error_count       = 0;
11377         warning_count     = 0;
11378
11379         type_set_output(stderr);
11380         ast_set_output(stderr);
11381
11382         assert(unit == NULL);
11383         unit = allocate_ast_zero(sizeof(unit[0]));
11384
11385         assert(file_scope == NULL);
11386         file_scope = &unit->scope;
11387
11388         assert(current_scope == NULL);
11389         scope_push(&unit->scope);
11390 }
11391
11392 translation_unit_t *finish_parsing(void)
11393 {
11394         assert(current_scope == &unit->scope);
11395         scope_pop(NULL);
11396
11397         assert(file_scope == &unit->scope);
11398         check_unused_globals();
11399         file_scope = NULL;
11400
11401         DEL_ARR_F(environment_stack);
11402         DEL_ARR_F(label_stack);
11403
11404         translation_unit_t *result = unit;
11405         unit = NULL;
11406         return result;
11407 }
11408
11409 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11410  * are given length one. */
11411 static void complete_incomplete_arrays(void)
11412 {
11413         size_t n = ARR_LEN(incomplete_arrays);
11414         for (size_t i = 0; i != n; ++i) {
11415                 declaration_t *const decl      = incomplete_arrays[i];
11416                 type_t        *const orig_type = decl->type;
11417                 type_t        *const type      = skip_typeref(orig_type);
11418
11419                 if (!is_type_incomplete(type))
11420                         continue;
11421
11422                 if (warning.other) {
11423                         warningf(&decl->base.source_position,
11424                                         "array '%#T' assumed to have one element",
11425                                         orig_type, decl->base.symbol);
11426                 }
11427
11428                 type_t *const new_type = duplicate_type(type);
11429                 new_type->array.size_constant     = true;
11430                 new_type->array.has_implicit_size = true;
11431                 new_type->array.size              = 1;
11432
11433                 type_t *const result = identify_new_type(new_type);
11434
11435                 decl->type = result;
11436         }
11437 }
11438
11439 void parse(void)
11440 {
11441         lookahead_bufpos = 0;
11442         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11443                 next_token();
11444         }
11445         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11446         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11447         parse_translation_unit();
11448         complete_incomplete_arrays();
11449         DEL_ARR_F(incomplete_arrays);
11450         incomplete_arrays = NULL;
11451 }
11452
11453 /**
11454  * Initialize the parser.
11455  */
11456 void init_parser(void)
11457 {
11458         sym_anonymous = symbol_table_insert("<anonymous>");
11459
11460         if (c_mode & _MS) {
11461                 /* add predefined symbols for extended-decl-modifier */
11462                 sym_align         = symbol_table_insert("align");
11463                 sym_allocate      = symbol_table_insert("allocate");
11464                 sym_dllimport     = symbol_table_insert("dllimport");
11465                 sym_dllexport     = symbol_table_insert("dllexport");
11466                 sym_naked         = symbol_table_insert("naked");
11467                 sym_noinline      = symbol_table_insert("noinline");
11468                 sym_returns_twice = symbol_table_insert("returns_twice");
11469                 sym_noreturn      = symbol_table_insert("noreturn");
11470                 sym_nothrow       = symbol_table_insert("nothrow");
11471                 sym_novtable      = symbol_table_insert("novtable");
11472                 sym_property      = symbol_table_insert("property");
11473                 sym_get           = symbol_table_insert("get");
11474                 sym_put           = symbol_table_insert("put");
11475                 sym_selectany     = symbol_table_insert("selectany");
11476                 sym_thread        = symbol_table_insert("thread");
11477                 sym_uuid          = symbol_table_insert("uuid");
11478                 sym_deprecated    = symbol_table_insert("deprecated");
11479                 sym_restrict      = symbol_table_insert("restrict");
11480                 sym_noalias       = symbol_table_insert("noalias");
11481         }
11482         memset(token_anchor_set, 0, sizeof(token_anchor_set));
11483
11484         init_expression_parsers();
11485         obstack_init(&temp_obst);
11486
11487         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11488         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11489 }
11490
11491 /**
11492  * Terminate the parser.
11493  */
11494 void exit_parser(void)
11495 {
11496         obstack_free(&temp_obst, NULL);
11497 }