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