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