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