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