00a8ed4f0cf1346565dff169f224452c2c1c46f2
[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         result->base.parenthesized = true;
7231         rem_anchor_token(')');
7232         expect(')', end_error);
7233
7234 end_error:
7235         return result;
7236 }
7237
7238 static expression_t *parse_function_keyword(void)
7239 {
7240         /* TODO */
7241
7242         if (current_function == NULL) {
7243                 errorf(HERE, "'__func__' used outside of a function");
7244         }
7245
7246         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7247         expression->base.type     = type_char_ptr;
7248         expression->funcname.kind = FUNCNAME_FUNCTION;
7249
7250         next_token();
7251
7252         return expression;
7253 }
7254
7255 static expression_t *parse_pretty_function_keyword(void)
7256 {
7257         if (current_function == NULL) {
7258                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7259         }
7260
7261         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7262         expression->base.type     = type_char_ptr;
7263         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7264
7265         eat(T___PRETTY_FUNCTION__);
7266
7267         return expression;
7268 }
7269
7270 static expression_t *parse_funcsig_keyword(void)
7271 {
7272         if (current_function == NULL) {
7273                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7274         }
7275
7276         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7277         expression->base.type     = type_char_ptr;
7278         expression->funcname.kind = FUNCNAME_FUNCSIG;
7279
7280         eat(T___FUNCSIG__);
7281
7282         return expression;
7283 }
7284
7285 static expression_t *parse_funcdname_keyword(void)
7286 {
7287         if (current_function == NULL) {
7288                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7289         }
7290
7291         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7292         expression->base.type     = type_char_ptr;
7293         expression->funcname.kind = FUNCNAME_FUNCDNAME;
7294
7295         eat(T___FUNCDNAME__);
7296
7297         return expression;
7298 }
7299
7300 static designator_t *parse_designator(void)
7301 {
7302         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
7303         result->source_position = *HERE;
7304
7305         if (token.type != T_IDENTIFIER) {
7306                 parse_error_expected("while parsing member designator",
7307                                      T_IDENTIFIER, NULL);
7308                 return NULL;
7309         }
7310         result->symbol = token.v.symbol;
7311         next_token();
7312
7313         designator_t *last_designator = result;
7314         while (true) {
7315                 if (token.type == '.') {
7316                         next_token();
7317                         if (token.type != T_IDENTIFIER) {
7318                                 parse_error_expected("while parsing member designator",
7319                                                      T_IDENTIFIER, NULL);
7320                                 return NULL;
7321                         }
7322                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7323                         designator->source_position = *HERE;
7324                         designator->symbol          = token.v.symbol;
7325                         next_token();
7326
7327                         last_designator->next = designator;
7328                         last_designator       = designator;
7329                         continue;
7330                 }
7331                 if (token.type == '[') {
7332                         next_token();
7333                         add_anchor_token(']');
7334                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7335                         designator->source_position = *HERE;
7336                         designator->array_index     = parse_expression();
7337                         rem_anchor_token(']');
7338                         expect(']', end_error);
7339                         if (designator->array_index == NULL) {
7340                                 return NULL;
7341                         }
7342
7343                         last_designator->next = designator;
7344                         last_designator       = designator;
7345                         continue;
7346                 }
7347                 break;
7348         }
7349
7350         return result;
7351 end_error:
7352         return NULL;
7353 }
7354
7355 /**
7356  * Parse the __builtin_offsetof() expression.
7357  */
7358 static expression_t *parse_offsetof(void)
7359 {
7360         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7361         expression->base.type    = type_size_t;
7362
7363         eat(T___builtin_offsetof);
7364
7365         expect('(', end_error);
7366         add_anchor_token(',');
7367         type_t *type = parse_typename();
7368         rem_anchor_token(',');
7369         expect(',', end_error);
7370         add_anchor_token(')');
7371         designator_t *designator = parse_designator();
7372         rem_anchor_token(')');
7373         expect(')', end_error);
7374
7375         expression->offsetofe.type       = type;
7376         expression->offsetofe.designator = designator;
7377
7378         type_path_t path;
7379         memset(&path, 0, sizeof(path));
7380         path.top_type = type;
7381         path.path     = NEW_ARR_F(type_path_entry_t, 0);
7382
7383         descend_into_subtype(&path);
7384
7385         if (!walk_designator(&path, designator, true)) {
7386                 return create_invalid_expression();
7387         }
7388
7389         DEL_ARR_F(path.path);
7390
7391         return expression;
7392 end_error:
7393         return create_invalid_expression();
7394 }
7395
7396 /**
7397  * Parses a _builtin_va_start() expression.
7398  */
7399 static expression_t *parse_va_start(void)
7400 {
7401         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7402
7403         eat(T___builtin_va_start);
7404
7405         expect('(', end_error);
7406         add_anchor_token(',');
7407         expression->va_starte.ap = parse_assignment_expression();
7408         rem_anchor_token(',');
7409         expect(',', end_error);
7410         expression_t *const expr = parse_assignment_expression();
7411         if (expr->kind == EXPR_REFERENCE) {
7412                 entity_t *const entity = expr->reference.entity;
7413                 if (entity->base.parent_scope != &current_function->parameters
7414                                 || entity->base.next != NULL
7415                                 || entity->kind != ENTITY_PARAMETER) {
7416                         errorf(&expr->base.source_position,
7417                                "second argument of 'va_start' must be last parameter of the current function");
7418                 } else {
7419                         expression->va_starte.parameter = &entity->variable;
7420                 }
7421                 expect(')', end_error);
7422                 return expression;
7423         }
7424         expect(')', end_error);
7425 end_error:
7426         return create_invalid_expression();
7427 }
7428
7429 /**
7430  * Parses a _builtin_va_arg() expression.
7431  */
7432 static expression_t *parse_va_arg(void)
7433 {
7434         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7435
7436         eat(T___builtin_va_arg);
7437
7438         expect('(', end_error);
7439         expression->va_arge.ap = parse_assignment_expression();
7440         expect(',', end_error);
7441         expression->base.type = parse_typename();
7442         expect(')', end_error);
7443
7444         return expression;
7445 end_error:
7446         return create_invalid_expression();
7447 }
7448
7449 static expression_t *parse_builtin_symbol(void)
7450 {
7451         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7452
7453         symbol_t *symbol = token.v.symbol;
7454
7455         expression->builtin_symbol.symbol = symbol;
7456         next_token();
7457
7458         type_t *type = get_builtin_symbol_type(symbol);
7459         type = automatic_type_conversion(type);
7460
7461         expression->base.type = type;
7462         return expression;
7463 }
7464
7465 /**
7466  * Parses a __builtin_constant() expression.
7467  */
7468 static expression_t *parse_builtin_constant(void)
7469 {
7470         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7471
7472         eat(T___builtin_constant_p);
7473
7474         expect('(', end_error);
7475         add_anchor_token(')');
7476         expression->builtin_constant.value = parse_assignment_expression();
7477         rem_anchor_token(')');
7478         expect(')', end_error);
7479         expression->base.type = type_int;
7480
7481         return expression;
7482 end_error:
7483         return create_invalid_expression();
7484 }
7485
7486 /**
7487  * Parses a __builtin_prefetch() expression.
7488  */
7489 static expression_t *parse_builtin_prefetch(void)
7490 {
7491         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7492
7493         eat(T___builtin_prefetch);
7494
7495         expect('(', end_error);
7496         add_anchor_token(')');
7497         expression->builtin_prefetch.adr = parse_assignment_expression();
7498         if (token.type == ',') {
7499                 next_token();
7500                 expression->builtin_prefetch.rw = parse_assignment_expression();
7501         }
7502         if (token.type == ',') {
7503                 next_token();
7504                 expression->builtin_prefetch.locality = parse_assignment_expression();
7505         }
7506         rem_anchor_token(')');
7507         expect(')', end_error);
7508         expression->base.type = type_void;
7509
7510         return expression;
7511 end_error:
7512         return create_invalid_expression();
7513 }
7514
7515 /**
7516  * Parses a __builtin_is_*() compare expression.
7517  */
7518 static expression_t *parse_compare_builtin(void)
7519 {
7520         expression_t *expression;
7521
7522         switch (token.type) {
7523         case T___builtin_isgreater:
7524                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7525                 break;
7526         case T___builtin_isgreaterequal:
7527                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7528                 break;
7529         case T___builtin_isless:
7530                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7531                 break;
7532         case T___builtin_islessequal:
7533                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7534                 break;
7535         case T___builtin_islessgreater:
7536                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7537                 break;
7538         case T___builtin_isunordered:
7539                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7540                 break;
7541         default:
7542                 internal_errorf(HERE, "invalid compare builtin found");
7543         }
7544         expression->base.source_position = *HERE;
7545         next_token();
7546
7547         expect('(', end_error);
7548         expression->binary.left = parse_assignment_expression();
7549         expect(',', end_error);
7550         expression->binary.right = parse_assignment_expression();
7551         expect(')', end_error);
7552
7553         type_t *const orig_type_left  = expression->binary.left->base.type;
7554         type_t *const orig_type_right = expression->binary.right->base.type;
7555
7556         type_t *const type_left  = skip_typeref(orig_type_left);
7557         type_t *const type_right = skip_typeref(orig_type_right);
7558         if (!is_type_float(type_left) && !is_type_float(type_right)) {
7559                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7560                         type_error_incompatible("invalid operands in comparison",
7561                                 &expression->base.source_position, orig_type_left, orig_type_right);
7562                 }
7563         } else {
7564                 semantic_comparison(&expression->binary);
7565         }
7566
7567         return expression;
7568 end_error:
7569         return create_invalid_expression();
7570 }
7571
7572 #if 0
7573 /**
7574  * Parses a __builtin_expect(, end_error) expression.
7575  */
7576 static expression_t *parse_builtin_expect(void, end_error)
7577 {
7578         expression_t *expression
7579                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7580
7581         eat(T___builtin_expect);
7582
7583         expect('(', end_error);
7584         expression->binary.left = parse_assignment_expression();
7585         expect(',', end_error);
7586         expression->binary.right = parse_constant_expression();
7587         expect(')', end_error);
7588
7589         expression->base.type = expression->binary.left->base.type;
7590
7591         return expression;
7592 end_error:
7593         return create_invalid_expression();
7594 }
7595 #endif
7596
7597 /**
7598  * Parses a MS assume() expression.
7599  */
7600 static expression_t *parse_assume(void)
7601 {
7602         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7603
7604         eat(T__assume);
7605
7606         expect('(', end_error);
7607         add_anchor_token(')');
7608         expression->unary.value = parse_assignment_expression();
7609         rem_anchor_token(')');
7610         expect(')', end_error);
7611
7612         expression->base.type = type_void;
7613         return expression;
7614 end_error:
7615         return create_invalid_expression();
7616 }
7617
7618 /**
7619  * Return the declaration for a given label symbol or create a new one.
7620  *
7621  * @param symbol  the symbol of the label
7622  */
7623 static label_t *get_label(symbol_t *symbol)
7624 {
7625         entity_t *label;
7626         assert(current_function != NULL);
7627
7628         label = get_entity(symbol, NAMESPACE_LABEL);
7629         /* if we found a local label, we already created the declaration */
7630         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7631                 if (label->base.parent_scope != current_scope) {
7632                         assert(label->base.parent_scope->depth < current_scope->depth);
7633                         current_function->goto_to_outer = true;
7634                 }
7635                 return &label->label;
7636         }
7637
7638         label = get_entity(symbol, NAMESPACE_LABEL);
7639         /* if we found a label in the same function, then we already created the
7640          * declaration */
7641         if (label != NULL
7642                         && label->base.parent_scope == &current_function->parameters) {
7643                 return &label->label;
7644         }
7645
7646         /* otherwise we need to create a new one */
7647         label               = allocate_entity_zero(ENTITY_LABEL);
7648         label->base.namespc = NAMESPACE_LABEL;
7649         label->base.symbol  = symbol;
7650
7651         label_push(label);
7652
7653         return &label->label;
7654 }
7655
7656 /**
7657  * Parses a GNU && label address expression.
7658  */
7659 static expression_t *parse_label_address(void)
7660 {
7661         source_position_t source_position = token.source_position;
7662         eat(T_ANDAND);
7663         if (token.type != T_IDENTIFIER) {
7664                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7665                 goto end_error;
7666         }
7667         symbol_t *symbol = token.v.symbol;
7668         next_token();
7669
7670         label_t *label       = get_label(symbol);
7671         label->used          = true;
7672         label->address_taken = true;
7673
7674         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7675         expression->base.source_position = source_position;
7676
7677         /* label address is threaten as a void pointer */
7678         expression->base.type           = type_void_ptr;
7679         expression->label_address.label = label;
7680         return expression;
7681 end_error:
7682         return create_invalid_expression();
7683 }
7684
7685 /**
7686  * Parse a microsoft __noop expression.
7687  */
7688 static expression_t *parse_noop_expression(void)
7689 {
7690         /* the result is a (int)0 */
7691         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
7692         cnst->base.type            = type_int;
7693         cnst->conste.v.int_value   = 0;
7694         cnst->conste.is_ms_noop    = true;
7695
7696         eat(T___noop);
7697
7698         if (token.type == '(') {
7699                 /* parse arguments */
7700                 eat('(');
7701                 add_anchor_token(')');
7702                 add_anchor_token(',');
7703
7704                 if (token.type != ')') {
7705                         while (true) {
7706                                 (void)parse_assignment_expression();
7707                                 if (token.type != ',')
7708                                         break;
7709                                 next_token();
7710                         }
7711                 }
7712         }
7713         rem_anchor_token(',');
7714         rem_anchor_token(')');
7715         expect(')', end_error);
7716
7717 end_error:
7718         return cnst;
7719 }
7720
7721 /**
7722  * Parses a primary expression.
7723  */
7724 static expression_t *parse_primary_expression(void)
7725 {
7726         switch (token.type) {
7727                 case T_false:                    return parse_bool_const(false);
7728                 case T_true:                     return parse_bool_const(true);
7729                 case T_INTEGER:                  return parse_int_const();
7730                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
7731                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
7732                 case T_FLOATINGPOINT:            return parse_float_const();
7733                 case T_STRING_LITERAL:
7734                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
7735                 case T_IDENTIFIER:               return parse_reference();
7736                 case T___FUNCTION__:
7737                 case T___func__:                 return parse_function_keyword();
7738                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
7739                 case T___FUNCSIG__:              return parse_funcsig_keyword();
7740                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
7741                 case T___builtin_offsetof:       return parse_offsetof();
7742                 case T___builtin_va_start:       return parse_va_start();
7743                 case T___builtin_va_arg:         return parse_va_arg();
7744                 case T___builtin_expect:
7745                 case T___builtin_alloca:
7746                 case T___builtin_inf:
7747                 case T___builtin_inff:
7748                 case T___builtin_infl:
7749                 case T___builtin_nan:
7750                 case T___builtin_nanf:
7751                 case T___builtin_nanl:
7752                 case T___builtin_huge_val:
7753                 case T___builtin_va_end:         return parse_builtin_symbol();
7754                 case T___builtin_isgreater:
7755                 case T___builtin_isgreaterequal:
7756                 case T___builtin_isless:
7757                 case T___builtin_islessequal:
7758                 case T___builtin_islessgreater:
7759                 case T___builtin_isunordered:    return parse_compare_builtin();
7760                 case T___builtin_constant_p:     return parse_builtin_constant();
7761                 case T___builtin_prefetch:       return parse_builtin_prefetch();
7762                 case T__assume:                  return parse_assume();
7763                 case T_ANDAND:
7764                         if (GNU_MODE)
7765                                 return parse_label_address();
7766                         break;
7767
7768                 case '(':                        return parse_parenthesized_expression();
7769                 case T___noop:                   return parse_noop_expression();
7770         }
7771
7772         errorf(HERE, "unexpected token %K, expected an expression", &token);
7773         return create_invalid_expression();
7774 }
7775
7776 /**
7777  * Check if the expression has the character type and issue a warning then.
7778  */
7779 static void check_for_char_index_type(const expression_t *expression)
7780 {
7781         type_t       *const type      = expression->base.type;
7782         const type_t *const base_type = skip_typeref(type);
7783
7784         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7785                         warning.char_subscripts) {
7786                 warningf(&expression->base.source_position,
7787                          "array subscript has type '%T'", type);
7788         }
7789 }
7790
7791 static expression_t *parse_array_expression(expression_t *left)
7792 {
7793         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7794
7795         eat('[');
7796         add_anchor_token(']');
7797
7798         expression_t *inside = parse_expression();
7799
7800         type_t *const orig_type_left   = left->base.type;
7801         type_t *const orig_type_inside = inside->base.type;
7802
7803         type_t *const type_left   = skip_typeref(orig_type_left);
7804         type_t *const type_inside = skip_typeref(orig_type_inside);
7805
7806         type_t                    *return_type;
7807         array_access_expression_t *array_access = &expression->array_access;
7808         if (is_type_pointer(type_left)) {
7809                 return_type             = type_left->pointer.points_to;
7810                 array_access->array_ref = left;
7811                 array_access->index     = inside;
7812                 check_for_char_index_type(inside);
7813         } else if (is_type_pointer(type_inside)) {
7814                 return_type             = type_inside->pointer.points_to;
7815                 array_access->array_ref = inside;
7816                 array_access->index     = left;
7817                 array_access->flipped   = true;
7818                 check_for_char_index_type(left);
7819         } else {
7820                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7821                         errorf(HERE,
7822                                 "array access on object with non-pointer types '%T', '%T'",
7823                                 orig_type_left, orig_type_inside);
7824                 }
7825                 return_type             = type_error_type;
7826                 array_access->array_ref = left;
7827                 array_access->index     = inside;
7828         }
7829
7830         expression->base.type = automatic_type_conversion(return_type);
7831
7832         rem_anchor_token(']');
7833         expect(']', end_error);
7834 end_error:
7835         return expression;
7836 }
7837
7838 static expression_t *parse_typeprop(expression_kind_t const kind)
7839 {
7840         expression_t  *tp_expression = allocate_expression_zero(kind);
7841         tp_expression->base.type     = type_size_t;
7842
7843         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7844
7845         /* we only refer to a type property, mark this case */
7846         bool old     = in_type_prop;
7847         in_type_prop = true;
7848
7849         type_t       *orig_type;
7850         expression_t *expression;
7851         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7852                 next_token();
7853                 add_anchor_token(')');
7854                 orig_type = parse_typename();
7855                 rem_anchor_token(')');
7856                 expect(')', end_error);
7857
7858                 if (token.type == '{') {
7859                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7860                          * starting with a compound literal */
7861                         expression = parse_compound_literal(orig_type);
7862                         goto typeprop_expression;
7863                 }
7864         } else {
7865                 expression = parse_sub_expression(PREC_UNARY);
7866
7867 typeprop_expression:
7868                 tp_expression->typeprop.tp_expression = expression;
7869
7870                 orig_type = revert_automatic_type_conversion(expression);
7871                 expression->base.type = orig_type;
7872         }
7873
7874         tp_expression->typeprop.type   = orig_type;
7875         type_t const* const type       = skip_typeref(orig_type);
7876         char   const* const wrong_type =
7877                 is_type_incomplete(type)    ? "incomplete"          :
7878                 type->kind == TYPE_FUNCTION ? "function designator" :
7879                 type->kind == TYPE_BITFIELD ? "bitfield"            :
7880                 NULL;
7881         if (wrong_type != NULL) {
7882                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7883                 errorf(&tp_expression->base.source_position,
7884                                 "operand of %s expression must not be of %s type '%T'",
7885                                 what, wrong_type, orig_type);
7886         }
7887
7888 end_error:
7889         in_type_prop = old;
7890         return tp_expression;
7891 }
7892
7893 static expression_t *parse_sizeof(void)
7894 {
7895         return parse_typeprop(EXPR_SIZEOF);
7896 }
7897
7898 static expression_t *parse_alignof(void)
7899 {
7900         return parse_typeprop(EXPR_ALIGNOF);
7901 }
7902
7903 static expression_t *parse_select_expression(expression_t *compound)
7904 {
7905         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
7906         select->select.compound = compound;
7907
7908         assert(token.type == '.' || token.type == T_MINUSGREATER);
7909         bool is_pointer = (token.type == T_MINUSGREATER);
7910         next_token();
7911
7912         if (token.type != T_IDENTIFIER) {
7913                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7914                 return select;
7915         }
7916         symbol_t *symbol = token.v.symbol;
7917         next_token();
7918
7919         type_t *const orig_type = compound->base.type;
7920         type_t *const type      = skip_typeref(orig_type);
7921
7922         type_t *type_left;
7923         bool    saw_error = false;
7924         if (is_type_pointer(type)) {
7925                 if (!is_pointer) {
7926                         errorf(HERE,
7927                                "request for member '%Y' in something not a struct or union, but '%T'",
7928                                symbol, orig_type);
7929                         saw_error = true;
7930                 }
7931                 type_left = skip_typeref(type->pointer.points_to);
7932         } else {
7933                 if (is_pointer && is_type_valid(type)) {
7934                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7935                         saw_error = true;
7936                 }
7937                 type_left = type;
7938         }
7939
7940         entity_t *entry;
7941         if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7942             type_left->kind == TYPE_COMPOUND_UNION) {
7943                 compound_t *compound = type_left->compound.compound;
7944
7945                 if (!compound->complete) {
7946                         errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7947                                symbol, type_left);
7948                         goto create_error_entry;
7949                 }
7950
7951                 entry = find_compound_entry(compound, symbol);
7952                 if (entry == NULL) {
7953                         errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7954                         goto create_error_entry;
7955                 }
7956         } else {
7957                 if (is_type_valid(type_left) && !saw_error) {
7958                         errorf(HERE,
7959                                "request for member '%Y' in something not a struct or union, but '%T'",
7960                                symbol, type_left);
7961                 }
7962 create_error_entry:
7963                 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7964         }
7965
7966         assert(is_declaration(entry));
7967         select->select.compound_entry = entry;
7968
7969         type_t *entry_type = entry->declaration.type;
7970         type_t *res_type
7971                 = get_qualified_type(entry_type, type_left->base.qualifiers);
7972
7973         /* we always do the auto-type conversions; the & and sizeof parser contains
7974          * code to revert this! */
7975         select->base.type = automatic_type_conversion(res_type);
7976
7977         type_t *skipped = skip_typeref(res_type);
7978         if (skipped->kind == TYPE_BITFIELD) {
7979                 select->base.type = skipped->bitfield.base_type;
7980         }
7981
7982         return select;
7983 }
7984
7985 static void check_call_argument(const function_parameter_t *parameter,
7986                                 call_argument_t *argument, unsigned pos)
7987 {
7988         type_t         *expected_type      = parameter->type;
7989         type_t         *expected_type_skip = skip_typeref(expected_type);
7990         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7991         expression_t   *arg_expr           = argument->expression;
7992         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7993
7994         /* handle transparent union gnu extension */
7995         if (is_type_union(expected_type_skip)
7996                         && (expected_type_skip->base.modifiers
7997                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7998                 compound_t *union_decl  = expected_type_skip->compound.compound;
7999                 type_t     *best_type   = NULL;
8000                 entity_t   *entry       = union_decl->members.entities;
8001                 for ( ; entry != NULL; entry = entry->base.next) {
8002                         assert(is_declaration(entry));
8003                         type_t *decl_type = entry->declaration.type;
8004                         error = semantic_assign(decl_type, arg_expr);
8005                         if (error == ASSIGN_ERROR_INCOMPATIBLE
8006                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8007                                 continue;
8008
8009                         if (error == ASSIGN_SUCCESS) {
8010                                 best_type = decl_type;
8011                         } else if (best_type == NULL) {
8012                                 best_type = decl_type;
8013                         }
8014                 }
8015
8016                 if (best_type != NULL) {
8017                         expected_type = best_type;
8018                 }
8019         }
8020
8021         error                = semantic_assign(expected_type, arg_expr);
8022         argument->expression = create_implicit_cast(argument->expression,
8023                                                     expected_type);
8024
8025         if (error != ASSIGN_SUCCESS) {
8026                 /* report exact scope in error messages (like "in argument 3") */
8027                 char buf[64];
8028                 snprintf(buf, sizeof(buf), "call argument %u", pos);
8029                 report_assign_error(error, expected_type, arg_expr,     buf,
8030                                                         &arg_expr->base.source_position);
8031         } else if (warning.traditional || warning.conversion) {
8032                 type_t *const promoted_type = get_default_promoted_type(arg_type);
8033                 if (!types_compatible(expected_type_skip, promoted_type) &&
8034                     !types_compatible(expected_type_skip, type_void_ptr) &&
8035                     !types_compatible(type_void_ptr,      promoted_type)) {
8036                         /* Deliberately show the skipped types in this warning */
8037                         warningf(&arg_expr->base.source_position,
8038                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
8039                                 pos, expected_type_skip, promoted_type);
8040                 }
8041         }
8042 }
8043
8044 /**
8045  * Parse a call expression, ie. expression '( ... )'.
8046  *
8047  * @param expression  the function address
8048  */
8049 static expression_t *parse_call_expression(expression_t *expression)
8050 {
8051         expression_t      *result = allocate_expression_zero(EXPR_CALL);
8052         call_expression_t *call   = &result->call;
8053         call->function            = expression;
8054
8055         type_t *const orig_type = expression->base.type;
8056         type_t *const type      = skip_typeref(orig_type);
8057
8058         function_type_t *function_type = NULL;
8059         if (is_type_pointer(type)) {
8060                 type_t *const to_type = skip_typeref(type->pointer.points_to);
8061
8062                 if (is_type_function(to_type)) {
8063                         function_type   = &to_type->function;
8064                         call->base.type = function_type->return_type;
8065                 }
8066         }
8067
8068         if (function_type == NULL && is_type_valid(type)) {
8069                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8070         }
8071
8072         /* parse arguments */
8073         eat('(');
8074         add_anchor_token(')');
8075         add_anchor_token(',');
8076
8077         if (token.type != ')') {
8078                 call_argument_t *last_argument = NULL;
8079
8080                 while (true) {
8081                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8082
8083                         argument->expression = parse_assignment_expression();
8084                         if (last_argument == NULL) {
8085                                 call->arguments = argument;
8086                         } else {
8087                                 last_argument->next = argument;
8088                         }
8089                         last_argument = argument;
8090
8091                         if (token.type != ',')
8092                                 break;
8093                         next_token();
8094                 }
8095         }
8096         rem_anchor_token(',');
8097         rem_anchor_token(')');
8098         expect(')', end_error);
8099
8100         if (function_type == NULL)
8101                 return result;
8102
8103         function_parameter_t *parameter = function_type->parameters;
8104         call_argument_t      *argument  = call->arguments;
8105         if (!function_type->unspecified_parameters) {
8106                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8107                                 parameter = parameter->next, argument = argument->next) {
8108                         check_call_argument(parameter, argument, ++pos);
8109                 }
8110
8111                 if (parameter != NULL) {
8112                         errorf(HERE, "too few arguments to function '%E'", expression);
8113                 } else if (argument != NULL && !function_type->variadic) {
8114                         errorf(HERE, "too many arguments to function '%E'", expression);
8115                 }
8116         }
8117
8118         /* do default promotion */
8119         for (; argument != NULL; argument = argument->next) {
8120                 type_t *type = argument->expression->base.type;
8121
8122                 type = get_default_promoted_type(type);
8123
8124                 argument->expression
8125                         = create_implicit_cast(argument->expression, type);
8126         }
8127
8128         check_format(&result->call);
8129
8130         if (warning.aggregate_return &&
8131             is_type_compound(skip_typeref(function_type->return_type))) {
8132                 warningf(&result->base.source_position,
8133                          "function call has aggregate value");
8134         }
8135
8136 end_error:
8137         return result;
8138 }
8139
8140 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8141
8142 static bool same_compound_type(const type_t *type1, const type_t *type2)
8143 {
8144         return
8145                 is_type_compound(type1) &&
8146                 type1->kind == type2->kind &&
8147                 type1->compound.compound == type2->compound.compound;
8148 }
8149
8150 static expression_t const *get_reference_address(expression_t const *expr)
8151 {
8152         bool regular_take_address = true;
8153         for (;;) {
8154                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8155                         expr = expr->unary.value;
8156                 } else {
8157                         regular_take_address = false;
8158                 }
8159
8160                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8161                         break;
8162
8163                 expr = expr->unary.value;
8164         }
8165
8166         if (expr->kind != EXPR_REFERENCE)
8167                 return NULL;
8168
8169         /* special case for functions which are automatically converted to a
8170          * pointer to function without an extra TAKE_ADDRESS operation */
8171         if (!regular_take_address &&
8172                         expr->reference.entity->kind != ENTITY_FUNCTION) {
8173                 return NULL;
8174         }
8175
8176         return expr;
8177 }
8178
8179 static void warn_reference_address_as_bool(expression_t const* expr)
8180 {
8181         if (!warning.address)
8182                 return;
8183
8184         expr = get_reference_address(expr);
8185         if (expr != NULL) {
8186                 warningf(&expr->base.source_position,
8187                          "the address of '%Y' will always evaluate as 'true'",
8188                          expr->reference.entity->base.symbol);
8189         }
8190 }
8191
8192 static void warn_assignment_in_condition(const expression_t *const expr)
8193 {
8194         if (!warning.parentheses)
8195                 return;
8196         if (expr->base.kind != EXPR_BINARY_ASSIGN)
8197                 return;
8198         if (expr->base.parenthesized)
8199                 return;
8200         warningf(&expr->base.source_position,
8201                         "suggest parentheses around assignment used as truth value");
8202 }
8203
8204 static void semantic_condition(expression_t const *const expr,
8205                                char const *const context)
8206 {
8207         type_t *const type = skip_typeref(expr->base.type);
8208         if (is_type_scalar(type)) {
8209                 warn_reference_address_as_bool(expr);
8210                 warn_assignment_in_condition(expr);
8211         } else if (is_type_valid(type)) {
8212                 errorf(&expr->base.source_position,
8213                                 "%s must have scalar type", context);
8214         }
8215 }
8216
8217 /**
8218  * Parse a conditional expression, ie. 'expression ? ... : ...'.
8219  *
8220  * @param expression  the conditional expression
8221  */
8222 static expression_t *parse_conditional_expression(expression_t *expression)
8223 {
8224         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8225
8226         conditional_expression_t *conditional = &result->conditional;
8227         conditional->condition                = expression;
8228
8229         eat('?');
8230         add_anchor_token(':');
8231
8232         /* Â§6.5.15:2  The first operand shall have scalar type. */
8233         semantic_condition(expression, "condition of conditional operator");
8234
8235         expression_t *true_expression = expression;
8236         bool          gnu_cond = false;
8237         if (GNU_MODE && token.type == ':') {
8238                 gnu_cond = true;
8239         } else {
8240                 true_expression = parse_expression();
8241         }
8242         rem_anchor_token(':');
8243         expect(':', end_error);
8244         expression_t *false_expression =
8245                 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8246
8247         type_t *const orig_true_type  = true_expression->base.type;
8248         type_t *const orig_false_type = false_expression->base.type;
8249         type_t *const true_type       = skip_typeref(orig_true_type);
8250         type_t *const false_type      = skip_typeref(orig_false_type);
8251
8252         /* 6.5.15.3 */
8253         type_t *result_type;
8254         if (is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8255                         is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8256                 /* ISO/IEC 14882:1998(E) Â§5.16:2 */
8257                 if (true_expression->kind == EXPR_UNARY_THROW) {
8258                         result_type = false_type;
8259                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8260                         result_type = true_type;
8261                 } else {
8262                         if (warning.other && (
8263                                                 !is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8264                                                 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8265                                         )) {
8266                                 warningf(&conditional->base.source_position,
8267                                                 "ISO C forbids conditional expression with only one void side");
8268                         }
8269                         result_type = type_void;
8270                 }
8271         } else if (is_type_arithmetic(true_type)
8272                    && is_type_arithmetic(false_type)) {
8273                 result_type = semantic_arithmetic(true_type, false_type);
8274
8275                 true_expression  = create_implicit_cast(true_expression, result_type);
8276                 false_expression = create_implicit_cast(false_expression, result_type);
8277
8278                 conditional->true_expression  = true_expression;
8279                 conditional->false_expression = false_expression;
8280                 conditional->base.type        = result_type;
8281         } else if (same_compound_type(true_type, false_type)) {
8282                 /* just take 1 of the 2 types */
8283                 result_type = true_type;
8284         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8285                 type_t *pointer_type;
8286                 type_t *other_type;
8287                 expression_t *other_expression;
8288                 if (is_type_pointer(true_type) &&
8289                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8290                         pointer_type     = true_type;
8291                         other_type       = false_type;
8292                         other_expression = false_expression;
8293                 } else {
8294                         pointer_type     = false_type;
8295                         other_type       = true_type;
8296                         other_expression = true_expression;
8297                 }
8298
8299                 if (is_null_pointer_constant(other_expression)) {
8300                         result_type = pointer_type;
8301                 } else if (is_type_pointer(other_type)) {
8302                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8303                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
8304
8305                         type_t *to;
8306                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8307                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8308                                 to = type_void;
8309                         } else if (types_compatible(get_unqualified_type(to1),
8310                                                     get_unqualified_type(to2))) {
8311                                 to = to1;
8312                         } else {
8313                                 if (warning.other) {
8314                                         warningf(&conditional->base.source_position,
8315                                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
8316                                                         true_type, false_type);
8317                                 }
8318                                 to = type_void;
8319                         }
8320
8321                         type_t *const type =
8322                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8323                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8324                 } else if (is_type_integer(other_type)) {
8325                         if (warning.other) {
8326                                 warningf(&conditional->base.source_position,
8327                                                 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8328                         }
8329                         result_type = pointer_type;
8330                 } else {
8331                         if (is_type_valid(other_type)) {
8332                                 type_error_incompatible("while parsing conditional",
8333                                                 &expression->base.source_position, true_type, false_type);
8334                         }
8335                         result_type = type_error_type;
8336                 }
8337         } else {
8338                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8339                         type_error_incompatible("while parsing conditional",
8340                                                 &conditional->base.source_position, true_type,
8341                                                 false_type);
8342                 }
8343                 result_type = type_error_type;
8344         }
8345
8346         conditional->true_expression
8347                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8348         conditional->false_expression
8349                 = create_implicit_cast(false_expression, result_type);
8350         conditional->base.type = result_type;
8351         return result;
8352 end_error:
8353         return create_invalid_expression();
8354 }
8355
8356 /**
8357  * Parse an extension expression.
8358  */
8359 static expression_t *parse_extension(void)
8360 {
8361         eat(T___extension__);
8362
8363         bool old_gcc_extension   = in_gcc_extension;
8364         in_gcc_extension         = true;
8365         expression_t *expression = parse_sub_expression(PREC_UNARY);
8366         in_gcc_extension         = old_gcc_extension;
8367         return expression;
8368 }
8369
8370 /**
8371  * Parse a __builtin_classify_type() expression.
8372  */
8373 static expression_t *parse_builtin_classify_type(void)
8374 {
8375         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8376         result->base.type    = type_int;
8377
8378         eat(T___builtin_classify_type);
8379
8380         expect('(', end_error);
8381         add_anchor_token(')');
8382         expression_t *expression = parse_expression();
8383         rem_anchor_token(')');
8384         expect(')', end_error);
8385         result->classify_type.type_expression = expression;
8386
8387         return result;
8388 end_error:
8389         return create_invalid_expression();
8390 }
8391
8392 /**
8393  * Parse a delete expression
8394  * ISO/IEC 14882:1998(E) Â§5.3.5
8395  */
8396 static expression_t *parse_delete(void)
8397 {
8398         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8399         result->base.type          = type_void;
8400
8401         eat(T_delete);
8402
8403         if (token.type == '[') {
8404                 next_token();
8405                 result->kind = EXPR_UNARY_DELETE_ARRAY;
8406                 expect(']', end_error);
8407 end_error:;
8408         }
8409
8410         expression_t *const value = parse_sub_expression(PREC_CAST);
8411         result->unary.value = value;
8412
8413         type_t *const type = skip_typeref(value->base.type);
8414         if (!is_type_pointer(type)) {
8415                 errorf(&value->base.source_position,
8416                                 "operand of delete must have pointer type");
8417         } else if (warning.other &&
8418                         is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8419                 warningf(&value->base.source_position,
8420                                 "deleting 'void*' is undefined");
8421         }
8422
8423         return result;
8424 }
8425
8426 /**
8427  * Parse a throw expression
8428  * ISO/IEC 14882:1998(E) Â§15:1
8429  */
8430 static expression_t *parse_throw(void)
8431 {
8432         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8433         result->base.type          = type_void;
8434
8435         eat(T_throw);
8436
8437         expression_t *value = NULL;
8438         switch (token.type) {
8439                 EXPRESSION_START {
8440                         value = parse_assignment_expression();
8441                         /* ISO/IEC 14882:1998(E) Â§15.1:3 */
8442                         type_t *const orig_type = value->base.type;
8443                         type_t *const type      = skip_typeref(orig_type);
8444                         if (is_type_incomplete(type)) {
8445                                 errorf(&value->base.source_position,
8446                                                 "cannot throw object of incomplete type '%T'", orig_type);
8447                         } else if (is_type_pointer(type)) {
8448                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
8449                                 if (is_type_incomplete(points_to) &&
8450                                                 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8451                                         errorf(&value->base.source_position,
8452                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
8453                                 }
8454                         }
8455                 }
8456
8457                 default:
8458                         break;
8459         }
8460         result->unary.value = value;
8461
8462         return result;
8463 }
8464
8465 static bool check_pointer_arithmetic(const source_position_t *source_position,
8466                                      type_t *pointer_type,
8467                                      type_t *orig_pointer_type)
8468 {
8469         type_t *points_to = pointer_type->pointer.points_to;
8470         points_to = skip_typeref(points_to);
8471
8472         if (is_type_incomplete(points_to)) {
8473                 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8474                         errorf(source_position,
8475                                "arithmetic with pointer to incomplete type '%T' not allowed",
8476                                orig_pointer_type);
8477                         return false;
8478                 } else if (warning.pointer_arith) {
8479                         warningf(source_position,
8480                                  "pointer of type '%T' used in arithmetic",
8481                                  orig_pointer_type);
8482                 }
8483         } else if (is_type_function(points_to)) {
8484                 if (!GNU_MODE) {
8485                         errorf(source_position,
8486                                "arithmetic with pointer to function type '%T' not allowed",
8487                                orig_pointer_type);
8488                         return false;
8489                 } else if (warning.pointer_arith) {
8490                         warningf(source_position,
8491                                  "pointer to a function '%T' used in arithmetic",
8492                                  orig_pointer_type);
8493                 }
8494         }
8495         return true;
8496 }
8497
8498 static bool is_lvalue(const expression_t *expression)
8499 {
8500         /* TODO: doesn't seem to be consistent with Â§6.3.2.1 (1) */
8501         switch (expression->kind) {
8502         case EXPR_ARRAY_ACCESS:
8503         case EXPR_COMPOUND_LITERAL:
8504         case EXPR_REFERENCE:
8505         case EXPR_SELECT:
8506         case EXPR_UNARY_DEREFERENCE:
8507                 return true;
8508
8509         default: {
8510           type_t *type = skip_typeref(expression->base.type);
8511           return
8512                 /* ISO/IEC 14882:1998(E) Â§3.10:3 */
8513                 is_type_reference(type) ||
8514                 /* Claim it is an lvalue, if the type is invalid.  There was a parse
8515                  * error before, which maybe prevented properly recognizing it as
8516                  * lvalue. */
8517                 !is_type_valid(type);
8518         }
8519         }
8520 }
8521
8522 static void semantic_incdec(unary_expression_t *expression)
8523 {
8524         type_t *const orig_type = expression->value->base.type;
8525         type_t *const type      = skip_typeref(orig_type);
8526         if (is_type_pointer(type)) {
8527                 if (!check_pointer_arithmetic(&expression->base.source_position,
8528                                               type, orig_type)) {
8529                         return;
8530                 }
8531         } else if (!is_type_real(type) && is_type_valid(type)) {
8532                 /* TODO: improve error message */
8533                 errorf(&expression->base.source_position,
8534                        "operation needs an arithmetic or pointer type");
8535                 return;
8536         }
8537         if (!is_lvalue(expression->value)) {
8538                 /* TODO: improve error message */
8539                 errorf(&expression->base.source_position, "lvalue required as operand");
8540         }
8541         expression->base.type = orig_type;
8542 }
8543
8544 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8545 {
8546         type_t *const orig_type = expression->value->base.type;
8547         type_t *const type      = skip_typeref(orig_type);
8548         if (!is_type_arithmetic(type)) {
8549                 if (is_type_valid(type)) {
8550                         /* TODO: improve error message */
8551                         errorf(&expression->base.source_position,
8552                                 "operation needs an arithmetic type");
8553                 }
8554                 return;
8555         }
8556
8557         expression->base.type = orig_type;
8558 }
8559
8560 static void semantic_unexpr_plus(unary_expression_t *expression)
8561 {
8562         semantic_unexpr_arithmetic(expression);
8563         if (warning.traditional)
8564                 warningf(&expression->base.source_position,
8565                         "traditional C rejects the unary plus operator");
8566 }
8567
8568 static void semantic_not(unary_expression_t *expression)
8569 {
8570         /* Â§6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
8571         semantic_condition(expression->value, "operand of !");
8572         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8573 }
8574
8575 static void semantic_unexpr_integer(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_integer(type)) {
8580                 if (is_type_valid(type)) {
8581                         errorf(&expression->base.source_position,
8582                                "operand of ~ must be of integer type");
8583                 }
8584                 return;
8585         }
8586
8587         expression->base.type = orig_type;
8588 }
8589
8590 static void semantic_dereference(unary_expression_t *expression)
8591 {
8592         type_t *const orig_type = expression->value->base.type;
8593         type_t *const type      = skip_typeref(orig_type);
8594         if (!is_type_pointer(type)) {
8595                 if (is_type_valid(type)) {
8596                         errorf(&expression->base.source_position,
8597                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8598                 }
8599                 return;
8600         }
8601
8602         type_t *result_type   = type->pointer.points_to;
8603         result_type           = automatic_type_conversion(result_type);
8604         expression->base.type = result_type;
8605 }
8606
8607 /**
8608  * Record that an address is taken (expression represents an lvalue).
8609  *
8610  * @param expression       the expression
8611  * @param may_be_register  if true, the expression might be an register
8612  */
8613 static void set_address_taken(expression_t *expression, bool may_be_register)
8614 {
8615         if (expression->kind != EXPR_REFERENCE)
8616                 return;
8617
8618         entity_t *const entity = expression->reference.entity;
8619
8620         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8621                 return;
8622
8623         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8624                         && !may_be_register) {
8625                 errorf(&expression->base.source_position,
8626                                 "address of register %s '%Y' requested",
8627                                 get_entity_kind_name(entity->kind),     entity->base.symbol);
8628         }
8629
8630         if (entity->kind == ENTITY_VARIABLE) {
8631                 entity->variable.address_taken = true;
8632         } else {
8633                 assert(entity->kind == ENTITY_PARAMETER);
8634                 entity->parameter.address_taken = true;
8635         }
8636 }
8637
8638 /**
8639  * Check the semantic of the address taken expression.
8640  */
8641 static void semantic_take_addr(unary_expression_t *expression)
8642 {
8643         expression_t *value = expression->value;
8644         value->base.type    = revert_automatic_type_conversion(value);
8645
8646         type_t *orig_type = value->base.type;
8647         type_t *type      = skip_typeref(orig_type);
8648         if (!is_type_valid(type))
8649                 return;
8650
8651         /* Â§6.5.3.2 */
8652         if (!is_lvalue(value)) {
8653                 errorf(&expression->base.source_position, "'&' requires an lvalue");
8654         }
8655         if (type->kind == TYPE_BITFIELD) {
8656                 errorf(&expression->base.source_position,
8657                        "'&' not allowed on object with bitfield type '%T'",
8658                        type);
8659         }
8660
8661         set_address_taken(value, false);
8662
8663         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8664 }
8665
8666 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8667 static expression_t *parse_##unexpression_type(void)                         \
8668 {                                                                            \
8669         expression_t *unary_expression                                           \
8670                 = allocate_expression_zero(unexpression_type);                       \
8671         eat(token_type);                                                         \
8672         unary_expression->unary.value = parse_sub_expression(PREC_UNARY);        \
8673                                                                                  \
8674         sfunc(&unary_expression->unary);                                         \
8675                                                                                  \
8676         return unary_expression;                                                 \
8677 }
8678
8679 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8680                                semantic_unexpr_arithmetic)
8681 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8682                                semantic_unexpr_plus)
8683 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8684                                semantic_not)
8685 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8686                                semantic_dereference)
8687 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8688                                semantic_take_addr)
8689 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8690                                semantic_unexpr_integer)
8691 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
8692                                semantic_incdec)
8693 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8694                                semantic_incdec)
8695
8696 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8697                                                sfunc)                         \
8698 static expression_t *parse_##unexpression_type(expression_t *left)            \
8699 {                                                                             \
8700         expression_t *unary_expression                                            \
8701                 = allocate_expression_zero(unexpression_type);                        \
8702         eat(token_type);                                                          \
8703         unary_expression->unary.value = left;                                     \
8704                                                                                   \
8705         sfunc(&unary_expression->unary);                                          \
8706                                                                               \
8707         return unary_expression;                                                  \
8708 }
8709
8710 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8711                                        EXPR_UNARY_POSTFIX_INCREMENT,
8712                                        semantic_incdec)
8713 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8714                                        EXPR_UNARY_POSTFIX_DECREMENT,
8715                                        semantic_incdec)
8716
8717 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8718 {
8719         /* TODO: handle complex + imaginary types */
8720
8721         type_left  = get_unqualified_type(type_left);
8722         type_right = get_unqualified_type(type_right);
8723
8724         /* Â§ 6.3.1.8 Usual arithmetic conversions */
8725         if (type_left == type_long_double || type_right == type_long_double) {
8726                 return type_long_double;
8727         } else if (type_left == type_double || type_right == type_double) {
8728                 return type_double;
8729         } else if (type_left == type_float || type_right == type_float) {
8730                 return type_float;
8731         }
8732
8733         type_left  = promote_integer(type_left);
8734         type_right = promote_integer(type_right);
8735
8736         if (type_left == type_right)
8737                 return type_left;
8738
8739         bool const signed_left  = is_type_signed(type_left);
8740         bool const signed_right = is_type_signed(type_right);
8741         int const  rank_left    = get_rank(type_left);
8742         int const  rank_right   = get_rank(type_right);
8743
8744         if (signed_left == signed_right)
8745                 return rank_left >= rank_right ? type_left : type_right;
8746
8747         int     s_rank;
8748         int     u_rank;
8749         type_t *s_type;
8750         type_t *u_type;
8751         if (signed_left) {
8752                 s_rank = rank_left;
8753                 s_type = type_left;
8754                 u_rank = rank_right;
8755                 u_type = type_right;
8756         } else {
8757                 s_rank = rank_right;
8758                 s_type = type_right;
8759                 u_rank = rank_left;
8760                 u_type = type_left;
8761         }
8762
8763         if (u_rank >= s_rank)
8764                 return u_type;
8765
8766         /* casting rank to atomic_type_kind is a bit hacky, but makes things
8767          * easier here... */
8768         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8769                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
8770                 return s_type;
8771
8772         switch (s_rank) {
8773                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
8774                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
8775                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8776
8777                 default: panic("invalid atomic type");
8778         }
8779 }
8780
8781 /**
8782  * Check the semantic restrictions for a binary expression.
8783  */
8784 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8785 {
8786         expression_t *const left            = expression->left;
8787         expression_t *const right           = expression->right;
8788         type_t       *const orig_type_left  = left->base.type;
8789         type_t       *const orig_type_right = right->base.type;
8790         type_t       *const type_left       = skip_typeref(orig_type_left);
8791         type_t       *const type_right      = skip_typeref(orig_type_right);
8792
8793         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8794                 /* TODO: improve error message */
8795                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8796                         errorf(&expression->base.source_position,
8797                                "operation needs arithmetic types");
8798                 }
8799                 return;
8800         }
8801
8802         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8803         expression->left      = create_implicit_cast(left, arithmetic_type);
8804         expression->right     = create_implicit_cast(right, arithmetic_type);
8805         expression->base.type = arithmetic_type;
8806 }
8807
8808 static void warn_div_by_zero(binary_expression_t const *const expression)
8809 {
8810         if (!warning.div_by_zero ||
8811             !is_type_integer(expression->base.type))
8812                 return;
8813
8814         expression_t const *const right = expression->right;
8815         /* The type of the right operand can be different for /= */
8816         if (is_type_integer(right->base.type) &&
8817             is_constant_expression(right)     &&
8818             fold_constant(right) == 0) {
8819                 warningf(&expression->base.source_position, "division by zero");
8820         }
8821 }
8822
8823 /**
8824  * Check the semantic restrictions for a div/mod expression.
8825  */
8826 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8827         semantic_binexpr_arithmetic(expression);
8828         warn_div_by_zero(expression);
8829 }
8830
8831 static void semantic_shift_op(binary_expression_t *expression)
8832 {
8833         expression_t *const left            = expression->left;
8834         expression_t *const right           = expression->right;
8835         type_t       *const orig_type_left  = left->base.type;
8836         type_t       *const orig_type_right = right->base.type;
8837         type_t       *      type_left       = skip_typeref(orig_type_left);
8838         type_t       *      type_right      = skip_typeref(orig_type_right);
8839
8840         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8841                 /* TODO: improve error message */
8842                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8843                         errorf(&expression->base.source_position,
8844                                "operands of shift operation must have integer types");
8845                 }
8846                 return;
8847         }
8848
8849         type_left  = promote_integer(type_left);
8850         type_right = promote_integer(type_right);
8851
8852         expression->left      = create_implicit_cast(left, type_left);
8853         expression->right     = create_implicit_cast(right, type_right);
8854         expression->base.type = type_left;
8855 }
8856
8857 static void semantic_add(binary_expression_t *expression)
8858 {
8859         expression_t *const left            = expression->left;
8860         expression_t *const right           = expression->right;
8861         type_t       *const orig_type_left  = left->base.type;
8862         type_t       *const orig_type_right = right->base.type;
8863         type_t       *const type_left       = skip_typeref(orig_type_left);
8864         type_t       *const type_right      = skip_typeref(orig_type_right);
8865
8866         /* Â§ 6.5.6 */
8867         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8868                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8869                 expression->left  = create_implicit_cast(left, arithmetic_type);
8870                 expression->right = create_implicit_cast(right, arithmetic_type);
8871                 expression->base.type = arithmetic_type;
8872                 return;
8873         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8874                 check_pointer_arithmetic(&expression->base.source_position,
8875                                          type_left, orig_type_left);
8876                 expression->base.type = type_left;
8877         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8878                 check_pointer_arithmetic(&expression->base.source_position,
8879                                          type_right, orig_type_right);
8880                 expression->base.type = type_right;
8881         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8882                 errorf(&expression->base.source_position,
8883                        "invalid operands to binary + ('%T', '%T')",
8884                        orig_type_left, orig_type_right);
8885         }
8886 }
8887
8888 static void semantic_sub(binary_expression_t *expression)
8889 {
8890         expression_t            *const left            = expression->left;
8891         expression_t            *const right           = expression->right;
8892         type_t                  *const orig_type_left  = left->base.type;
8893         type_t                  *const orig_type_right = right->base.type;
8894         type_t                  *const type_left       = skip_typeref(orig_type_left);
8895         type_t                  *const type_right      = skip_typeref(orig_type_right);
8896         source_position_t const *const pos             = &expression->base.source_position;
8897
8898         /* Â§ 5.6.5 */
8899         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8900                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8901                 expression->left        = create_implicit_cast(left, arithmetic_type);
8902                 expression->right       = create_implicit_cast(right, arithmetic_type);
8903                 expression->base.type =  arithmetic_type;
8904                 return;
8905         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8906                 check_pointer_arithmetic(&expression->base.source_position,
8907                                          type_left, orig_type_left);
8908                 expression->base.type = type_left;
8909         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8910                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8911                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8912                 if (!types_compatible(unqual_left, unqual_right)) {
8913                         errorf(pos,
8914                                "subtracting pointers to incompatible types '%T' and '%T'",
8915                                orig_type_left, orig_type_right);
8916                 } else if (!is_type_object(unqual_left)) {
8917                         if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8918                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8919                                        orig_type_left);
8920                         } else if (warning.other) {
8921                                 warningf(pos, "subtracting pointers to void");
8922                         }
8923                 }
8924                 expression->base.type = type_ptrdiff_t;
8925         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8926                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8927                        orig_type_left, orig_type_right);
8928         }
8929 }
8930
8931 static void warn_string_literal_address(expression_t const* expr)
8932 {
8933         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8934                 expr = expr->unary.value;
8935                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8936                         return;
8937                 expr = expr->unary.value;
8938         }
8939
8940         if (expr->kind == EXPR_STRING_LITERAL ||
8941             expr->kind == EXPR_WIDE_STRING_LITERAL) {
8942                 warningf(&expr->base.source_position,
8943                         "comparison with string literal results in unspecified behaviour");
8944         }
8945 }
8946
8947 static void warn_comparison_in_comparison(const expression_t *const expr)
8948 {
8949         if (expr->base.parenthesized)
8950                 return;
8951         switch (expr->base.kind) {
8952                 case EXPR_BINARY_LESS:
8953                 case EXPR_BINARY_GREATER:
8954                 case EXPR_BINARY_LESSEQUAL:
8955                 case EXPR_BINARY_GREATEREQUAL:
8956                 case EXPR_BINARY_NOTEQUAL:
8957                 case EXPR_BINARY_EQUAL:
8958                         warningf(&expr->base.source_position,
8959                                         "comparisons like 'x <= y < z' do not have their mathematical meaning");
8960                         break;
8961                 default:
8962                         break;
8963         }
8964 }
8965
8966 /**
8967  * Check the semantics of comparison expressions.
8968  *
8969  * @param expression   The expression to check.
8970  */
8971 static void semantic_comparison(binary_expression_t *expression)
8972 {
8973         expression_t *left  = expression->left;
8974         expression_t *right = expression->right;
8975
8976         if (warning.address) {
8977                 warn_string_literal_address(left);
8978                 warn_string_literal_address(right);
8979
8980                 expression_t const* const func_left = get_reference_address(left);
8981                 if (func_left != NULL && is_null_pointer_constant(right)) {
8982                         warningf(&expression->base.source_position,
8983                                  "the address of '%Y' will never be NULL",
8984                                  func_left->reference.entity->base.symbol);
8985                 }
8986
8987                 expression_t const* const func_right = get_reference_address(right);
8988                 if (func_right != NULL && is_null_pointer_constant(right)) {
8989                         warningf(&expression->base.source_position,
8990                                  "the address of '%Y' will never be NULL",
8991                                  func_right->reference.entity->base.symbol);
8992                 }
8993         }
8994
8995         if (warning.parentheses) {
8996                 warn_comparison_in_comparison(left);
8997                 warn_comparison_in_comparison(right);
8998         }
8999
9000         type_t *orig_type_left  = left->base.type;
9001         type_t *orig_type_right = right->base.type;
9002         type_t *type_left       = skip_typeref(orig_type_left);
9003         type_t *type_right      = skip_typeref(orig_type_right);
9004
9005         /* TODO non-arithmetic types */
9006         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9007                 /* test for signed vs unsigned compares */
9008                 if (warning.sign_compare &&
9009                     (expression->base.kind != EXPR_BINARY_EQUAL &&
9010                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
9011                     (is_type_signed(type_left) != is_type_signed(type_right))) {
9012
9013                         /* check if 1 of the operands is a constant, in this case we just
9014                          * check wether we can safely represent the resulting constant in
9015                          * the type of the other operand. */
9016                         expression_t *const_expr = NULL;
9017                         expression_t *other_expr = NULL;
9018
9019                         if (is_constant_expression(left)) {
9020                                 const_expr = left;
9021                                 other_expr = right;
9022                         } else if (is_constant_expression(right)) {
9023                                 const_expr = right;
9024                                 other_expr = left;
9025                         }
9026
9027                         if (const_expr != NULL) {
9028                                 type_t *other_type = skip_typeref(other_expr->base.type);
9029                                 long    val        = fold_constant(const_expr);
9030                                 /* TODO: check if val can be represented by other_type */
9031                                 (void) other_type;
9032                                 (void) val;
9033                         }
9034                         warningf(&expression->base.source_position,
9035                                  "comparison between signed and unsigned");
9036                 }
9037                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9038                 expression->left        = create_implicit_cast(left, arithmetic_type);
9039                 expression->right       = create_implicit_cast(right, arithmetic_type);
9040                 expression->base.type   = arithmetic_type;
9041                 if (warning.float_equal &&
9042                     (expression->base.kind == EXPR_BINARY_EQUAL ||
9043                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9044                     is_type_float(arithmetic_type)) {
9045                         warningf(&expression->base.source_position,
9046                                  "comparing floating point with == or != is unsafe");
9047                 }
9048         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9049                 /* TODO check compatibility */
9050         } else if (is_type_pointer(type_left)) {
9051                 expression->right = create_implicit_cast(right, type_left);
9052         } else if (is_type_pointer(type_right)) {
9053                 expression->left = create_implicit_cast(left, type_right);
9054         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9055                 type_error_incompatible("invalid operands in comparison",
9056                                         &expression->base.source_position,
9057                                         type_left, type_right);
9058         }
9059         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9060 }
9061
9062 /**
9063  * Checks if a compound type has constant fields.
9064  */
9065 static bool has_const_fields(const compound_type_t *type)
9066 {
9067         compound_t *compound = type->compound;
9068         entity_t   *entry    = compound->members.entities;
9069
9070         for (; entry != NULL; entry = entry->base.next) {
9071                 if (!is_declaration(entry))
9072                         continue;
9073
9074                 const type_t *decl_type = skip_typeref(entry->declaration.type);
9075                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9076                         return true;
9077         }
9078
9079         return false;
9080 }
9081
9082 static bool is_valid_assignment_lhs(expression_t const* const left)
9083 {
9084         type_t *const orig_type_left = revert_automatic_type_conversion(left);
9085         type_t *const type_left      = skip_typeref(orig_type_left);
9086
9087         if (!is_lvalue(left)) {
9088                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9089                        left);
9090                 return false;
9091         }
9092
9093         if (left->kind == EXPR_REFERENCE
9094                         && left->reference.entity->kind == ENTITY_FUNCTION) {
9095                 errorf(HERE, "cannot assign to function '%E'", left);
9096                 return false;
9097         }
9098
9099         if (is_type_array(type_left)) {
9100                 errorf(HERE, "cannot assign to array '%E'", left);
9101                 return false;
9102         }
9103         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9104                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9105                        orig_type_left);
9106                 return false;
9107         }
9108         if (is_type_incomplete(type_left)) {
9109                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9110                        left, orig_type_left);
9111                 return false;
9112         }
9113         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9114                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9115                        left, orig_type_left);
9116                 return false;
9117         }
9118
9119         return true;
9120 }
9121
9122 static void semantic_arithmetic_assign(binary_expression_t *expression)
9123 {
9124         expression_t *left            = expression->left;
9125         expression_t *right           = expression->right;
9126         type_t       *orig_type_left  = left->base.type;
9127         type_t       *orig_type_right = right->base.type;
9128
9129         if (!is_valid_assignment_lhs(left))
9130                 return;
9131
9132         type_t *type_left  = skip_typeref(orig_type_left);
9133         type_t *type_right = skip_typeref(orig_type_right);
9134
9135         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9136                 /* TODO: improve error message */
9137                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9138                         errorf(&expression->base.source_position,
9139                                "operation needs arithmetic types");
9140                 }
9141                 return;
9142         }
9143
9144         /* combined instructions are tricky. We can't create an implicit cast on
9145          * the left side, because we need the uncasted form for the store.
9146          * The ast2firm pass has to know that left_type must be right_type
9147          * for the arithmetic operation and create a cast by itself */
9148         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9149         expression->right       = create_implicit_cast(right, arithmetic_type);
9150         expression->base.type   = type_left;
9151 }
9152
9153 static void semantic_divmod_assign(binary_expression_t *expression)
9154 {
9155         semantic_arithmetic_assign(expression);
9156         warn_div_by_zero(expression);
9157 }
9158
9159 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9160 {
9161         expression_t *const left            = expression->left;
9162         expression_t *const right           = expression->right;
9163         type_t       *const orig_type_left  = left->base.type;
9164         type_t       *const orig_type_right = right->base.type;
9165         type_t       *const type_left       = skip_typeref(orig_type_left);
9166         type_t       *const type_right      = skip_typeref(orig_type_right);
9167
9168         if (!is_valid_assignment_lhs(left))
9169                 return;
9170
9171         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9172                 /* combined instructions are tricky. We can't create an implicit cast on
9173                  * the left side, because we need the uncasted form for the store.
9174                  * The ast2firm pass has to know that left_type must be right_type
9175                  * for the arithmetic operation and create a cast by itself */
9176                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9177                 expression->right     = create_implicit_cast(right, arithmetic_type);
9178                 expression->base.type = type_left;
9179         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9180                 check_pointer_arithmetic(&expression->base.source_position,
9181                                          type_left, orig_type_left);
9182                 expression->base.type = type_left;
9183         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9184                 errorf(&expression->base.source_position,
9185                        "incompatible types '%T' and '%T' in assignment",
9186                        orig_type_left, orig_type_right);
9187         }
9188 }
9189
9190 static void warn_logical_and_within_or(const expression_t *const expr)
9191 {
9192         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9193                 return;
9194         if (expr->base.parenthesized)
9195                 return;
9196         warningf(&expr->base.source_position,
9197                         "suggest parentheses around && within ||");
9198 }
9199
9200 /**
9201  * Check the semantic restrictions of a logical expression.
9202  */
9203 static void semantic_logical_op(binary_expression_t *expression)
9204 {
9205         /* Â§6.5.13:2  Each of the operands shall have scalar type.
9206          * Â§6.5.14:2  Each of the operands shall have scalar type. */
9207         semantic_condition(expression->left,   "left operand of logical operator");
9208         semantic_condition(expression->right, "right operand of logical operator");
9209         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9210                         warning.parentheses) {
9211                 warn_logical_and_within_or(expression->left);
9212                 warn_logical_and_within_or(expression->right);
9213         }
9214         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9215 }
9216
9217 /**
9218  * Check the semantic restrictions of a binary assign expression.
9219  */
9220 static void semantic_binexpr_assign(binary_expression_t *expression)
9221 {
9222         expression_t *left           = expression->left;
9223         type_t       *orig_type_left = left->base.type;
9224
9225         if (!is_valid_assignment_lhs(left))
9226                 return;
9227
9228         assign_error_t error = semantic_assign(orig_type_left, expression->right);
9229         report_assign_error(error, orig_type_left, expression->right,
9230                         "assignment", &left->base.source_position);
9231         expression->right = create_implicit_cast(expression->right, orig_type_left);
9232         expression->base.type = orig_type_left;
9233 }
9234
9235 /**
9236  * Determine if the outermost operation (or parts thereof) of the given
9237  * expression has no effect in order to generate a warning about this fact.
9238  * Therefore in some cases this only examines some of the operands of the
9239  * expression (see comments in the function and examples below).
9240  * Examples:
9241  *   f() + 23;    // warning, because + has no effect
9242  *   x || f();    // no warning, because x controls execution of f()
9243  *   x ? y : f(); // warning, because y has no effect
9244  *   (void)x;     // no warning to be able to suppress the warning
9245  * This function can NOT be used for an "expression has definitely no effect"-
9246  * analysis. */
9247 static bool expression_has_effect(const expression_t *const expr)
9248 {
9249         switch (expr->kind) {
9250                 case EXPR_UNKNOWN:                   break;
9251                 case EXPR_INVALID:                   return true; /* do NOT warn */
9252                 case EXPR_REFERENCE:                 return false;
9253                 case EXPR_REFERENCE_ENUM_VALUE:      return false;
9254                 /* suppress the warning for microsoft __noop operations */
9255                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
9256                 case EXPR_CHARACTER_CONSTANT:        return false;
9257                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
9258                 case EXPR_STRING_LITERAL:            return false;
9259                 case EXPR_WIDE_STRING_LITERAL:       return false;
9260                 case EXPR_LABEL_ADDRESS:             return false;
9261
9262                 case EXPR_CALL: {
9263                         const call_expression_t *const call = &expr->call;
9264                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9265                                 return true;
9266
9267                         switch (call->function->builtin_symbol.symbol->ID) {
9268                                 case T___builtin_va_end: return true;
9269                                 default:                 return false;
9270                         }
9271                 }
9272
9273                 /* Generate the warning if either the left or right hand side of a
9274                  * conditional expression has no effect */
9275                 case EXPR_CONDITIONAL: {
9276                         const conditional_expression_t *const cond = &expr->conditional;
9277                         return
9278                                 expression_has_effect(cond->true_expression) &&
9279                                 expression_has_effect(cond->false_expression);
9280                 }
9281
9282                 case EXPR_SELECT:                    return false;
9283                 case EXPR_ARRAY_ACCESS:              return false;
9284                 case EXPR_SIZEOF:                    return false;
9285                 case EXPR_CLASSIFY_TYPE:             return false;
9286                 case EXPR_ALIGNOF:                   return false;
9287
9288                 case EXPR_FUNCNAME:                  return false;
9289                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
9290                 case EXPR_BUILTIN_CONSTANT_P:        return false;
9291                 case EXPR_BUILTIN_PREFETCH:          return true;
9292                 case EXPR_OFFSETOF:                  return false;
9293                 case EXPR_VA_START:                  return true;
9294                 case EXPR_VA_ARG:                    return true;
9295                 case EXPR_STATEMENT:                 return true; // TODO
9296                 case EXPR_COMPOUND_LITERAL:          return false;
9297
9298                 case EXPR_UNARY_NEGATE:              return false;
9299                 case EXPR_UNARY_PLUS:                return false;
9300                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
9301                 case EXPR_UNARY_NOT:                 return false;
9302                 case EXPR_UNARY_DEREFERENCE:         return false;
9303                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
9304                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
9305                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
9306                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
9307                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
9308
9309                 /* Treat void casts as if they have an effect in order to being able to
9310                  * suppress the warning */
9311                 case EXPR_UNARY_CAST: {
9312                         type_t *const type = skip_typeref(expr->base.type);
9313                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
9314                 }
9315
9316                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
9317                 case EXPR_UNARY_ASSUME:              return true;
9318                 case EXPR_UNARY_DELETE:              return true;
9319                 case EXPR_UNARY_DELETE_ARRAY:        return true;
9320                 case EXPR_UNARY_THROW:               return true;
9321
9322                 case EXPR_BINARY_ADD:                return false;
9323                 case EXPR_BINARY_SUB:                return false;
9324                 case EXPR_BINARY_MUL:                return false;
9325                 case EXPR_BINARY_DIV:                return false;
9326                 case EXPR_BINARY_MOD:                return false;
9327                 case EXPR_BINARY_EQUAL:              return false;
9328                 case EXPR_BINARY_NOTEQUAL:           return false;
9329                 case EXPR_BINARY_LESS:               return false;
9330                 case EXPR_BINARY_LESSEQUAL:          return false;
9331                 case EXPR_BINARY_GREATER:            return false;
9332                 case EXPR_BINARY_GREATEREQUAL:       return false;
9333                 case EXPR_BINARY_BITWISE_AND:        return false;
9334                 case EXPR_BINARY_BITWISE_OR:         return false;
9335                 case EXPR_BINARY_BITWISE_XOR:        return false;
9336                 case EXPR_BINARY_SHIFTLEFT:          return false;
9337                 case EXPR_BINARY_SHIFTRIGHT:         return false;
9338                 case EXPR_BINARY_ASSIGN:             return true;
9339                 case EXPR_BINARY_MUL_ASSIGN:         return true;
9340                 case EXPR_BINARY_DIV_ASSIGN:         return true;
9341                 case EXPR_BINARY_MOD_ASSIGN:         return true;
9342                 case EXPR_BINARY_ADD_ASSIGN:         return true;
9343                 case EXPR_BINARY_SUB_ASSIGN:         return true;
9344                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
9345                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
9346                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9347                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9348                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
9349
9350                 /* Only examine the right hand side of && and ||, because the left hand
9351                  * side already has the effect of controlling the execution of the right
9352                  * hand side */
9353                 case EXPR_BINARY_LOGICAL_AND:
9354                 case EXPR_BINARY_LOGICAL_OR:
9355                 /* Only examine the right hand side of a comma expression, because the left
9356                  * hand side has a separate warning */
9357                 case EXPR_BINARY_COMMA:
9358                         return expression_has_effect(expr->binary.right);
9359
9360                 case EXPR_BINARY_ISGREATER:          return false;
9361                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
9362                 case EXPR_BINARY_ISLESS:             return false;
9363                 case EXPR_BINARY_ISLESSEQUAL:        return false;
9364                 case EXPR_BINARY_ISLESSGREATER:      return false;
9365                 case EXPR_BINARY_ISUNORDERED:        return false;
9366         }
9367
9368         internal_errorf(HERE, "unexpected expression");
9369 }
9370
9371 static void semantic_comma(binary_expression_t *expression)
9372 {
9373         if (warning.unused_value) {
9374                 const expression_t *const left = expression->left;
9375                 if (!expression_has_effect(left)) {
9376                         warningf(&left->base.source_position,
9377                                  "left-hand operand of comma expression has no effect");
9378                 }
9379         }
9380         expression->base.type = expression->right->base.type;
9381 }
9382
9383 /**
9384  * @param prec_r precedence of the right operand
9385  */
9386 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9387 static expression_t *parse_##binexpression_type(expression_t *left)          \
9388 {                                                                            \
9389         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
9390         binexpr->binary.left  = left;                                            \
9391         eat(token_type);                                                         \
9392                                                                              \
9393         expression_t *right = parse_sub_expression(prec_r);                      \
9394                                                                              \
9395         binexpr->binary.right = right;                                           \
9396         sfunc(&binexpr->binary);                                                 \
9397                                                                              \
9398         return binexpr;                                                          \
9399 }
9400
9401 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
9402 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
9403 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
9404 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
9405 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
9406 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
9407 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
9408 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
9409 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
9410 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
9411 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
9412 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
9413 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
9414 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_arithmetic)
9415 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_arithmetic)
9416 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_arithmetic)
9417 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
9418 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
9419 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
9420 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9421 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9422 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9423 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9424 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9425 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9426 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9427 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9428 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9429 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9430 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
9431
9432
9433 static expression_t *parse_sub_expression(precedence_t precedence)
9434 {
9435         if (token.type < 0) {
9436                 return expected_expression_error();
9437         }
9438
9439         expression_parser_function_t *parser
9440                 = &expression_parsers[token.type];
9441         source_position_t             source_position = token.source_position;
9442         expression_t                 *left;
9443
9444         if (parser->parser != NULL) {
9445                 left = parser->parser();
9446         } else {
9447                 left = parse_primary_expression();
9448         }
9449         assert(left != NULL);
9450         left->base.source_position = source_position;
9451
9452         while (true) {
9453                 if (token.type < 0) {
9454                         return expected_expression_error();
9455                 }
9456
9457                 parser = &expression_parsers[token.type];
9458                 if (parser->infix_parser == NULL)
9459                         break;
9460                 if (parser->infix_precedence < precedence)
9461                         break;
9462
9463                 left = parser->infix_parser(left);
9464
9465                 assert(left != NULL);
9466                 assert(left->kind != EXPR_UNKNOWN);
9467                 left->base.source_position = source_position;
9468         }
9469
9470         return left;
9471 }
9472
9473 /**
9474  * Parse an expression.
9475  */
9476 static expression_t *parse_expression(void)
9477 {
9478         return parse_sub_expression(PREC_EXPRESSION);
9479 }
9480
9481 /**
9482  * Register a parser for a prefix-like operator.
9483  *
9484  * @param parser      the parser function
9485  * @param token_type  the token type of the prefix token
9486  */
9487 static void register_expression_parser(parse_expression_function parser,
9488                                        int token_type)
9489 {
9490         expression_parser_function_t *entry = &expression_parsers[token_type];
9491
9492         if (entry->parser != NULL) {
9493                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9494                 panic("trying to register multiple expression parsers for a token");
9495         }
9496         entry->parser = parser;
9497 }
9498
9499 /**
9500  * Register a parser for an infix operator with given precedence.
9501  *
9502  * @param parser      the parser function
9503  * @param token_type  the token type of the infix operator
9504  * @param precedence  the precedence of the operator
9505  */
9506 static void register_infix_parser(parse_expression_infix_function parser,
9507                 int token_type, unsigned precedence)
9508 {
9509         expression_parser_function_t *entry = &expression_parsers[token_type];
9510
9511         if (entry->infix_parser != NULL) {
9512                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9513                 panic("trying to register multiple infix expression parsers for a "
9514                       "token");
9515         }
9516         entry->infix_parser     = parser;
9517         entry->infix_precedence = precedence;
9518 }
9519
9520 /**
9521  * Initialize the expression parsers.
9522  */
9523 static void init_expression_parsers(void)
9524 {
9525         memset(&expression_parsers, 0, sizeof(expression_parsers));
9526
9527         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
9528         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
9529         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
9530         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
9531         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
9532         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
9533         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
9534         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
9535         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
9536         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
9537         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
9538         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
9539         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
9540         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
9541         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
9542         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
9543         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
9544         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
9545         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9546         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
9547         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
9548         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
9549         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
9550         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
9551         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
9552         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
9553         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
9554         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
9555         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
9556         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
9557         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
9558         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
9559         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
9560         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
9561         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
9562         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
9563         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
9564
9565         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
9566         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
9567         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
9568         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
9569         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
9570         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
9571         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9572         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9573         register_expression_parser(parse_sizeof,                      T_sizeof);
9574         register_expression_parser(parse_alignof,                     T___alignof__);
9575         register_expression_parser(parse_extension,                   T___extension__);
9576         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
9577         register_expression_parser(parse_delete,                      T_delete);
9578         register_expression_parser(parse_throw,                       T_throw);
9579 }
9580
9581 /**
9582  * Parse a asm statement arguments specification.
9583  */
9584 static asm_argument_t *parse_asm_arguments(bool is_out)
9585 {
9586         asm_argument_t  *result = NULL;
9587         asm_argument_t **anchor = &result;
9588
9589         while (token.type == T_STRING_LITERAL || token.type == '[') {
9590                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9591                 memset(argument, 0, sizeof(argument[0]));
9592
9593                 if (token.type == '[') {
9594                         eat('[');
9595                         if (token.type != T_IDENTIFIER) {
9596                                 parse_error_expected("while parsing asm argument",
9597                                                      T_IDENTIFIER, NULL);
9598                                 return NULL;
9599                         }
9600                         argument->symbol = token.v.symbol;
9601
9602                         expect(']', end_error);
9603                 }
9604
9605                 argument->constraints = parse_string_literals();
9606                 expect('(', end_error);
9607                 add_anchor_token(')');
9608                 expression_t *expression = parse_expression();
9609                 rem_anchor_token(')');
9610                 if (is_out) {
9611                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
9612                          * change size or type representation (e.g. int -> long is ok, but
9613                          * int -> float is not) */
9614                         if (expression->kind == EXPR_UNARY_CAST) {
9615                                 type_t      *const type = expression->base.type;
9616                                 type_kind_t  const kind = type->kind;
9617                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9618                                         unsigned flags;
9619                                         unsigned size;
9620                                         if (kind == TYPE_ATOMIC) {
9621                                                 atomic_type_kind_t const akind = type->atomic.akind;
9622                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9623                                                 size  = get_atomic_type_size(akind);
9624                                         } else {
9625                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9626                                                 size  = get_atomic_type_size(get_intptr_kind());
9627                                         }
9628
9629                                         do {
9630                                                 expression_t *const value      = expression->unary.value;
9631                                                 type_t       *const value_type = value->base.type;
9632                                                 type_kind_t   const value_kind = value_type->kind;
9633
9634                                                 unsigned value_flags;
9635                                                 unsigned value_size;
9636                                                 if (value_kind == TYPE_ATOMIC) {
9637                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
9638                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9639                                                         value_size  = get_atomic_type_size(value_akind);
9640                                                 } else if (value_kind == TYPE_POINTER) {
9641                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9642                                                         value_size  = get_atomic_type_size(get_intptr_kind());
9643                                                 } else {
9644                                                         break;
9645                                                 }
9646
9647                                                 if (value_flags != flags || value_size != size)
9648                                                         break;
9649
9650                                                 expression = value;
9651                                         } while (expression->kind == EXPR_UNARY_CAST);
9652                                 }
9653                         }
9654
9655                         if (!is_lvalue(expression)) {
9656                                 errorf(&expression->base.source_position,
9657                                        "asm output argument is not an lvalue");
9658                         }
9659
9660                         if (argument->constraints.begin[0] == '+')
9661                                 mark_vars_read(expression, NULL);
9662                 } else {
9663                         mark_vars_read(expression, NULL);
9664                 }
9665                 argument->expression = expression;
9666                 expect(')', end_error);
9667
9668                 set_address_taken(expression, true);
9669
9670                 *anchor = argument;
9671                 anchor  = &argument->next;
9672
9673                 if (token.type != ',')
9674                         break;
9675                 eat(',');
9676         }
9677
9678         return result;
9679 end_error:
9680         return NULL;
9681 }
9682
9683 /**
9684  * Parse a asm statement clobber specification.
9685  */
9686 static asm_clobber_t *parse_asm_clobbers(void)
9687 {
9688         asm_clobber_t *result = NULL;
9689         asm_clobber_t *last   = NULL;
9690
9691         while (token.type == T_STRING_LITERAL) {
9692                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9693                 clobber->clobber       = parse_string_literals();
9694
9695                 if (last != NULL) {
9696                         last->next = clobber;
9697                 } else {
9698                         result = clobber;
9699                 }
9700                 last = clobber;
9701
9702                 if (token.type != ',')
9703                         break;
9704                 eat(',');
9705         }
9706
9707         return result;
9708 }
9709
9710 /**
9711  * Parse an asm statement.
9712  */
9713 static statement_t *parse_asm_statement(void)
9714 {
9715         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
9716         asm_statement_t *asm_statement = &statement->asms;
9717
9718         eat(T_asm);
9719
9720         if (token.type == T_volatile) {
9721                 next_token();
9722                 asm_statement->is_volatile = true;
9723         }
9724
9725         expect('(', end_error);
9726         add_anchor_token(')');
9727         add_anchor_token(':');
9728         asm_statement->asm_text = parse_string_literals();
9729
9730         if (token.type != ':') {
9731                 rem_anchor_token(':');
9732                 goto end_of_asm;
9733         }
9734         eat(':');
9735
9736         asm_statement->outputs = parse_asm_arguments(true);
9737         if (token.type != ':') {
9738                 rem_anchor_token(':');
9739                 goto end_of_asm;
9740         }
9741         eat(':');
9742
9743         asm_statement->inputs = parse_asm_arguments(false);
9744         if (token.type != ':') {
9745                 rem_anchor_token(':');
9746                 goto end_of_asm;
9747         }
9748         rem_anchor_token(':');
9749         eat(':');
9750
9751         asm_statement->clobbers = parse_asm_clobbers();
9752
9753 end_of_asm:
9754         rem_anchor_token(')');
9755         expect(')', end_error);
9756         expect(';', end_error);
9757
9758         if (asm_statement->outputs == NULL) {
9759                 /* GCC: An 'asm' instruction without any output operands will be treated
9760                  * identically to a volatile 'asm' instruction. */
9761                 asm_statement->is_volatile = true;
9762         }
9763
9764         return statement;
9765 end_error:
9766         return create_invalid_statement();
9767 }
9768
9769 /**
9770  * Parse a case statement.
9771  */
9772 static statement_t *parse_case_statement(void)
9773 {
9774         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9775         source_position_t *const pos       = &statement->base.source_position;
9776
9777         eat(T_case);
9778
9779         expression_t *const expression   = parse_expression();
9780         statement->case_label.expression = expression;
9781         if (!is_constant_expression(expression)) {
9782                 /* This check does not prevent the error message in all cases of an
9783                  * prior error while parsing the expression.  At least it catches the
9784                  * common case of a mistyped enum entry. */
9785                 if (is_type_valid(skip_typeref(expression->base.type))) {
9786                         errorf(pos, "case label does not reduce to an integer constant");
9787                 }
9788                 statement->case_label.is_bad = true;
9789         } else {
9790                 long const val = fold_constant(expression);
9791                 statement->case_label.first_case = val;
9792                 statement->case_label.last_case  = val;
9793         }
9794
9795         if (GNU_MODE) {
9796                 if (token.type == T_DOTDOTDOT) {
9797                         next_token();
9798                         expression_t *const end_range   = parse_expression();
9799                         statement->case_label.end_range = end_range;
9800                         if (!is_constant_expression(end_range)) {
9801                                 /* This check does not prevent the error message in all cases of an
9802                                  * prior error while parsing the expression.  At least it catches the
9803                                  * common case of a mistyped enum entry. */
9804                                 if (is_type_valid(skip_typeref(end_range->base.type))) {
9805                                         errorf(pos, "case range does not reduce to an integer constant");
9806                                 }
9807                                 statement->case_label.is_bad = true;
9808                         } else {
9809                                 long const val = fold_constant(end_range);
9810                                 statement->case_label.last_case = val;
9811
9812                                 if (warning.other && val < statement->case_label.first_case) {
9813                                         statement->case_label.is_empty_range = true;
9814                                         warningf(pos, "empty range specified");
9815                                 }
9816                         }
9817                 }
9818         }
9819
9820         PUSH_PARENT(statement);
9821
9822         expect(':', end_error);
9823 end_error:
9824
9825         if (current_switch != NULL) {
9826                 if (! statement->case_label.is_bad) {
9827                         /* Check for duplicate case values */
9828                         case_label_statement_t *c = &statement->case_label;
9829                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9830                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9831                                         continue;
9832
9833                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9834                                         continue;
9835
9836                                 errorf(pos, "duplicate case value (previously used %P)",
9837                                        &l->base.source_position);
9838                                 break;
9839                         }
9840                 }
9841                 /* link all cases into the switch statement */
9842                 if (current_switch->last_case == NULL) {
9843                         current_switch->first_case      = &statement->case_label;
9844                 } else {
9845                         current_switch->last_case->next = &statement->case_label;
9846                 }
9847                 current_switch->last_case = &statement->case_label;
9848         } else {
9849                 errorf(pos, "case label not within a switch statement");
9850         }
9851
9852         statement_t *const inner_stmt = parse_statement();
9853         statement->case_label.statement = inner_stmt;
9854         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9855                 errorf(&inner_stmt->base.source_position, "declaration after case label");
9856         }
9857
9858         POP_PARENT;
9859         return statement;
9860 }
9861
9862 /**
9863  * Parse a default statement.
9864  */
9865 static statement_t *parse_default_statement(void)
9866 {
9867         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9868
9869         eat(T_default);
9870
9871         PUSH_PARENT(statement);
9872
9873         expect(':', end_error);
9874         if (current_switch != NULL) {
9875                 const case_label_statement_t *def_label = current_switch->default_label;
9876                 if (def_label != NULL) {
9877                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9878                                &def_label->base.source_position);
9879                 } else {
9880                         current_switch->default_label = &statement->case_label;
9881
9882                         /* link all cases into the switch statement */
9883                         if (current_switch->last_case == NULL) {
9884                                 current_switch->first_case      = &statement->case_label;
9885                         } else {
9886                                 current_switch->last_case->next = &statement->case_label;
9887                         }
9888                         current_switch->last_case = &statement->case_label;
9889                 }
9890         } else {
9891                 errorf(&statement->base.source_position,
9892                         "'default' label not within a switch statement");
9893         }
9894
9895         statement_t *const inner_stmt = parse_statement();
9896         statement->case_label.statement = inner_stmt;
9897         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9898                 errorf(&inner_stmt->base.source_position, "declaration after default label");
9899         }
9900
9901         POP_PARENT;
9902         return statement;
9903 end_error:
9904         POP_PARENT;
9905         return create_invalid_statement();
9906 }
9907
9908 /**
9909  * Parse a label statement.
9910  */
9911 static statement_t *parse_label_statement(void)
9912 {
9913         assert(token.type == T_IDENTIFIER);
9914         symbol_t *symbol = token.v.symbol;
9915         label_t  *label  = get_label(symbol);
9916
9917         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9918         statement->label.label       = label;
9919
9920         next_token();
9921
9922         PUSH_PARENT(statement);
9923
9924         /* if statement is already set then the label is defined twice,
9925          * otherwise it was just mentioned in a goto/local label declaration so far
9926          */
9927         if (label->statement != NULL) {
9928                 errorf(HERE, "duplicate label '%Y' (declared %P)",
9929                        symbol, &label->base.source_position);
9930         } else {
9931                 label->base.source_position = token.source_position;
9932                 label->statement            = statement;
9933         }
9934
9935         eat(':');
9936
9937         if (token.type == '}') {
9938                 /* TODO only warn? */
9939                 if (warning.other && false) {
9940                         warningf(HERE, "label at end of compound statement");
9941                         statement->label.statement = create_empty_statement();
9942                 } else {
9943                         errorf(HERE, "label at end of compound statement");
9944                         statement->label.statement = create_invalid_statement();
9945                 }
9946         } else if (token.type == ';') {
9947                 /* Eat an empty statement here, to avoid the warning about an empty
9948                  * statement after a label.  label:; is commonly used to have a label
9949                  * before a closing brace. */
9950                 statement->label.statement = create_empty_statement();
9951                 next_token();
9952         } else {
9953                 statement_t *const inner_stmt = parse_statement();
9954                 statement->label.statement = inner_stmt;
9955                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9956                         errorf(&inner_stmt->base.source_position, "declaration after label");
9957                 }
9958         }
9959
9960         /* remember the labels in a list for later checking */
9961         *label_anchor = &statement->label;
9962         label_anchor  = &statement->label.next;
9963
9964         POP_PARENT;
9965         return statement;
9966 }
9967
9968 /**
9969  * Parse an if statement.
9970  */
9971 static statement_t *parse_if(void)
9972 {
9973         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9974
9975         eat(T_if);
9976
9977         PUSH_PARENT(statement);
9978
9979         add_anchor_token('{');
9980
9981         expect('(', end_error);
9982         add_anchor_token(')');
9983         expression_t *const expr = parse_expression();
9984         statement->ifs.condition = expr;
9985         /* Â§6.8.4.1:1  The controlling expression of an if statement shall have
9986          *             scalar type. */
9987         semantic_condition(expr, "condition of 'if'-statment");
9988         mark_vars_read(expr, NULL);
9989         rem_anchor_token(')');
9990         expect(')', end_error);
9991
9992 end_error:
9993         rem_anchor_token('{');
9994
9995         add_anchor_token(T_else);
9996         statement_t *const true_stmt = parse_statement();
9997         statement->ifs.true_statement = true_stmt;
9998         rem_anchor_token(T_else);
9999
10000         if (token.type == T_else) {
10001                 next_token();
10002                 statement->ifs.false_statement = parse_statement();
10003         } else if (warning.parentheses &&
10004                         true_stmt->kind == STATEMENT_IF &&
10005                         true_stmt->ifs.false_statement != NULL) {
10006                 warningf(&true_stmt->base.source_position,
10007                                 "suggest explicit braces to avoid ambiguous 'else'");
10008         }
10009
10010         POP_PARENT;
10011         return statement;
10012 }
10013
10014 /**
10015  * Check that all enums are handled in a switch.
10016  *
10017  * @param statement  the switch statement to check
10018  */
10019 static void check_enum_cases(const switch_statement_t *statement) {
10020         const type_t *type = skip_typeref(statement->expression->base.type);
10021         if (! is_type_enum(type))
10022                 return;
10023         const enum_type_t *enumt = &type->enumt;
10024
10025         /* if we have a default, no warnings */
10026         if (statement->default_label != NULL)
10027                 return;
10028
10029         /* FIXME: calculation of value should be done while parsing */
10030         /* TODO: quadratic algorithm here. Change to an n log n one */
10031         long            last_value = -1;
10032         const entity_t *entry      = enumt->enume->base.next;
10033         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10034              entry = entry->base.next) {
10035                 const expression_t *expression = entry->enum_value.value;
10036                 long                value      = expression != NULL ? fold_constant(expression) : last_value + 1;
10037                 bool                found      = false;
10038                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10039                         if (l->expression == NULL)
10040                                 continue;
10041                         if (l->first_case <= value && value <= l->last_case) {
10042                                 found = true;
10043                                 break;
10044                         }
10045                 }
10046                 if (! found) {
10047                         warningf(&statement->base.source_position,
10048                                  "enumeration value '%Y' not handled in switch",
10049                                  entry->base.symbol);
10050                 }
10051                 last_value = value;
10052         }
10053 }
10054
10055 /**
10056  * Parse a switch statement.
10057  */
10058 static statement_t *parse_switch(void)
10059 {
10060         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10061
10062         eat(T_switch);
10063
10064         PUSH_PARENT(statement);
10065
10066         expect('(', end_error);
10067         add_anchor_token(')');
10068         expression_t *const expr = parse_expression();
10069         mark_vars_read(expr, NULL);
10070         type_t       *      type = skip_typeref(expr->base.type);
10071         if (is_type_integer(type)) {
10072                 type = promote_integer(type);
10073                 if (warning.traditional) {
10074                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10075                                 warningf(&expr->base.source_position,
10076                                         "'%T' switch expression not converted to '%T' in ISO C",
10077                                         type, type_int);
10078                         }
10079                 }
10080         } else if (is_type_valid(type)) {
10081                 errorf(&expr->base.source_position,
10082                        "switch quantity is not an integer, but '%T'", type);
10083                 type = type_error_type;
10084         }
10085         statement->switchs.expression = create_implicit_cast(expr, type);
10086         expect(')', end_error);
10087         rem_anchor_token(')');
10088
10089         switch_statement_t *rem = current_switch;
10090         current_switch          = &statement->switchs;
10091         statement->switchs.body = parse_statement();
10092         current_switch          = rem;
10093
10094         if (warning.switch_default &&
10095             statement->switchs.default_label == NULL) {
10096                 warningf(&statement->base.source_position, "switch has no default case");
10097         }
10098         if (warning.switch_enum)
10099                 check_enum_cases(&statement->switchs);
10100
10101         POP_PARENT;
10102         return statement;
10103 end_error:
10104         POP_PARENT;
10105         return create_invalid_statement();
10106 }
10107
10108 static statement_t *parse_loop_body(statement_t *const loop)
10109 {
10110         statement_t *const rem = current_loop;
10111         current_loop = loop;
10112
10113         statement_t *const body = parse_statement();
10114
10115         current_loop = rem;
10116         return body;
10117 }
10118
10119 /**
10120  * Parse a while statement.
10121  */
10122 static statement_t *parse_while(void)
10123 {
10124         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10125
10126         eat(T_while);
10127
10128         PUSH_PARENT(statement);
10129
10130         expect('(', end_error);
10131         add_anchor_token(')');
10132         expression_t *const cond = parse_expression();
10133         statement->whiles.condition = cond;
10134         /* Â§6.8.5:2    The controlling expression of an iteration statement shall
10135          *             have scalar type. */
10136         semantic_condition(cond, "condition of 'while'-statement");
10137         mark_vars_read(cond, NULL);
10138         rem_anchor_token(')');
10139         expect(')', end_error);
10140
10141         statement->whiles.body = parse_loop_body(statement);
10142
10143         POP_PARENT;
10144         return statement;
10145 end_error:
10146         POP_PARENT;
10147         return create_invalid_statement();
10148 }
10149
10150 /**
10151  * Parse a do statement.
10152  */
10153 static statement_t *parse_do(void)
10154 {
10155         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10156
10157         eat(T_do);
10158
10159         PUSH_PARENT(statement);
10160
10161         add_anchor_token(T_while);
10162         statement->do_while.body = parse_loop_body(statement);
10163         rem_anchor_token(T_while);
10164
10165         expect(T_while, end_error);
10166         expect('(', end_error);
10167         add_anchor_token(')');
10168         expression_t *const cond = parse_expression();
10169         statement->do_while.condition = cond;
10170         /* Â§6.8.5:2    The controlling expression of an iteration statement shall
10171          *             have scalar type. */
10172         semantic_condition(cond, "condition of 'do-while'-statement");
10173         mark_vars_read(cond, NULL);
10174         rem_anchor_token(')');
10175         expect(')', end_error);
10176         expect(';', end_error);
10177
10178         POP_PARENT;
10179         return statement;
10180 end_error:
10181         POP_PARENT;
10182         return create_invalid_statement();
10183 }
10184
10185 /**
10186  * Parse a for statement.
10187  */
10188 static statement_t *parse_for(void)
10189 {
10190         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10191
10192         eat(T_for);
10193
10194         expect('(', end_error1);
10195         add_anchor_token(')');
10196
10197         PUSH_PARENT(statement);
10198
10199         size_t const  top       = environment_top();
10200         scope_t      *old_scope = scope_push(&statement->fors.scope);
10201
10202         if (token.type == ';') {
10203                 next_token();
10204         } else if (is_declaration_specifier(&token, false)) {
10205                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10206         } else {
10207                 add_anchor_token(';');
10208                 expression_t *const init = parse_expression();
10209                 statement->fors.initialisation = init;
10210                 mark_vars_read(init, ENT_ANY);
10211                 if (warning.unused_value && !expression_has_effect(init)) {
10212                         warningf(&init->base.source_position,
10213                                         "initialisation of 'for'-statement has no effect");
10214                 }
10215                 rem_anchor_token(';');
10216                 expect(';', end_error2);
10217         }
10218
10219         if (token.type != ';') {
10220                 add_anchor_token(';');
10221                 expression_t *const cond = parse_expression();
10222                 statement->fors.condition = cond;
10223                 /* Â§6.8.5:2    The controlling expression of an iteration statement
10224                  *             shall have scalar type. */
10225                 semantic_condition(cond, "condition of 'for'-statement");
10226                 mark_vars_read(cond, NULL);
10227                 rem_anchor_token(';');
10228         }
10229         expect(';', end_error2);
10230         if (token.type != ')') {
10231                 expression_t *const step = parse_expression();
10232                 statement->fors.step = step;
10233                 mark_vars_read(step, ENT_ANY);
10234                 if (warning.unused_value && !expression_has_effect(step)) {
10235                         warningf(&step->base.source_position,
10236                                  "step of 'for'-statement has no effect");
10237                 }
10238         }
10239         expect(')', end_error2);
10240         rem_anchor_token(')');
10241         statement->fors.body = parse_loop_body(statement);
10242
10243         assert(current_scope == &statement->fors.scope);
10244         scope_pop(old_scope);
10245         environment_pop_to(top);
10246
10247         POP_PARENT;
10248         return statement;
10249
10250 end_error2:
10251         POP_PARENT;
10252         rem_anchor_token(')');
10253         assert(current_scope == &statement->fors.scope);
10254         scope_pop(old_scope);
10255         environment_pop_to(top);
10256         /* fallthrough */
10257
10258 end_error1:
10259         return create_invalid_statement();
10260 }
10261
10262 /**
10263  * Parse a goto statement.
10264  */
10265 static statement_t *parse_goto(void)
10266 {
10267         statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10268         eat(T_goto);
10269
10270         if (GNU_MODE && token.type == '*') {
10271                 next_token();
10272                 expression_t *expression = parse_expression();
10273                 mark_vars_read(expression, NULL);
10274
10275                 /* Argh: although documentation says the expression must be of type void*,
10276                  * gcc accepts anything that can be casted into void* without error */
10277                 type_t *type = expression->base.type;
10278
10279                 if (type != type_error_type) {
10280                         if (!is_type_pointer(type) && !is_type_integer(type)) {
10281                                 errorf(&expression->base.source_position,
10282                                         "cannot convert to a pointer type");
10283                         } else if (warning.other && type != type_void_ptr) {
10284                                 warningf(&expression->base.source_position,
10285                                         "type of computed goto expression should be 'void*' not '%T'", type);
10286                         }
10287                         expression = create_implicit_cast(expression, type_void_ptr);
10288                 }
10289
10290                 statement->gotos.expression = expression;
10291         } else {
10292                 if (token.type != T_IDENTIFIER) {
10293                         if (GNU_MODE)
10294                                 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10295                         else
10296                                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10297                         eat_until_anchor();
10298                         goto end_error;
10299                 }
10300                 symbol_t *symbol = token.v.symbol;
10301                 next_token();
10302
10303                 statement->gotos.label = get_label(symbol);
10304         }
10305
10306         /* remember the goto's in a list for later checking */
10307         *goto_anchor = &statement->gotos;
10308         goto_anchor  = &statement->gotos.next;
10309
10310         expect(';', end_error);
10311
10312         return statement;
10313 end_error:
10314         return create_invalid_statement();
10315 }
10316
10317 /**
10318  * Parse a continue statement.
10319  */
10320 static statement_t *parse_continue(void)
10321 {
10322         if (current_loop == NULL) {
10323                 errorf(HERE, "continue statement not within loop");
10324         }
10325
10326         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10327
10328         eat(T_continue);
10329         expect(';', end_error);
10330
10331 end_error:
10332         return statement;
10333 }
10334
10335 /**
10336  * Parse a break statement.
10337  */
10338 static statement_t *parse_break(void)
10339 {
10340         if (current_switch == NULL && current_loop == NULL) {
10341                 errorf(HERE, "break statement not within loop or switch");
10342         }
10343
10344         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10345
10346         eat(T_break);
10347         expect(';', end_error);
10348
10349 end_error:
10350         return statement;
10351 }
10352
10353 /**
10354  * Parse a __leave statement.
10355  */
10356 static statement_t *parse_leave_statement(void)
10357 {
10358         if (current_try == NULL) {
10359                 errorf(HERE, "__leave statement not within __try");
10360         }
10361
10362         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10363
10364         eat(T___leave);
10365         expect(';', end_error);
10366
10367 end_error:
10368         return statement;
10369 }
10370
10371 /**
10372  * Check if a given entity represents a local variable.
10373  */
10374 static bool is_local_variable(const entity_t *entity)
10375 {
10376         if (entity->kind != ENTITY_VARIABLE)
10377                 return false;
10378
10379         switch ((storage_class_tag_t) entity->declaration.storage_class) {
10380         case STORAGE_CLASS_AUTO:
10381         case STORAGE_CLASS_REGISTER: {
10382                 const type_t *type = skip_typeref(entity->declaration.type);
10383                 if (is_type_function(type)) {
10384                         return false;
10385                 } else {
10386                         return true;
10387                 }
10388         }
10389         default:
10390                 return false;
10391         }
10392 }
10393
10394 /**
10395  * Check if a given expression represents a local variable.
10396  */
10397 static bool expression_is_local_variable(const expression_t *expression)
10398 {
10399         if (expression->base.kind != EXPR_REFERENCE) {
10400                 return false;
10401         }
10402         const entity_t *entity = expression->reference.entity;
10403         return is_local_variable(entity);
10404 }
10405
10406 /**
10407  * Check if a given expression represents a local variable and
10408  * return its declaration then, else return NULL.
10409  */
10410 entity_t *expression_is_variable(const expression_t *expression)
10411 {
10412         if (expression->base.kind != EXPR_REFERENCE) {
10413                 return NULL;
10414         }
10415         entity_t *entity = expression->reference.entity;
10416         if (entity->kind != ENTITY_VARIABLE)
10417                 return NULL;
10418
10419         return entity;
10420 }
10421
10422 /**
10423  * Parse a return statement.
10424  */
10425 static statement_t *parse_return(void)
10426 {
10427         eat(T_return);
10428
10429         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10430
10431         expression_t *return_value = NULL;
10432         if (token.type != ';') {
10433                 return_value = parse_expression();
10434                 mark_vars_read(return_value, NULL);
10435         }
10436
10437         const type_t *const func_type = skip_typeref(current_function->base.type);
10438         assert(is_type_function(func_type));
10439         type_t *const return_type = skip_typeref(func_type->function.return_type);
10440
10441         source_position_t const *const pos = &statement->base.source_position;
10442         if (return_value != NULL) {
10443                 type_t *return_value_type = skip_typeref(return_value->base.type);
10444
10445                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10446                         if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10447                                 /* ISO/IEC 14882:1998(E) Â§6.6.3:2 */
10448                                 /* Only warn in C mode, because GCC does the same */
10449                                 if (c_mode & _CXX || strict_mode) {
10450                                         errorf(pos,
10451                                                         "'return' with a value, in function returning 'void'");
10452                                 } else if (warning.other) {
10453                                         warningf(pos,
10454                                                         "'return' with a value, in function returning 'void'");
10455                                 }
10456                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) Â§6.6.3:3 */
10457                                 /* Only warn in C mode, because GCC does the same */
10458                                 if (strict_mode) {
10459                                         errorf(pos,
10460                                                         "'return' with expression in function return 'void'");
10461                                 } else if (warning.other) {
10462                                         warningf(pos,
10463                                                         "'return' with expression in function return 'void'");
10464                                 }
10465                         }
10466                 } else {
10467                         assign_error_t error = semantic_assign(return_type, return_value);
10468                         report_assign_error(error, return_type, return_value, "'return'",
10469                                         pos);
10470                 }
10471                 return_value = create_implicit_cast(return_value, return_type);
10472                 /* check for returning address of a local var */
10473                 if (warning.other && return_value != NULL
10474                                 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10475                         const expression_t *expression = return_value->unary.value;
10476                         if (expression_is_local_variable(expression)) {
10477                                 warningf(pos, "function returns address of local variable");
10478                         }
10479                 }
10480         } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10481                 /* ISO/IEC 14882:1998(E) Â§6.6.3:3 */
10482                 if (c_mode & _CXX || strict_mode) {
10483                         errorf(pos,
10484                                         "'return' without value, in function returning non-void");
10485                 } else {
10486                         warningf(pos,
10487                                         "'return' without value, in function returning non-void");
10488                 }
10489         }
10490         statement->returns.value = return_value;
10491
10492         expect(';', end_error);
10493
10494 end_error:
10495         return statement;
10496 }
10497
10498 /**
10499  * Parse a declaration statement.
10500  */
10501 static statement_t *parse_declaration_statement(void)
10502 {
10503         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10504
10505         entity_t *before = current_scope->last_entity;
10506         if (GNU_MODE) {
10507                 parse_external_declaration();
10508         } else {
10509                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10510         }
10511
10512         if (before == NULL) {
10513                 statement->declaration.declarations_begin = current_scope->entities;
10514         } else {
10515                 statement->declaration.declarations_begin = before->base.next;
10516         }
10517         statement->declaration.declarations_end = current_scope->last_entity;
10518
10519         return statement;
10520 }
10521
10522 /**
10523  * Parse an expression statement, ie. expr ';'.
10524  */
10525 static statement_t *parse_expression_statement(void)
10526 {
10527         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10528
10529         expression_t *const expr         = parse_expression();
10530         statement->expression.expression = expr;
10531         mark_vars_read(expr, ENT_ANY);
10532
10533         expect(';', end_error);
10534
10535 end_error:
10536         return statement;
10537 }
10538
10539 /**
10540  * Parse a microsoft __try { } __finally { } or
10541  * __try{ } __except() { }
10542  */
10543 static statement_t *parse_ms_try_statment(void)
10544 {
10545         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10546         eat(T___try);
10547
10548         PUSH_PARENT(statement);
10549
10550         ms_try_statement_t *rem = current_try;
10551         current_try = &statement->ms_try;
10552         statement->ms_try.try_statement = parse_compound_statement(false);
10553         current_try = rem;
10554
10555         POP_PARENT;
10556
10557         if (token.type == T___except) {
10558                 eat(T___except);
10559                 expect('(', end_error);
10560                 add_anchor_token(')');
10561                 expression_t *const expr = parse_expression();
10562                 mark_vars_read(expr, NULL);
10563                 type_t       *      type = skip_typeref(expr->base.type);
10564                 if (is_type_integer(type)) {
10565                         type = promote_integer(type);
10566                 } else if (is_type_valid(type)) {
10567                         errorf(&expr->base.source_position,
10568                                "__expect expression is not an integer, but '%T'", type);
10569                         type = type_error_type;
10570                 }
10571                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10572                 rem_anchor_token(')');
10573                 expect(')', end_error);
10574                 statement->ms_try.final_statement = parse_compound_statement(false);
10575         } else if (token.type == T__finally) {
10576                 eat(T___finally);
10577                 statement->ms_try.final_statement = parse_compound_statement(false);
10578         } else {
10579                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10580                 return create_invalid_statement();
10581         }
10582         return statement;
10583 end_error:
10584         return create_invalid_statement();
10585 }
10586
10587 static statement_t *parse_empty_statement(void)
10588 {
10589         if (warning.empty_statement) {
10590                 warningf(HERE, "statement is empty");
10591         }
10592         statement_t *const statement = create_empty_statement();
10593         eat(';');
10594         return statement;
10595 }
10596
10597 static statement_t *parse_local_label_declaration(void)
10598 {
10599         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10600
10601         eat(T___label__);
10602
10603         entity_t *begin = NULL, *end = NULL;
10604
10605         while (true) {
10606                 if (token.type != T_IDENTIFIER) {
10607                         parse_error_expected("while parsing local label declaration",
10608                                 T_IDENTIFIER, NULL);
10609                         goto end_error;
10610                 }
10611                 symbol_t *symbol = token.v.symbol;
10612                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10613                 if (entity != NULL && entity->base.parent_scope == current_scope) {
10614                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10615                                symbol, &entity->base.source_position);
10616                 } else {
10617                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10618
10619                         entity->base.parent_scope    = current_scope;
10620                         entity->base.namespc         = NAMESPACE_LABEL;
10621                         entity->base.source_position = token.source_position;
10622                         entity->base.symbol          = symbol;
10623
10624                         if (end != NULL)
10625                                 end->base.next = entity;
10626                         end = entity;
10627                         if (begin == NULL)
10628                                 begin = entity;
10629
10630                         environment_push(entity);
10631                 }
10632                 next_token();
10633
10634                 if (token.type != ',')
10635                         break;
10636                 next_token();
10637         }
10638         eat(';');
10639 end_error:
10640         statement->declaration.declarations_begin = begin;
10641         statement->declaration.declarations_end   = end;
10642         return statement;
10643 }
10644
10645 static void parse_namespace_definition(void)
10646 {
10647         eat(T_namespace);
10648
10649         entity_t *entity = NULL;
10650         symbol_t *symbol = NULL;
10651
10652         if (token.type == T_IDENTIFIER) {
10653                 symbol = token.v.symbol;
10654                 next_token();
10655
10656                 entity = get_entity(symbol, NAMESPACE_NORMAL);
10657                 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10658                                 && entity->base.parent_scope == current_scope) {
10659                         error_redefined_as_different_kind(&token.source_position,
10660                                                           entity, ENTITY_NAMESPACE);
10661                         entity = NULL;
10662                 }
10663         }
10664
10665         if (entity == NULL) {
10666                 entity                       = allocate_entity_zero(ENTITY_NAMESPACE);
10667                 entity->base.symbol          = symbol;
10668                 entity->base.source_position = token.source_position;
10669                 entity->base.namespc         = NAMESPACE_NORMAL;
10670                 entity->base.parent_scope    = current_scope;
10671         }
10672
10673         if (token.type == '=') {
10674                 /* TODO: parse namespace alias */
10675                 panic("namespace alias definition not supported yet");
10676         }
10677
10678         environment_push(entity);
10679         append_entity(current_scope, entity);
10680
10681         size_t const  top       = environment_top();
10682         scope_t      *old_scope = scope_push(&entity->namespacee.members);
10683
10684         expect('{', end_error);
10685         parse_externals();
10686         expect('}', end_error);
10687
10688 end_error:
10689         assert(current_scope == &entity->namespacee.members);
10690         scope_pop(old_scope);
10691         environment_pop_to(top);
10692 }
10693
10694 /**
10695  * Parse a statement.
10696  * There's also parse_statement() which additionally checks for
10697  * "statement has no effect" warnings
10698  */
10699 static statement_t *intern_parse_statement(void)
10700 {
10701         statement_t *statement = NULL;
10702
10703         /* declaration or statement */
10704         add_anchor_token(';');
10705         switch (token.type) {
10706         case T_IDENTIFIER: {
10707                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10708                 if (la1_type == ':') {
10709                         statement = parse_label_statement();
10710                 } else if (is_typedef_symbol(token.v.symbol)) {
10711                         statement = parse_declaration_statement();
10712                 } else {
10713                         /* it's an identifier, the grammar says this must be an
10714                          * expression statement. However it is common that users mistype
10715                          * declaration types, so we guess a bit here to improve robustness
10716                          * for incorrect programs */
10717                         switch (la1_type) {
10718                         case '&':
10719                         case '*':
10720                                 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10721                                         goto expression_statment;
10722                                 /* FALLTHROUGH */
10723
10724                         DECLARATION_START
10725                         case T_IDENTIFIER:
10726                                 statement = parse_declaration_statement();
10727                                 break;
10728
10729                         default:
10730 expression_statment:
10731                                 statement = parse_expression_statement();
10732                                 break;
10733                         }
10734                 }
10735                 break;
10736         }
10737
10738         case T___extension__:
10739                 /* This can be a prefix to a declaration or an expression statement.
10740                  * We simply eat it now and parse the rest with tail recursion. */
10741                 do {
10742                         next_token();
10743                 } while (token.type == T___extension__);
10744                 bool old_gcc_extension = in_gcc_extension;
10745                 in_gcc_extension       = true;
10746                 statement = intern_parse_statement();
10747                 in_gcc_extension = old_gcc_extension;
10748                 break;
10749
10750         DECLARATION_START
10751                 statement = parse_declaration_statement();
10752                 break;
10753
10754         case T___label__:
10755                 statement = parse_local_label_declaration();
10756                 break;
10757
10758         case ';':         statement = parse_empty_statement();         break;
10759         case '{':         statement = parse_compound_statement(false); break;
10760         case T___leave:   statement = parse_leave_statement();         break;
10761         case T___try:     statement = parse_ms_try_statment();         break;
10762         case T_asm:       statement = parse_asm_statement();           break;
10763         case T_break:     statement = parse_break();                   break;
10764         case T_case:      statement = parse_case_statement();          break;
10765         case T_continue:  statement = parse_continue();                break;
10766         case T_default:   statement = parse_default_statement();       break;
10767         case T_do:        statement = parse_do();                      break;
10768         case T_for:       statement = parse_for();                     break;
10769         case T_goto:      statement = parse_goto();                    break;
10770         case T_if:        statement = parse_if();                      break;
10771         case T_return:    statement = parse_return();                  break;
10772         case T_switch:    statement = parse_switch();                  break;
10773         case T_while:     statement = parse_while();                   break;
10774
10775         EXPRESSION_START
10776                 statement = parse_expression_statement();
10777                 break;
10778
10779         default:
10780                 errorf(HERE, "unexpected token %K while parsing statement", &token);
10781                 statement = create_invalid_statement();
10782                 if (!at_anchor())
10783                         next_token();
10784                 break;
10785         }
10786         rem_anchor_token(';');
10787
10788         assert(statement != NULL
10789                         && statement->base.source_position.input_name != NULL);
10790
10791         return statement;
10792 }
10793
10794 /**
10795  * parse a statement and emits "statement has no effect" warning if needed
10796  * (This is really a wrapper around intern_parse_statement with check for 1
10797  *  single warning. It is needed, because for statement expressions we have
10798  *  to avoid the warning on the last statement)
10799  */
10800 static statement_t *parse_statement(void)
10801 {
10802         statement_t *statement = intern_parse_statement();
10803
10804         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10805                 expression_t *expression = statement->expression.expression;
10806                 if (!expression_has_effect(expression)) {
10807                         warningf(&expression->base.source_position,
10808                                         "statement has no effect");
10809                 }
10810         }
10811
10812         return statement;
10813 }
10814
10815 /**
10816  * Parse a compound statement.
10817  */
10818 static statement_t *parse_compound_statement(bool inside_expression_statement)
10819 {
10820         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10821
10822         PUSH_PARENT(statement);
10823
10824         eat('{');
10825         add_anchor_token('}');
10826         /* tokens, which can start a statement */
10827         /* TODO MS, __builtin_FOO */
10828         add_anchor_token('!');
10829         add_anchor_token('&');
10830         add_anchor_token('(');
10831         add_anchor_token('*');
10832         add_anchor_token('+');
10833         add_anchor_token('-');
10834         add_anchor_token('{');
10835         add_anchor_token('~');
10836         add_anchor_token(T_CHARACTER_CONSTANT);
10837         add_anchor_token(T_COLONCOLON);
10838         add_anchor_token(T_FLOATINGPOINT);
10839         add_anchor_token(T_IDENTIFIER);
10840         add_anchor_token(T_INTEGER);
10841         add_anchor_token(T_MINUSMINUS);
10842         add_anchor_token(T_PLUSPLUS);
10843         add_anchor_token(T_STRING_LITERAL);
10844         add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10845         add_anchor_token(T_WIDE_STRING_LITERAL);
10846         add_anchor_token(T__Bool);
10847         add_anchor_token(T__Complex);
10848         add_anchor_token(T__Imaginary);
10849         add_anchor_token(T___FUNCTION__);
10850         add_anchor_token(T___PRETTY_FUNCTION__);
10851         add_anchor_token(T___alignof__);
10852         add_anchor_token(T___attribute__);
10853         add_anchor_token(T___builtin_va_start);
10854         add_anchor_token(T___extension__);
10855         add_anchor_token(T___func__);
10856         add_anchor_token(T___imag__);
10857         add_anchor_token(T___label__);
10858         add_anchor_token(T___real__);
10859         add_anchor_token(T___thread);
10860         add_anchor_token(T_asm);
10861         add_anchor_token(T_auto);
10862         add_anchor_token(T_bool);
10863         add_anchor_token(T_break);
10864         add_anchor_token(T_case);
10865         add_anchor_token(T_char);
10866         add_anchor_token(T_class);
10867         add_anchor_token(T_const);
10868         add_anchor_token(T_const_cast);
10869         add_anchor_token(T_continue);
10870         add_anchor_token(T_default);
10871         add_anchor_token(T_delete);
10872         add_anchor_token(T_double);
10873         add_anchor_token(T_do);
10874         add_anchor_token(T_dynamic_cast);
10875         add_anchor_token(T_enum);
10876         add_anchor_token(T_extern);
10877         add_anchor_token(T_false);
10878         add_anchor_token(T_float);
10879         add_anchor_token(T_for);
10880         add_anchor_token(T_goto);
10881         add_anchor_token(T_if);
10882         add_anchor_token(T_inline);
10883         add_anchor_token(T_int);
10884         add_anchor_token(T_long);
10885         add_anchor_token(T_new);
10886         add_anchor_token(T_operator);
10887         add_anchor_token(T_register);
10888         add_anchor_token(T_reinterpret_cast);
10889         add_anchor_token(T_restrict);
10890         add_anchor_token(T_return);
10891         add_anchor_token(T_short);
10892         add_anchor_token(T_signed);
10893         add_anchor_token(T_sizeof);
10894         add_anchor_token(T_static);
10895         add_anchor_token(T_static_cast);
10896         add_anchor_token(T_struct);
10897         add_anchor_token(T_switch);
10898         add_anchor_token(T_template);
10899         add_anchor_token(T_this);
10900         add_anchor_token(T_throw);
10901         add_anchor_token(T_true);
10902         add_anchor_token(T_try);
10903         add_anchor_token(T_typedef);
10904         add_anchor_token(T_typeid);
10905         add_anchor_token(T_typename);
10906         add_anchor_token(T_typeof);
10907         add_anchor_token(T_union);
10908         add_anchor_token(T_unsigned);
10909         add_anchor_token(T_using);
10910         add_anchor_token(T_void);
10911         add_anchor_token(T_volatile);
10912         add_anchor_token(T_wchar_t);
10913         add_anchor_token(T_while);
10914
10915         size_t const  top       = environment_top();
10916         scope_t      *old_scope = scope_push(&statement->compound.scope);
10917
10918         statement_t **anchor            = &statement->compound.statements;
10919         bool          only_decls_so_far = true;
10920         while (token.type != '}') {
10921                 if (token.type == T_EOF) {
10922                         errorf(&statement->base.source_position,
10923                                "EOF while parsing compound statement");
10924                         break;
10925                 }
10926                 statement_t *sub_statement = intern_parse_statement();
10927                 if (is_invalid_statement(sub_statement)) {
10928                         /* an error occurred. if we are at an anchor, return */
10929                         if (at_anchor())
10930                                 goto end_error;
10931                         continue;
10932                 }
10933
10934                 if (warning.declaration_after_statement) {
10935                         if (sub_statement->kind != STATEMENT_DECLARATION) {
10936                                 only_decls_so_far = false;
10937                         } else if (!only_decls_so_far) {
10938                                 warningf(&sub_statement->base.source_position,
10939                                          "ISO C90 forbids mixed declarations and code");
10940                         }
10941                 }
10942
10943                 *anchor = sub_statement;
10944
10945                 while (sub_statement->base.next != NULL)
10946                         sub_statement = sub_statement->base.next;
10947
10948                 anchor = &sub_statement->base.next;
10949         }
10950         next_token();
10951
10952         /* look over all statements again to produce no effect warnings */
10953         if (warning.unused_value) {
10954                 statement_t *sub_statement = statement->compound.statements;
10955                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10956                         if (sub_statement->kind != STATEMENT_EXPRESSION)
10957                                 continue;
10958                         /* don't emit a warning for the last expression in an expression
10959                          * statement as it has always an effect */
10960                         if (inside_expression_statement && sub_statement->base.next == NULL)
10961                                 continue;
10962
10963                         expression_t *expression = sub_statement->expression.expression;
10964                         if (!expression_has_effect(expression)) {
10965                                 warningf(&expression->base.source_position,
10966                                          "statement has no effect");
10967                         }
10968                 }
10969         }
10970
10971 end_error:
10972         rem_anchor_token(T_while);
10973         rem_anchor_token(T_wchar_t);
10974         rem_anchor_token(T_volatile);
10975         rem_anchor_token(T_void);
10976         rem_anchor_token(T_using);
10977         rem_anchor_token(T_unsigned);
10978         rem_anchor_token(T_union);
10979         rem_anchor_token(T_typeof);
10980         rem_anchor_token(T_typename);
10981         rem_anchor_token(T_typeid);
10982         rem_anchor_token(T_typedef);
10983         rem_anchor_token(T_try);
10984         rem_anchor_token(T_true);
10985         rem_anchor_token(T_throw);
10986         rem_anchor_token(T_this);
10987         rem_anchor_token(T_template);
10988         rem_anchor_token(T_switch);
10989         rem_anchor_token(T_struct);
10990         rem_anchor_token(T_static_cast);
10991         rem_anchor_token(T_static);
10992         rem_anchor_token(T_sizeof);
10993         rem_anchor_token(T_signed);
10994         rem_anchor_token(T_short);
10995         rem_anchor_token(T_return);
10996         rem_anchor_token(T_restrict);
10997         rem_anchor_token(T_reinterpret_cast);
10998         rem_anchor_token(T_register);
10999         rem_anchor_token(T_operator);
11000         rem_anchor_token(T_new);
11001         rem_anchor_token(T_long);
11002         rem_anchor_token(T_int);
11003         rem_anchor_token(T_inline);
11004         rem_anchor_token(T_if);
11005         rem_anchor_token(T_goto);
11006         rem_anchor_token(T_for);
11007         rem_anchor_token(T_float);
11008         rem_anchor_token(T_false);
11009         rem_anchor_token(T_extern);
11010         rem_anchor_token(T_enum);
11011         rem_anchor_token(T_dynamic_cast);
11012         rem_anchor_token(T_do);
11013         rem_anchor_token(T_double);
11014         rem_anchor_token(T_delete);
11015         rem_anchor_token(T_default);
11016         rem_anchor_token(T_continue);
11017         rem_anchor_token(T_const_cast);
11018         rem_anchor_token(T_const);
11019         rem_anchor_token(T_class);
11020         rem_anchor_token(T_char);
11021         rem_anchor_token(T_case);
11022         rem_anchor_token(T_break);
11023         rem_anchor_token(T_bool);
11024         rem_anchor_token(T_auto);
11025         rem_anchor_token(T_asm);
11026         rem_anchor_token(T___thread);
11027         rem_anchor_token(T___real__);
11028         rem_anchor_token(T___label__);
11029         rem_anchor_token(T___imag__);
11030         rem_anchor_token(T___func__);
11031         rem_anchor_token(T___extension__);
11032         rem_anchor_token(T___builtin_va_start);
11033         rem_anchor_token(T___attribute__);
11034         rem_anchor_token(T___alignof__);
11035         rem_anchor_token(T___PRETTY_FUNCTION__);
11036         rem_anchor_token(T___FUNCTION__);
11037         rem_anchor_token(T__Imaginary);
11038         rem_anchor_token(T__Complex);
11039         rem_anchor_token(T__Bool);
11040         rem_anchor_token(T_WIDE_STRING_LITERAL);
11041         rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11042         rem_anchor_token(T_STRING_LITERAL);
11043         rem_anchor_token(T_PLUSPLUS);
11044         rem_anchor_token(T_MINUSMINUS);
11045         rem_anchor_token(T_INTEGER);
11046         rem_anchor_token(T_IDENTIFIER);
11047         rem_anchor_token(T_FLOATINGPOINT);
11048         rem_anchor_token(T_COLONCOLON);
11049         rem_anchor_token(T_CHARACTER_CONSTANT);
11050         rem_anchor_token('~');
11051         rem_anchor_token('{');
11052         rem_anchor_token('-');
11053         rem_anchor_token('+');
11054         rem_anchor_token('*');
11055         rem_anchor_token('(');
11056         rem_anchor_token('&');
11057         rem_anchor_token('!');
11058         rem_anchor_token('}');
11059         assert(current_scope == &statement->compound.scope);
11060         scope_pop(old_scope);
11061         environment_pop_to(top);
11062
11063         POP_PARENT;
11064         return statement;
11065 }
11066
11067 /**
11068  * Check for unused global static functions and variables
11069  */
11070 static void check_unused_globals(void)
11071 {
11072         if (!warning.unused_function && !warning.unused_variable)
11073                 return;
11074
11075         for (const entity_t *entity = file_scope->entities; entity != NULL;
11076              entity = entity->base.next) {
11077                 if (!is_declaration(entity))
11078                         continue;
11079
11080                 const declaration_t *declaration = &entity->declaration;
11081                 if (declaration->used                  ||
11082                     declaration->modifiers & DM_UNUSED ||
11083                     declaration->modifiers & DM_USED   ||
11084                     declaration->storage_class != STORAGE_CLASS_STATIC)
11085                         continue;
11086
11087                 type_t *const type = declaration->type;
11088                 const char *s;
11089                 if (entity->kind == ENTITY_FUNCTION) {
11090                         /* inhibit warning for static inline functions */
11091                         if (entity->function.is_inline)
11092                                 continue;
11093
11094                         s = entity->function.statement != NULL ? "defined" : "declared";
11095                 } else {
11096                         s = "defined";
11097                 }
11098
11099                 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11100                         type, declaration->base.symbol, s);
11101         }
11102 }
11103
11104 static void parse_global_asm(void)
11105 {
11106         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11107
11108         eat(T_asm);
11109         expect('(', end_error);
11110
11111         statement->asms.asm_text = parse_string_literals();
11112         statement->base.next     = unit->global_asm;
11113         unit->global_asm         = statement;
11114
11115         expect(')', end_error);
11116         expect(';', end_error);
11117
11118 end_error:;
11119 }
11120
11121 static void parse_linkage_specification(void)
11122 {
11123         eat(T_extern);
11124         assert(token.type == T_STRING_LITERAL);
11125
11126         const char *linkage = parse_string_literals().begin;
11127
11128         linkage_kind_t old_linkage = current_linkage;
11129         linkage_kind_t new_linkage;
11130         if (strcmp(linkage, "C") == 0) {
11131                 new_linkage = LINKAGE_C;
11132         } else if (strcmp(linkage, "C++") == 0) {
11133                 new_linkage = LINKAGE_CXX;
11134         } else {
11135                 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11136                 new_linkage = LINKAGE_INVALID;
11137         }
11138         current_linkage = new_linkage;
11139
11140         if (token.type == '{') {
11141                 next_token();
11142                 parse_externals();
11143                 expect('}', end_error);
11144         } else {
11145                 parse_external();
11146         }
11147
11148 end_error:
11149         assert(current_linkage == new_linkage);
11150         current_linkage = old_linkage;
11151 }
11152
11153 static void parse_external(void)
11154 {
11155         switch (token.type) {
11156                 DECLARATION_START_NO_EXTERN
11157                 case T_IDENTIFIER:
11158                 case T___extension__:
11159                 /* tokens below are for implicit int */
11160                 case '&': /* & x; -> int& x; (and error later, because C++ has no
11161                              implicit int) */
11162                 case '*': /* * x; -> int* x; */
11163                 case '(': /* (x); -> int (x); */
11164                         parse_external_declaration();
11165                         return;
11166
11167                 case T_extern:
11168                         if (look_ahead(1)->type == T_STRING_LITERAL) {
11169                                 parse_linkage_specification();
11170                         } else {
11171                                 parse_external_declaration();
11172                         }
11173                         return;
11174
11175                 case T_asm:
11176                         parse_global_asm();
11177                         return;
11178
11179                 case T_namespace:
11180                         parse_namespace_definition();
11181                         return;
11182
11183                 case ';':
11184                         if (!strict_mode) {
11185                                 if (warning.other)
11186                                         warningf(HERE, "stray ';' outside of function");
11187                                 next_token();
11188                                 return;
11189                         }
11190                         /* FALLTHROUGH */
11191
11192                 default:
11193                         errorf(HERE, "stray %K outside of function", &token);
11194                         if (token.type == '(' || token.type == '{' || token.type == '[')
11195                                 eat_until_matching_token(token.type);
11196                         next_token();
11197                         return;
11198         }
11199 }
11200
11201 static void parse_externals(void)
11202 {
11203         add_anchor_token('}');
11204         add_anchor_token(T_EOF);
11205
11206 #ifndef NDEBUG
11207         unsigned char token_anchor_copy[T_LAST_TOKEN];
11208         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11209 #endif
11210
11211         while (token.type != T_EOF && token.type != '}') {
11212 #ifndef NDEBUG
11213                 bool anchor_leak = false;
11214                 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11215                         unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11216                         if (count != 0) {
11217                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11218                                 anchor_leak = true;
11219                         }
11220                 }
11221                 if (in_gcc_extension) {
11222                         errorf(HERE, "Leaked __extension__");
11223                         anchor_leak = true;
11224                 }
11225
11226                 if (anchor_leak)
11227                         abort();
11228 #endif
11229
11230                 parse_external();
11231         }
11232
11233         rem_anchor_token(T_EOF);
11234         rem_anchor_token('}');
11235 }
11236
11237 /**
11238  * Parse a translation unit.
11239  */
11240 static void parse_translation_unit(void)
11241 {
11242         add_anchor_token(T_EOF);
11243
11244         while (true) {
11245                 parse_externals();
11246
11247                 if (token.type == T_EOF)
11248                         break;
11249
11250                 errorf(HERE, "stray %K outside of function", &token);
11251                 if (token.type == '(' || token.type == '{' || token.type == '[')
11252                         eat_until_matching_token(token.type);
11253                 next_token();
11254         }
11255 }
11256
11257 /**
11258  * Parse the input.
11259  *
11260  * @return  the translation unit or NULL if errors occurred.
11261  */
11262 void start_parsing(void)
11263 {
11264         environment_stack = NEW_ARR_F(stack_entry_t, 0);
11265         label_stack       = NEW_ARR_F(stack_entry_t, 0);
11266         diagnostic_count  = 0;
11267         error_count       = 0;
11268         warning_count     = 0;
11269
11270         type_set_output(stderr);
11271         ast_set_output(stderr);
11272
11273         assert(unit == NULL);
11274         unit = allocate_ast_zero(sizeof(unit[0]));
11275
11276         assert(file_scope == NULL);
11277         file_scope = &unit->scope;
11278
11279         assert(current_scope == NULL);
11280         scope_push(&unit->scope);
11281 }
11282
11283 translation_unit_t *finish_parsing(void)
11284 {
11285         assert(current_scope == &unit->scope);
11286         scope_pop(NULL);
11287
11288         assert(file_scope == &unit->scope);
11289         check_unused_globals();
11290         file_scope = NULL;
11291
11292         DEL_ARR_F(environment_stack);
11293         DEL_ARR_F(label_stack);
11294
11295         translation_unit_t *result = unit;
11296         unit = NULL;
11297         return result;
11298 }
11299
11300 /* GCC allows global arrays without size and assigns them a length of one,
11301  * if no different declaration follows */
11302 static void complete_incomplete_arrays(void)
11303 {
11304         size_t n = ARR_LEN(incomplete_arrays);
11305         for (size_t i = 0; i != n; ++i) {
11306                 declaration_t *const decl      = incomplete_arrays[i];
11307                 type_t        *const orig_type = decl->type;
11308                 type_t        *const type      = skip_typeref(orig_type);
11309
11310                 if (!is_type_incomplete(type))
11311                         continue;
11312
11313                 if (warning.other) {
11314                         warningf(&decl->base.source_position,
11315                                         "array '%#T' assumed to have one element",
11316                                         orig_type, decl->base.symbol);
11317                 }
11318
11319                 type_t *const new_type = duplicate_type(type);
11320                 new_type->array.size_constant     = true;
11321                 new_type->array.has_implicit_size = true;
11322                 new_type->array.size              = 1;
11323
11324                 type_t *const result = typehash_insert(new_type);
11325                 if (type != result)
11326                         free_type(type);
11327
11328                 decl->type = result;
11329         }
11330 }
11331
11332 void parse(void)
11333 {
11334         lookahead_bufpos = 0;
11335         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11336                 next_token();
11337         }
11338         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11339         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11340         parse_translation_unit();
11341         complete_incomplete_arrays();
11342         DEL_ARR_F(incomplete_arrays);
11343         incomplete_arrays = NULL;
11344 }
11345
11346 /**
11347  * Initialize the parser.
11348  */
11349 void init_parser(void)
11350 {
11351         sym_anonymous = symbol_table_insert("<anonymous>");
11352
11353         if (c_mode & _MS) {
11354                 /* add predefined symbols for extended-decl-modifier */
11355                 sym_align      = symbol_table_insert("align");
11356                 sym_allocate   = symbol_table_insert("allocate");
11357                 sym_dllimport  = symbol_table_insert("dllimport");
11358                 sym_dllexport  = symbol_table_insert("dllexport");
11359                 sym_naked      = symbol_table_insert("naked");
11360                 sym_noinline   = symbol_table_insert("noinline");
11361                 sym_noreturn   = symbol_table_insert("noreturn");
11362                 sym_nothrow    = symbol_table_insert("nothrow");
11363                 sym_novtable   = symbol_table_insert("novtable");
11364                 sym_property   = symbol_table_insert("property");
11365                 sym_get        = symbol_table_insert("get");
11366                 sym_put        = symbol_table_insert("put");
11367                 sym_selectany  = symbol_table_insert("selectany");
11368                 sym_thread     = symbol_table_insert("thread");
11369                 sym_uuid       = symbol_table_insert("uuid");
11370                 sym_deprecated = symbol_table_insert("deprecated");
11371                 sym_restrict   = symbol_table_insert("restrict");
11372                 sym_noalias    = symbol_table_insert("noalias");
11373         }
11374         memset(token_anchor_set, 0, sizeof(token_anchor_set));
11375
11376         init_expression_parsers();
11377         obstack_init(&temp_obst);
11378
11379         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11380         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11381 }
11382
11383 /**
11384  * Terminate the parser.
11385  */
11386 void exit_parser(void)
11387 {
11388         obstack_free(&temp_obst, NULL);
11389 }