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