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