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