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