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