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