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