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