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