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