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