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