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