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