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