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