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