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