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