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