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