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