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