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