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