81c2ef80d118fd0d06538709bb1f7f4ed16d3ea2
[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         decl_modifiers_t  modifiers  = 0;
2478         if(is_struct) {
2479                 eat(T_struct);
2480         } else {
2481                 eat(T_union);
2482         }
2483
2484         symbol_t      *symbol      = NULL;
2485         declaration_t *declaration = NULL;
2486
2487         if (token.type == T___attribute__) {
2488                 modifiers |= parse_attributes(&attributes);
2489         }
2490
2491         if(token.type == T_IDENTIFIER) {
2492                 symbol = token.v.symbol;
2493                 next_token();
2494
2495                 if(is_struct) {
2496                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2497                 } else {
2498                         declaration = get_declaration(symbol, NAMESPACE_UNION);
2499                 }
2500         } else if(token.type != '{') {
2501                 if(is_struct) {
2502                         parse_error_expected("while parsing struct type specifier",
2503                                              T_IDENTIFIER, '{', NULL);
2504                 } else {
2505                         parse_error_expected("while parsing union type specifier",
2506                                              T_IDENTIFIER, '{', NULL);
2507                 }
2508
2509                 return NULL;
2510         }
2511
2512         if(declaration == NULL) {
2513                 declaration = allocate_declaration_zero();
2514                 declaration->namespc         =
2515                         (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2516                 declaration->source_position = token.source_position;
2517                 declaration->symbol          = symbol;
2518                 declaration->parent_scope    = scope;
2519                 if (symbol != NULL) {
2520                         environment_push(declaration);
2521                 }
2522                 append_declaration(declaration);
2523         }
2524
2525         if(token.type == '{') {
2526                 if (declaration->init.complete) {
2527                         assert(symbol != NULL);
2528                         errorf(HERE, "multiple definitions of '%s %Y'",
2529                                is_struct ? "struct" : "union", symbol);
2530                         declaration->scope.declarations = NULL;
2531                 }
2532                 declaration->init.complete = true;
2533
2534                 parse_compound_type_entries(declaration);
2535                 modifiers |= parse_attributes(&attributes);
2536         }
2537
2538         declaration->modifiers |= modifiers;
2539         return declaration;
2540 }
2541
2542 static void parse_enum_entries(type_t *const enum_type)
2543 {
2544         eat('{');
2545
2546         if(token.type == '}') {
2547                 next_token();
2548                 errorf(HERE, "empty enum not allowed");
2549                 return;
2550         }
2551
2552         add_anchor_token('}');
2553         do {
2554                 if(token.type != T_IDENTIFIER) {
2555                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2556                         eat_block();
2557                         rem_anchor_token('}');
2558                         return;
2559                 }
2560
2561                 declaration_t *const entry = allocate_declaration_zero();
2562                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
2563                 entry->type            = enum_type;
2564                 entry->symbol          = token.v.symbol;
2565                 entry->source_position = token.source_position;
2566                 next_token();
2567
2568                 if(token.type == '=') {
2569                         next_token();
2570                         expression_t *value = parse_constant_expression();
2571
2572                         value = create_implicit_cast(value, enum_type);
2573                         entry->init.enum_value = value;
2574
2575                         /* TODO semantic */
2576                 }
2577
2578                 record_declaration(entry);
2579
2580                 if(token.type != ',')
2581                         break;
2582                 next_token();
2583         } while(token.type != '}');
2584         rem_anchor_token('}');
2585
2586         expect('}');
2587
2588 end_error:
2589         ;
2590 }
2591
2592 static type_t *parse_enum_specifier(void)
2593 {
2594         gnu_attribute_t *attributes = NULL;
2595         declaration_t   *declaration;
2596         symbol_t        *symbol;
2597
2598         eat(T_enum);
2599         if(token.type == T_IDENTIFIER) {
2600                 symbol = token.v.symbol;
2601                 next_token();
2602
2603                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2604         } else if(token.type != '{') {
2605                 parse_error_expected("while parsing enum type specifier",
2606                                      T_IDENTIFIER, '{', NULL);
2607                 return NULL;
2608         } else {
2609                 declaration = NULL;
2610                 symbol      = NULL;
2611         }
2612
2613         if(declaration == NULL) {
2614                 declaration = allocate_declaration_zero();
2615                 declaration->namespc         = NAMESPACE_ENUM;
2616                 declaration->source_position = token.source_position;
2617                 declaration->symbol          = symbol;
2618                 declaration->parent_scope  = scope;
2619         }
2620
2621         type_t *const type      = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2622         type->enumt.declaration = declaration;
2623
2624         if(token.type == '{') {
2625                 if(declaration->init.complete) {
2626                         errorf(HERE, "multiple definitions of enum %Y", symbol);
2627                 }
2628                 if (symbol != NULL) {
2629                         environment_push(declaration);
2630                 }
2631                 append_declaration(declaration);
2632                 declaration->init.complete = true;
2633
2634                 parse_enum_entries(type);
2635                 parse_attributes(&attributes);
2636         }
2637
2638         return type;
2639 }
2640
2641 /**
2642  * if a symbol is a typedef to another type, return true
2643  */
2644 static bool is_typedef_symbol(symbol_t *symbol)
2645 {
2646         const declaration_t *const declaration =
2647                 get_declaration(symbol, NAMESPACE_NORMAL);
2648         return
2649                 declaration != NULL &&
2650                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2651 }
2652
2653 static type_t *parse_typeof(void)
2654 {
2655         eat(T___typeof__);
2656
2657         type_t *type;
2658
2659         expect('(');
2660         add_anchor_token(')');
2661
2662         expression_t *expression  = NULL;
2663
2664 restart:
2665         switch(token.type) {
2666         case T___extension__:
2667                 /* this can be a prefix to a typename or an expression */
2668                 /* we simply eat it now. */
2669                 do {
2670                         next_token();
2671                 } while(token.type == T___extension__);
2672                 goto restart;
2673
2674         case T_IDENTIFIER:
2675                 if(is_typedef_symbol(token.v.symbol)) {
2676                         type = parse_typename();
2677                 } else {
2678                         expression = parse_expression();
2679                         type       = expression->base.type;
2680                 }
2681                 break;
2682
2683         TYPENAME_START
2684                 type = parse_typename();
2685                 break;
2686
2687         default:
2688                 expression = parse_expression();
2689                 type       = expression->base.type;
2690                 break;
2691         }
2692
2693         rem_anchor_token(')');
2694         expect(')');
2695
2696         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2697         typeof_type->typeoft.expression  = expression;
2698         typeof_type->typeoft.typeof_type = type;
2699
2700         return typeof_type;
2701 end_error:
2702         return NULL;
2703 }
2704
2705 typedef enum {
2706         SPECIFIER_SIGNED    = 1 << 0,
2707         SPECIFIER_UNSIGNED  = 1 << 1,
2708         SPECIFIER_LONG      = 1 << 2,
2709         SPECIFIER_INT       = 1 << 3,
2710         SPECIFIER_DOUBLE    = 1 << 4,
2711         SPECIFIER_CHAR      = 1 << 5,
2712         SPECIFIER_SHORT     = 1 << 6,
2713         SPECIFIER_LONG_LONG = 1 << 7,
2714         SPECIFIER_FLOAT     = 1 << 8,
2715         SPECIFIER_BOOL      = 1 << 9,
2716         SPECIFIER_VOID      = 1 << 10,
2717         SPECIFIER_INT8      = 1 << 11,
2718         SPECIFIER_INT16     = 1 << 12,
2719         SPECIFIER_INT32     = 1 << 13,
2720         SPECIFIER_INT64     = 1 << 14,
2721         SPECIFIER_INT128    = 1 << 15,
2722         SPECIFIER_COMPLEX   = 1 << 16,
2723         SPECIFIER_IMAGINARY = 1 << 17,
2724 } specifiers_t;
2725
2726 static type_t *create_builtin_type(symbol_t *const symbol,
2727                                    type_t *const real_type)
2728 {
2729         type_t *type            = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2730         type->builtin.symbol    = symbol;
2731         type->builtin.real_type = real_type;
2732
2733         type_t *result = typehash_insert(type);
2734         if(type != result) {
2735                 free_type(type);
2736         }
2737
2738         return result;
2739 }
2740
2741 static type_t *get_typedef_type(symbol_t *symbol)
2742 {
2743         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2744         if(declaration == NULL ||
2745            declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2746                 return NULL;
2747
2748         type_t *type               = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2749         type->typedeft.declaration = declaration;
2750
2751         return type;
2752 }
2753
2754 /**
2755  * check for the allowed MS alignment values.
2756  */
2757 static bool check_elignment_value(long long intvalue) {
2758         if(intvalue < 1 || intvalue > 8192) {
2759                 errorf(HERE, "illegal alignment value");
2760                 return false;
2761         }
2762         unsigned v = (unsigned)intvalue;
2763         for(unsigned i = 1; i <= 8192; i += i) {
2764                 if (i == v)
2765                         return true;
2766         }
2767         errorf(HERE, "alignment must be power of two");
2768         return false;
2769 }
2770
2771 #define DET_MOD(name, tag) do { \
2772         if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2773         *modifiers |= tag; \
2774 } while(0)
2775
2776 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2777 {
2778         decl_modifiers_t *modifiers = &specifiers->modifiers;
2779
2780         while(true) {
2781                 if(token.type == T_restrict) {
2782                         next_token();
2783                         DET_MOD(restrict, DM_RESTRICT);
2784                         goto end_loop;
2785                 } else if(token.type != T_IDENTIFIER)
2786                         break;
2787                 symbol_t *symbol = token.v.symbol;
2788                 if(symbol == sym_align) {
2789                         next_token();
2790                         expect('(');
2791                         if(token.type != T_INTEGER)
2792                                 goto end_error;
2793                         if(check_elignment_value(token.v.intvalue)) {
2794                                 if(specifiers->alignment != 0)
2795                                         warningf(HERE, "align used more than once");
2796                                 specifiers->alignment = (unsigned char)token.v.intvalue;
2797                         }
2798                         next_token();
2799                         expect(')');
2800                 } else if(symbol == sym_allocate) {
2801                         next_token();
2802                         expect('(');
2803                         if(token.type != T_IDENTIFIER)
2804                                 goto end_error;
2805                         (void)token.v.symbol;
2806                         expect(')');
2807                 } else if(symbol == sym_dllimport) {
2808                         next_token();
2809                         DET_MOD(dllimport, DM_DLLIMPORT);
2810                 } else if(symbol == sym_dllexport) {
2811                         next_token();
2812                         DET_MOD(dllexport, DM_DLLEXPORT);
2813                 } else if(symbol == sym_thread) {
2814                         next_token();
2815                         DET_MOD(thread, DM_THREAD);
2816                 } else if(symbol == sym_naked) {
2817                         next_token();
2818                         DET_MOD(naked, DM_NAKED);
2819                 } else if(symbol == sym_noinline) {
2820                         next_token();
2821                         DET_MOD(noinline, DM_NOINLINE);
2822                 } else if(symbol == sym_noreturn) {
2823                         next_token();
2824                         DET_MOD(noreturn, DM_NORETURN);
2825                 } else if(symbol == sym_nothrow) {
2826                         next_token();
2827                         DET_MOD(nothrow, DM_NOTHROW);
2828                 } else if(symbol == sym_novtable) {
2829                         next_token();
2830                         DET_MOD(novtable, DM_NOVTABLE);
2831                 } else if(symbol == sym_property) {
2832                         next_token();
2833                         expect('(');
2834                         for(;;) {
2835                                 bool is_get = false;
2836                                 if(token.type != T_IDENTIFIER)
2837                                         goto end_error;
2838                                 if(token.v.symbol == sym_get) {
2839                                         is_get = true;
2840                                 } else if(token.v.symbol == sym_put) {
2841                                 } else {
2842                                         errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2843                                         goto end_error;
2844                                 }
2845                                 next_token();
2846                                 expect('=');
2847                                 if(token.type != T_IDENTIFIER)
2848                                         goto end_error;
2849                                 if(is_get) {
2850                                         if(specifiers->get_property_sym != NULL) {
2851                                                 errorf(HERE, "get property name already specified");
2852                                         } else {
2853                                                 specifiers->get_property_sym = token.v.symbol;
2854                                         }
2855                                 } else {
2856                                         if(specifiers->put_property_sym != NULL) {
2857                                                 errorf(HERE, "put property name already specified");
2858                                         } else {
2859                                                 specifiers->put_property_sym = token.v.symbol;
2860                                         }
2861                                 }
2862                                 next_token();
2863                                 if(token.type == ',') {
2864                                         next_token();
2865                                         continue;
2866                                 }
2867                                 break;
2868                         }
2869                         expect(')');
2870                 } else if(symbol == sym_selectany) {
2871                         next_token();
2872                         DET_MOD(selectany, DM_SELECTANY);
2873                 } else if(symbol == sym_uuid) {
2874                         next_token();
2875                         expect('(');
2876                         if(token.type != T_STRING_LITERAL)
2877                                 goto end_error;
2878                         next_token();
2879                         expect(')');
2880                 } else if(symbol == sym_deprecated) {
2881                         next_token();
2882                         if(specifiers->deprecated != 0)
2883                                 warningf(HERE, "deprecated used more than once");
2884                         specifiers->deprecated = 1;
2885                         if(token.type == '(') {
2886                                 next_token();
2887                                 if(token.type == T_STRING_LITERAL) {
2888                                         specifiers->deprecated_string = token.v.string.begin;
2889                                         next_token();
2890                                 } else {
2891                                         errorf(HERE, "string literal expected");
2892                                 }
2893                                 expect(')');
2894                         }
2895                 } else if(symbol == sym_noalias) {
2896                         next_token();
2897                         DET_MOD(noalias, DM_NOALIAS);
2898                 } else {
2899                         warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2900                         next_token();
2901                         if(token.type == '(')
2902                                 skip_until(')');
2903                 }
2904 end_loop:
2905                 if (token.type == ',')
2906                         next_token();
2907         }
2908 end_error:
2909         return;
2910 }
2911
2912 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2913 {
2914         type_t   *type            = NULL;
2915         unsigned  type_qualifiers = 0;
2916         unsigned  type_specifiers = 0;
2917         int       newtype         = 0;
2918
2919         specifiers->source_position = token.source_position;
2920
2921         while(true) {
2922                 switch(token.type) {
2923
2924                 /* storage class */
2925 #define MATCH_STORAGE_CLASS(token, class)                                  \
2926                 case token:                                                        \
2927                         if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2928                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2929                         }                                                              \
2930                         specifiers->declared_storage_class = class;                    \
2931                         next_token();                                                  \
2932                         break;
2933
2934                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
2935                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
2936                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
2937                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
2938                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2939
2940                 case T__declspec:
2941                         next_token();
2942                         expect('(');
2943                         add_anchor_token(')');
2944                         parse_microsoft_extended_decl_modifier(specifiers);
2945                         rem_anchor_token(')');
2946                         expect(')');
2947                         break;
2948
2949                 case T___thread:
2950                         switch (specifiers->declared_storage_class) {
2951                         case STORAGE_CLASS_NONE:
2952                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2953                                 break;
2954
2955                         case STORAGE_CLASS_EXTERN:
2956                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2957                                 break;
2958
2959                         case STORAGE_CLASS_STATIC:
2960                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2961                                 break;
2962
2963                         default:
2964                                 errorf(HERE, "multiple storage classes in declaration specifiers");
2965                                 break;
2966                         }
2967                         next_token();
2968                         break;
2969
2970                 /* type qualifiers */
2971 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
2972                 case token:                                                     \
2973                         type_qualifiers |= qualifier;                               \
2974                         next_token();                                               \
2975                         break;
2976
2977                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2978                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2979                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2980                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
2981                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
2982                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
2983                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
2984                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
2985
2986                 case T___extension__:
2987                         /* TODO */
2988                         next_token();
2989                         break;
2990
2991                 /* type specifiers */
2992 #define MATCH_SPECIFIER(token, specifier, name)                         \
2993                 case token:                                                     \
2994                         next_token();                                               \
2995                         if(type_specifiers & specifier) {                           \
2996                                 errorf(HERE, "multiple " name " type specifiers given"); \
2997                         } else {                                                    \
2998                                 type_specifiers |= specifier;                           \
2999                         }                                                           \
3000                         break;
3001
3002                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
3003                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
3004                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
3005                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
3006                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
3007                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
3008                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
3009                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
3010                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
3011                 MATCH_SPECIFIER(T__int8,      SPECIFIER_INT8,      "_int8")
3012                 MATCH_SPECIFIER(T__int16,     SPECIFIER_INT16,     "_int16")
3013                 MATCH_SPECIFIER(T__int32,     SPECIFIER_INT32,     "_int32")
3014                 MATCH_SPECIFIER(T__int64,     SPECIFIER_INT64,     "_int64")
3015                 MATCH_SPECIFIER(T__int128,    SPECIFIER_INT128,    "_int128")
3016                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
3017                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3018
3019                 case T__forceinline:
3020                         /* only in microsoft mode */
3021                         specifiers->modifiers |= DM_FORCEINLINE;
3022
3023                 case T_inline:
3024                         next_token();
3025                         specifiers->is_inline = true;
3026                         break;
3027
3028                 case T_long:
3029                         next_token();
3030                         if(type_specifiers & SPECIFIER_LONG_LONG) {
3031                                 errorf(HERE, "multiple type specifiers given");
3032                         } else if(type_specifiers & SPECIFIER_LONG) {
3033                                 type_specifiers |= SPECIFIER_LONG_LONG;
3034                         } else {
3035                                 type_specifiers |= SPECIFIER_LONG;
3036                         }
3037                         break;
3038
3039                 case T_struct: {
3040                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3041
3042                         type->compound.declaration = parse_compound_type_specifier(true);
3043                         break;
3044                 }
3045                 case T_union: {
3046                         type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3047
3048                         type->compound.declaration = parse_compound_type_specifier(false);
3049                         break;
3050                 }
3051                 case T_enum:
3052                         type = parse_enum_specifier();
3053                         break;
3054                 case T___typeof__:
3055                         type = parse_typeof();
3056                         break;
3057                 case T___builtin_va_list:
3058                         type = duplicate_type(type_valist);
3059                         next_token();
3060                         break;
3061
3062                 case T___attribute__:
3063                         specifiers->modifiers
3064                                 |= parse_attributes(&specifiers->gnu_attributes);
3065                         break;
3066
3067                 case T_IDENTIFIER: {
3068                         /* only parse identifier if we haven't found a type yet */
3069                         if(type != NULL || type_specifiers != 0)
3070                                 goto finish_specifiers;
3071
3072                         type_t *typedef_type = get_typedef_type(token.v.symbol);
3073
3074                         if(typedef_type == NULL)
3075                                 goto finish_specifiers;
3076
3077                         next_token();
3078                         type = typedef_type;
3079                         break;
3080                 }
3081
3082                 /* function specifier */
3083                 default:
3084                         goto finish_specifiers;
3085                 }
3086         }
3087
3088 finish_specifiers:
3089
3090         if(type == NULL) {
3091                 atomic_type_kind_t atomic_type;
3092
3093                 /* match valid basic types */
3094                 switch(type_specifiers) {
3095                 case SPECIFIER_VOID:
3096                         atomic_type = ATOMIC_TYPE_VOID;
3097                         break;
3098                 case SPECIFIER_CHAR:
3099                         atomic_type = ATOMIC_TYPE_CHAR;
3100                         break;
3101                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3102                         atomic_type = ATOMIC_TYPE_SCHAR;
3103                         break;
3104                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3105                         atomic_type = ATOMIC_TYPE_UCHAR;
3106                         break;
3107                 case SPECIFIER_SHORT:
3108                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3109                 case SPECIFIER_SHORT | SPECIFIER_INT:
3110                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3111                         atomic_type = ATOMIC_TYPE_SHORT;
3112                         break;
3113                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3114                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3115                         atomic_type = ATOMIC_TYPE_USHORT;
3116                         break;
3117                 case SPECIFIER_INT:
3118                 case SPECIFIER_SIGNED:
3119                 case SPECIFIER_SIGNED | SPECIFIER_INT:
3120                         atomic_type = ATOMIC_TYPE_INT;
3121                         break;
3122                 case SPECIFIER_UNSIGNED:
3123                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3124                         atomic_type = ATOMIC_TYPE_UINT;
3125                         break;
3126                 case SPECIFIER_LONG:
3127                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3128                 case SPECIFIER_LONG | SPECIFIER_INT:
3129                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3130                         atomic_type = ATOMIC_TYPE_LONG;
3131                         break;
3132                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3133                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3134                         atomic_type = ATOMIC_TYPE_ULONG;
3135                         break;
3136                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3137                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3138                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3139                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3140                         | SPECIFIER_INT:
3141                         atomic_type = ATOMIC_TYPE_LONGLONG;
3142                         break;
3143                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3144                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3145                         | SPECIFIER_INT:
3146                         atomic_type = ATOMIC_TYPE_ULONGLONG;
3147                         break;
3148
3149                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3150                         atomic_type = unsigned_int8_type_kind;
3151                         break;
3152
3153                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3154                         atomic_type = unsigned_int16_type_kind;
3155                         break;
3156
3157                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3158                         atomic_type = unsigned_int32_type_kind;
3159                         break;
3160
3161                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3162                         atomic_type = unsigned_int64_type_kind;
3163                         break;
3164
3165                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3166                         atomic_type = unsigned_int128_type_kind;
3167                         break;
3168
3169                 case SPECIFIER_INT8:
3170                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3171                         atomic_type = int8_type_kind;
3172                         break;
3173
3174                 case SPECIFIER_INT16:
3175                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3176                         atomic_type = int16_type_kind;
3177                         break;
3178
3179                 case SPECIFIER_INT32:
3180                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3181                         atomic_type = int32_type_kind;
3182                         break;
3183
3184                 case SPECIFIER_INT64:
3185                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3186                         atomic_type = int64_type_kind;
3187                         break;
3188
3189                 case SPECIFIER_INT128:
3190                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3191                         atomic_type = int128_type_kind;
3192                         break;
3193
3194                 case SPECIFIER_FLOAT:
3195                         atomic_type = ATOMIC_TYPE_FLOAT;
3196                         break;
3197                 case SPECIFIER_DOUBLE:
3198                         atomic_type = ATOMIC_TYPE_DOUBLE;
3199                         break;
3200                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3201                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3202                         break;
3203                 case SPECIFIER_BOOL:
3204                         atomic_type = ATOMIC_TYPE_BOOL;
3205                         break;
3206                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3207                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3208                         atomic_type = ATOMIC_TYPE_FLOAT;
3209                         break;
3210                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3211                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3212                         atomic_type = ATOMIC_TYPE_DOUBLE;
3213                         break;
3214                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3215                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3216                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3217                         break;
3218                 default:
3219                         /* invalid specifier combination, give an error message */
3220                         if(type_specifiers == 0) {
3221                                 if (! strict_mode) {
3222                                         if (warning.implicit_int) {
3223                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
3224                                         }
3225                                         atomic_type = ATOMIC_TYPE_INT;
3226                                         break;
3227                                 } else {
3228                                         errorf(HERE, "no type specifiers given in declaration");
3229                                 }
3230                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
3231                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
3232                                 errorf(HERE, "signed and unsigned specifiers gives");
3233                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3234                                 errorf(HERE, "only integer types can be signed or unsigned");
3235                         } else {
3236                                 errorf(HERE, "multiple datatypes in declaration");
3237                         }
3238                         atomic_type = ATOMIC_TYPE_INVALID;
3239                 }
3240
3241                 if(type_specifiers & SPECIFIER_COMPLEX &&
3242                    atomic_type != ATOMIC_TYPE_INVALID) {
3243                         type                = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3244                         type->complex.akind = atomic_type;
3245                 } else if(type_specifiers & SPECIFIER_IMAGINARY &&
3246                           atomic_type != ATOMIC_TYPE_INVALID) {
3247                         type                  = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3248                         type->imaginary.akind = atomic_type;
3249                 } else {
3250                         type               = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3251                         type->atomic.akind = atomic_type;
3252                 }
3253                 newtype = 1;
3254         } else {
3255                 if(type_specifiers != 0) {
3256                         errorf(HERE, "multiple datatypes in declaration");
3257                 }
3258         }
3259
3260         type->base.qualifiers = type_qualifiers;
3261         /* FIXME: check type qualifiers here */
3262
3263         type_t *result = typehash_insert(type);
3264         if(newtype && result != type) {
3265                 free_type(type);
3266         }
3267
3268         specifiers->type = result;
3269 end_error:
3270         return;
3271 }
3272
3273 static type_qualifiers_t parse_type_qualifiers(void)
3274 {
3275         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3276
3277         while(true) {
3278                 switch(token.type) {
3279                 /* type qualifiers */
3280                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3281                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3282                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3283                 /* microsoft extended type modifiers */
3284                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3285                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3286                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3287                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3288                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3289
3290                 default:
3291                         return type_qualifiers;
3292                 }
3293         }
3294 }
3295
3296 static declaration_t *parse_identifier_list(void)
3297 {
3298         declaration_t *declarations     = NULL;
3299         declaration_t *last_declaration = NULL;
3300         do {
3301                 declaration_t *const declaration = allocate_declaration_zero();
3302                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
3303                 declaration->source_position = token.source_position;
3304                 declaration->symbol          = token.v.symbol;
3305                 next_token();
3306
3307                 if(last_declaration != NULL) {
3308                         last_declaration->next = declaration;
3309                 } else {
3310                         declarations = declaration;
3311                 }
3312                 last_declaration = declaration;
3313
3314                 if (token.type != ',') {
3315                         break;
3316                 }
3317                 next_token();
3318         } while(token.type == T_IDENTIFIER);
3319
3320         return declarations;
3321 }
3322
3323 static void semantic_parameter(declaration_t *declaration)
3324 {
3325         /* TODO: improve error messages */
3326
3327         if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3328                 errorf(HERE, "typedef not allowed in parameter list");
3329         } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3330                         && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3331                 errorf(HERE, "parameter may only have none or register storage class");
3332         }
3333
3334         type_t *const orig_type = declaration->type;
3335         type_t *      type      = skip_typeref(orig_type);
3336
3337         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
3338          * into a pointer. Â§ 6.7.5.3 (7) */
3339         if (is_type_array(type)) {
3340                 type_t *const element_type = type->array.element_type;
3341
3342                 type = make_pointer_type(element_type, type->base.qualifiers);
3343
3344                 declaration->type = type;
3345         }
3346
3347         if(is_type_incomplete(type)) {
3348                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3349                        orig_type, declaration->symbol);
3350         }
3351 }
3352
3353 static declaration_t *parse_parameter(void)
3354 {
3355         declaration_specifiers_t specifiers;
3356         memset(&specifiers, 0, sizeof(specifiers));
3357
3358         parse_declaration_specifiers(&specifiers);
3359
3360         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3361
3362         semantic_parameter(declaration);
3363
3364         return declaration;
3365 }
3366
3367 static declaration_t *parse_parameters(function_type_t *type)
3368 {
3369         declaration_t *declarations = NULL;
3370
3371         eat('(');
3372         add_anchor_token(')');
3373         int saved_comma_state = save_and_reset_anchor_state(',');
3374
3375         if(token.type == T_IDENTIFIER) {
3376                 symbol_t *symbol = token.v.symbol;
3377                 if(!is_typedef_symbol(symbol)) {
3378                         type->kr_style_parameters = true;
3379                         declarations = parse_identifier_list();
3380                         goto parameters_finished;
3381                 }
3382         }
3383
3384         if(token.type == ')') {
3385                 type->unspecified_parameters = 1;
3386                 goto parameters_finished;
3387         }
3388         if(token.type == T_void && look_ahead(1)->type == ')') {
3389                 next_token();
3390                 goto parameters_finished;
3391         }
3392
3393         declaration_t        *declaration;
3394         declaration_t        *last_declaration = NULL;
3395         function_parameter_t *parameter;
3396         function_parameter_t *last_parameter = NULL;
3397
3398         while(true) {
3399                 switch(token.type) {
3400                 case T_DOTDOTDOT:
3401                         next_token();
3402                         type->variadic = 1;
3403                         goto parameters_finished;
3404
3405                 case T_IDENTIFIER:
3406                 case T___extension__:
3407                 DECLARATION_START
3408                         declaration = parse_parameter();
3409
3410                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
3411                         memset(parameter, 0, sizeof(parameter[0]));
3412                         parameter->type = declaration->type;
3413
3414                         if(last_parameter != NULL) {
3415                                 last_declaration->next = declaration;
3416                                 last_parameter->next   = parameter;
3417                         } else {
3418                                 type->parameters = parameter;
3419                                 declarations     = declaration;
3420                         }
3421                         last_parameter   = parameter;
3422                         last_declaration = declaration;
3423                         break;
3424
3425                 default:
3426                         goto parameters_finished;
3427                 }
3428                 if (token.type != ',') {
3429                         goto parameters_finished;
3430                 }
3431                 next_token();
3432         }
3433
3434
3435 parameters_finished:
3436         rem_anchor_token(')');
3437         expect(')');
3438
3439         restore_anchor_state(',', saved_comma_state);
3440         return declarations;
3441
3442 end_error:
3443         restore_anchor_state(',', saved_comma_state);
3444         return NULL;
3445 }
3446
3447 typedef enum {
3448         CONSTRUCT_INVALID,
3449         CONSTRUCT_POINTER,
3450         CONSTRUCT_FUNCTION,
3451         CONSTRUCT_ARRAY
3452 } construct_type_kind_t;
3453
3454 typedef struct construct_type_t construct_type_t;
3455 struct construct_type_t {
3456         construct_type_kind_t  kind;
3457         construct_type_t      *next;
3458 };
3459
3460 typedef struct parsed_pointer_t parsed_pointer_t;
3461 struct parsed_pointer_t {
3462         construct_type_t  construct_type;
3463         type_qualifiers_t type_qualifiers;
3464 };
3465
3466 typedef struct construct_function_type_t construct_function_type_t;
3467 struct construct_function_type_t {
3468         construct_type_t  construct_type;
3469         type_t           *function_type;
3470 };
3471
3472 typedef struct parsed_array_t parsed_array_t;
3473 struct parsed_array_t {
3474         construct_type_t  construct_type;
3475         type_qualifiers_t type_qualifiers;
3476         bool              is_static;
3477         bool              is_variable;
3478         expression_t     *size;
3479 };
3480
3481 typedef struct construct_base_type_t construct_base_type_t;
3482 struct construct_base_type_t {
3483         construct_type_t  construct_type;
3484         type_t           *type;
3485 };
3486
3487 static construct_type_t *parse_pointer_declarator(void)
3488 {
3489         eat('*');
3490
3491         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3492         memset(pointer, 0, sizeof(pointer[0]));
3493         pointer->construct_type.kind = CONSTRUCT_POINTER;
3494         pointer->type_qualifiers     = parse_type_qualifiers();
3495
3496         return (construct_type_t*) pointer;
3497 }
3498
3499 static construct_type_t *parse_array_declarator(void)
3500 {
3501         eat('[');
3502         add_anchor_token(']');
3503
3504         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3505         memset(array, 0, sizeof(array[0]));
3506         array->construct_type.kind = CONSTRUCT_ARRAY;
3507
3508         if(token.type == T_static) {
3509                 array->is_static = true;
3510                 next_token();
3511         }
3512
3513         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3514         if(type_qualifiers != 0) {
3515                 if(token.type == T_static) {
3516                         array->is_static = true;
3517                         next_token();
3518                 }
3519         }
3520         array->type_qualifiers = type_qualifiers;
3521
3522         if(token.type == '*' && look_ahead(1)->type == ']') {
3523                 array->is_variable = true;
3524                 next_token();
3525         } else if(token.type != ']') {
3526                 array->size = parse_assignment_expression();
3527         }
3528
3529         rem_anchor_token(']');
3530         expect(']');
3531
3532         return (construct_type_t*) array;
3533 end_error:
3534         return NULL;
3535 }
3536
3537 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3538 {
3539         type_t *type;
3540         if(declaration != NULL) {
3541                 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3542         } else {
3543                 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3544         }
3545
3546         declaration_t *parameters = parse_parameters(&type->function);
3547         if(declaration != NULL) {
3548                 declaration->scope.declarations = parameters;
3549         }
3550
3551         construct_function_type_t *construct_function_type =
3552                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3553         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3554         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3555         construct_function_type->function_type       = type;
3556
3557         return (construct_type_t*) construct_function_type;
3558 }
3559
3560 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3561                 bool may_be_abstract)
3562 {
3563         /* construct a single linked list of construct_type_t's which describe
3564          * how to construct the final declarator type */
3565         construct_type_t *first = NULL;
3566         construct_type_t *last  = NULL;
3567         gnu_attribute_t  *attributes = NULL;
3568
3569         /* pointers */
3570         while(token.type == '*') {
3571                 construct_type_t *type = parse_pointer_declarator();
3572
3573                 if(last == NULL) {
3574                         first = type;
3575                         last  = type;
3576                 } else {
3577                         last->next = type;
3578                         last       = type;
3579                 }
3580         }
3581
3582         /* TODO: find out if this is correct */
3583         decl_modifiers_t modifiers = parse_attributes(&attributes);
3584         if (declaration != NULL)
3585                 declaration->modifiers |= modifiers;
3586
3587         construct_type_t *inner_types = NULL;
3588
3589         switch(token.type) {
3590         case T_IDENTIFIER:
3591                 if(declaration == NULL) {
3592                         errorf(HERE, "no identifier expected in typename");
3593                 } else {
3594                         declaration->symbol          = token.v.symbol;
3595                         declaration->source_position = token.source_position;
3596                 }
3597                 next_token();
3598                 break;
3599         case '(':
3600                 next_token();
3601                 add_anchor_token(')');
3602                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3603                 rem_anchor_token(')');
3604                 expect(')');
3605                 break;
3606         default:
3607                 if(may_be_abstract)
3608                         break;
3609                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3610                 /* avoid a loop in the outermost scope, because eat_statement doesn't
3611                  * eat '}' */
3612                 if(token.type == '}' && current_function == NULL) {
3613                         next_token();
3614                 } else {
3615                         eat_statement();
3616                 }
3617                 return NULL;
3618         }
3619
3620         construct_type_t *p = last;
3621
3622         while(true) {
3623                 construct_type_t *type;
3624                 switch(token.type) {
3625                 case '(':
3626                         type = parse_function_declarator(declaration);
3627                         break;
3628                 case '[':
3629                         type = parse_array_declarator();
3630                         break;
3631                 default:
3632                         goto declarator_finished;
3633                 }
3634
3635                 /* insert in the middle of the list (behind p) */
3636                 if(p != NULL) {
3637                         type->next = p->next;
3638                         p->next    = type;
3639                 } else {
3640                         type->next = first;
3641                         first      = type;
3642                 }
3643                 if(last == p) {
3644                         last = type;
3645                 }
3646         }
3647
3648 declarator_finished:
3649         modifiers = parse_attributes(&attributes);
3650         if (declaration != NULL)
3651                 declaration->modifiers |= modifiers;
3652
3653         /* append inner_types at the end of the list, we don't to set last anymore
3654          * as it's not needed anymore */
3655         if(last == NULL) {
3656                 assert(first == NULL);
3657                 first = inner_types;
3658         } else {
3659                 last->next = inner_types;
3660         }
3661
3662         return first;
3663 end_error:
3664         return NULL;
3665 }
3666
3667 static type_t *construct_declarator_type(construct_type_t *construct_list,
3668                                          type_t *type)
3669 {
3670         construct_type_t *iter = construct_list;
3671         for( ; iter != NULL; iter = iter->next) {
3672                 switch(iter->kind) {
3673                 case CONSTRUCT_INVALID:
3674                         internal_errorf(HERE, "invalid type construction found");
3675                 case CONSTRUCT_FUNCTION: {
3676                         construct_function_type_t *construct_function_type
3677                                 = (construct_function_type_t*) iter;
3678
3679                         type_t *function_type = construct_function_type->function_type;
3680
3681                         function_type->function.return_type = type;
3682
3683                         type_t *skipped_return_type = skip_typeref(type);
3684                         if (is_type_function(skipped_return_type)) {
3685                                 errorf(HERE, "function returning function is not allowed");
3686                                 type = type_error_type;
3687                         } else if (is_type_array(skipped_return_type)) {
3688                                 errorf(HERE, "function returning array is not allowed");
3689                                 type = type_error_type;
3690                         } else {
3691                                 type = function_type;
3692                         }
3693                         break;
3694                 }
3695
3696                 case CONSTRUCT_POINTER: {
3697                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3698                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, &null_position);
3699                         pointer_type->pointer.points_to  = type;
3700                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
3701
3702                         type = pointer_type;
3703                         break;
3704                 }
3705
3706                 case CONSTRUCT_ARRAY: {
3707                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
3708                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, &null_position);
3709
3710                         expression_t *size_expression = parsed_array->size;
3711                         if(size_expression != NULL) {
3712                                 size_expression
3713                                         = create_implicit_cast(size_expression, type_size_t);
3714                         }
3715
3716                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
3717                         array_type->array.element_type    = type;
3718                         array_type->array.is_static       = parsed_array->is_static;
3719                         array_type->array.is_variable     = parsed_array->is_variable;
3720                         array_type->array.size_expression = size_expression;
3721
3722                         if(size_expression != NULL) {
3723                                 if(is_constant_expression(size_expression)) {
3724                                         array_type->array.size_constant = true;
3725                                         array_type->array.size
3726                                                 = fold_constant(size_expression);
3727                                 } else {
3728                                         array_type->array.is_vla = true;
3729                                 }
3730                         }
3731
3732                         type_t *skipped_type = skip_typeref(type);
3733                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3734                                 errorf(HERE, "array of void is not allowed");
3735                                 type = type_error_type;
3736                         } else {
3737                                 type = array_type;
3738                         }
3739                         break;
3740                 }
3741                 }
3742
3743                 type_t *hashed_type = typehash_insert(type);
3744                 if(hashed_type != type) {
3745                         /* the function type was constructed earlier freeing it here will
3746                          * destroy other types... */
3747                         if(iter->kind != CONSTRUCT_FUNCTION) {
3748                                 free_type(type);
3749                         }
3750                         type = hashed_type;
3751                 }
3752         }
3753
3754         return type;
3755 }
3756
3757 static declaration_t *parse_declarator(
3758                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3759 {
3760         declaration_t *const declaration    = allocate_declaration_zero();
3761         declaration->declared_storage_class = specifiers->declared_storage_class;
3762         declaration->modifiers              = specifiers->modifiers;
3763         declaration->deprecated             = specifiers->deprecated;
3764         declaration->deprecated_string      = specifiers->deprecated_string;
3765         declaration->get_property_sym       = specifiers->get_property_sym;
3766         declaration->put_property_sym       = specifiers->put_property_sym;
3767         declaration->is_inline              = specifiers->is_inline;
3768
3769         declaration->storage_class          = specifiers->declared_storage_class;
3770         if(declaration->storage_class == STORAGE_CLASS_NONE
3771                         && scope != global_scope) {
3772                 declaration->storage_class = STORAGE_CLASS_AUTO;
3773         }
3774
3775         if(specifiers->alignment != 0) {
3776                 /* TODO: add checks here */
3777                 declaration->alignment = specifiers->alignment;
3778         }
3779
3780         construct_type_t *construct_type
3781                 = parse_inner_declarator(declaration, may_be_abstract);
3782         type_t *const type = specifiers->type;
3783         declaration->type = construct_declarator_type(construct_type, type);
3784
3785         if(construct_type != NULL) {
3786                 obstack_free(&temp_obst, construct_type);
3787         }
3788
3789         return declaration;
3790 }
3791
3792 static type_t *parse_abstract_declarator(type_t *base_type)
3793 {
3794         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3795
3796         type_t *result = construct_declarator_type(construct_type, base_type);
3797         if(construct_type != NULL) {
3798                 obstack_free(&temp_obst, construct_type);
3799         }
3800
3801         return result;
3802 }
3803
3804 static declaration_t *append_declaration(declaration_t* const declaration)
3805 {
3806         if (last_declaration != NULL) {
3807                 last_declaration->next = declaration;
3808         } else {
3809                 scope->declarations = declaration;
3810         }
3811         last_declaration = declaration;
3812         return declaration;
3813 }
3814
3815 /**
3816  * Check if the declaration of main is suspicious.  main should be a
3817  * function with external linkage, returning int, taking either zero
3818  * arguments, two, or three arguments of appropriate types, ie.
3819  *
3820  * int main([ int argc, char **argv [, char **env ] ]).
3821  *
3822  * @param decl    the declaration to check
3823  * @param type    the function type of the declaration
3824  */
3825 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3826 {
3827         if (decl->storage_class == STORAGE_CLASS_STATIC) {
3828                 warningf(&decl->source_position,
3829                          "'main' is normally a non-static function");
3830         }
3831         if (skip_typeref(func_type->return_type) != type_int) {
3832                 warningf(&decl->source_position,
3833                          "return type of 'main' should be 'int', but is '%T'",
3834                          func_type->return_type);
3835         }
3836         const function_parameter_t *parm = func_type->parameters;
3837         if (parm != NULL) {
3838                 type_t *const first_type = parm->type;
3839                 if (!types_compatible(skip_typeref(first_type), type_int)) {
3840                         warningf(&decl->source_position,
3841                                  "first argument of 'main' should be 'int', but is '%T'", first_type);
3842                 }
3843                 parm = parm->next;
3844                 if (parm != NULL) {
3845                         type_t *const second_type = parm->type;
3846                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3847                                 warningf(&decl->source_position,
3848                                          "second argument of 'main' should be 'char**', but is '%T'", second_type);
3849                         }
3850                         parm = parm->next;
3851                         if (parm != NULL) {
3852                                 type_t *const third_type = parm->type;
3853                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3854                                         warningf(&decl->source_position,
3855                                                  "third argument of 'main' should be 'char**', but is '%T'", third_type);
3856                                 }
3857                                 parm = parm->next;
3858                                 if (parm != NULL) {
3859                                         warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3860                                 }
3861                         }
3862                 } else {
3863                         warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3864                 }
3865         }
3866 }
3867
3868 /**
3869  * Check if a symbol is the equal to "main".
3870  */
3871 static bool is_sym_main(const symbol_t *const sym)
3872 {
3873         return strcmp(sym->string, "main") == 0;
3874 }
3875
3876 static declaration_t *internal_record_declaration(
3877         declaration_t *const declaration,
3878         const bool is_function_definition)
3879 {
3880         const symbol_t *const symbol  = declaration->symbol;
3881         const namespace_t     namespc = (namespace_t)declaration->namespc;
3882
3883         assert(declaration->symbol != NULL);
3884         declaration_t *previous_declaration = get_declaration(symbol, namespc);
3885
3886         type_t *const orig_type = declaration->type;
3887         type_t *const type      = skip_typeref(orig_type);
3888         if (is_type_function(type) &&
3889                         type->function.unspecified_parameters &&
3890                         warning.strict_prototypes &&
3891                         previous_declaration == NULL) {
3892                 warningf(&declaration->source_position,
3893                          "function declaration '%#T' is not a prototype",
3894                          orig_type, declaration->symbol);
3895         }
3896
3897         if (is_function_definition && warning.main && is_sym_main(symbol)) {
3898                 check_type_of_main(declaration, &type->function);
3899         }
3900
3901         assert(declaration != previous_declaration);
3902         if (previous_declaration != NULL
3903                         && previous_declaration->parent_scope == scope) {
3904                 /* can happen for K&R style declarations */
3905                 if (previous_declaration->type == NULL) {
3906                         previous_declaration->type = declaration->type;
3907                 }
3908
3909                 const type_t *prev_type = skip_typeref(previous_declaration->type);
3910                 if (!types_compatible(type, prev_type)) {
3911                         errorf(&declaration->source_position,
3912                                    "declaration '%#T' is incompatible with '%#T' (declared %P)",
3913                                    orig_type, symbol, previous_declaration->type, symbol,
3914                                    &previous_declaration->source_position);
3915                 } else {
3916                         unsigned old_storage_class = previous_declaration->storage_class;
3917                         if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3918                                 errorf(&declaration->source_position,
3919                                            "redeclaration of enum entry '%Y' (declared %P)",
3920                                            symbol, &previous_declaration->source_position);
3921                                 return previous_declaration;
3922                         }
3923
3924                         unsigned new_storage_class = declaration->storage_class;
3925
3926                         if (is_type_incomplete(prev_type)) {
3927                                 previous_declaration->type = type;
3928                                 prev_type                  = type;
3929                         }
3930
3931                         /* pretend no storage class means extern for function
3932                          * declarations (except if the previous declaration is neither
3933                          * none nor extern) */
3934                         if (is_type_function(type)) {
3935                                 if (prev_type->function.unspecified_parameters) {
3936                                         previous_declaration->type = type;
3937                                         prev_type                  = type;
3938                                 }
3939
3940                                 switch (old_storage_class) {
3941                                 case STORAGE_CLASS_NONE:
3942                                         old_storage_class = STORAGE_CLASS_EXTERN;
3943
3944                                 case STORAGE_CLASS_EXTERN:
3945                                         if (is_function_definition) {
3946                                                 if (warning.missing_prototypes &&
3947                                                         prev_type->function.unspecified_parameters &&
3948                                                         !is_sym_main(symbol)) {
3949                                                         warningf(&declaration->source_position,
3950                                                                          "no previous prototype for '%#T'",
3951                                                                          orig_type, symbol);
3952                                                 }
3953                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
3954                                                 new_storage_class = STORAGE_CLASS_EXTERN;
3955                                         }
3956                                         break;
3957
3958                                 default:
3959                                         break;
3960                                 }
3961                         }
3962
3963                         if (old_storage_class == STORAGE_CLASS_EXTERN &&
3964                                         new_storage_class == STORAGE_CLASS_EXTERN) {
3965 warn_redundant_declaration:
3966                                 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
3967                                         warningf(&declaration->source_position,
3968                                                          "redundant declaration for '%Y' (declared %P)",
3969                                                          symbol, &previous_declaration->source_position);
3970                                 }
3971                         } else if (current_function == NULL) {
3972                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
3973                                                 new_storage_class == STORAGE_CLASS_STATIC) {
3974                                         errorf(&declaration->source_position,
3975                                                    "static declaration of '%Y' follows non-static declaration (declared %P)",
3976                                                    symbol, &previous_declaration->source_position);
3977                                 } else if (old_storage_class != STORAGE_CLASS_EXTERN
3978                                                 && !is_function_definition) {
3979                                         goto warn_redundant_declaration;
3980                                 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3981                                                 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3982                                                 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3983                                 }
3984                         } else if (old_storage_class == new_storage_class) {
3985                                 errorf(&declaration->source_position,
3986                                            "redeclaration of '%Y' (declared %P)",
3987                                            symbol, &previous_declaration->source_position);
3988                         } else {
3989                                 errorf(&declaration->source_position,
3990                                            "redeclaration of '%Y' with different linkage (declared %P)",
3991                                            symbol, &previous_declaration->source_position);
3992                         }
3993                 }
3994
3995                 if (declaration->is_inline)
3996                         previous_declaration->is_inline = true;
3997                 return previous_declaration;
3998         } else if (is_function_definition) {
3999                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4000                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
4001                                 warningf(&declaration->source_position,
4002                                          "no previous prototype for '%#T'", orig_type, symbol);
4003                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4004                                 warningf(&declaration->source_position,
4005                                          "no previous declaration for '%#T'", orig_type,
4006                                          symbol);
4007                         }
4008                 }
4009         } else if (warning.missing_declarations &&
4010             scope == global_scope &&
4011             !is_type_function(type) && (
4012               declaration->storage_class == STORAGE_CLASS_NONE ||
4013               declaration->storage_class == STORAGE_CLASS_THREAD
4014             )) {
4015                 warningf(&declaration->source_position,
4016                          "no previous declaration for '%#T'", orig_type, symbol);
4017         }
4018
4019         assert(declaration->parent_scope == NULL);
4020         assert(scope != NULL);
4021
4022         declaration->parent_scope = scope;
4023
4024         environment_push(declaration);
4025         return append_declaration(declaration);
4026 }
4027
4028 static declaration_t *record_declaration(declaration_t *declaration)
4029 {
4030         return internal_record_declaration(declaration, false);
4031 }
4032
4033 static declaration_t *record_function_definition(declaration_t *declaration)
4034 {
4035         return internal_record_declaration(declaration, true);
4036 }
4037
4038 static void parser_error_multiple_definition(declaration_t *declaration,
4039                 const source_position_t *source_position)
4040 {
4041         errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4042                declaration->symbol, &declaration->source_position);
4043 }
4044
4045 static bool is_declaration_specifier(const token_t *token,
4046                                      bool only_specifiers_qualifiers)
4047 {
4048         switch(token->type) {
4049                 TYPE_SPECIFIERS
4050                 TYPE_QUALIFIERS
4051                         return true;
4052                 case T_IDENTIFIER:
4053                         return is_typedef_symbol(token->v.symbol);
4054
4055                 case T___extension__:
4056                 STORAGE_CLASSES
4057                         return !only_specifiers_qualifiers;
4058
4059                 default:
4060                         return false;
4061         }
4062 }
4063
4064 static void parse_init_declarator_rest(declaration_t *declaration)
4065 {
4066         eat('=');
4067
4068         type_t *orig_type = declaration->type;
4069         type_t *type      = skip_typeref(orig_type);
4070
4071         if(declaration->init.initializer != NULL) {
4072                 parser_error_multiple_definition(declaration, HERE);
4073         }
4074
4075         bool must_be_constant = false;
4076         if(declaration->storage_class == STORAGE_CLASS_STATIC
4077                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4078                         || declaration->parent_scope == global_scope) {
4079                 must_be_constant = true;
4080         }
4081
4082         parse_initializer_env_t env;
4083         env.type             = orig_type;
4084         env.must_be_constant = must_be_constant;
4085         env.declaration      = declaration;
4086
4087         initializer_t *initializer = parse_initializer(&env);
4088
4089         if(env.type != orig_type) {
4090                 orig_type         = env.type;
4091                 type              = skip_typeref(orig_type);
4092                 declaration->type = env.type;
4093         }
4094
4095         if(is_type_function(type)) {
4096                 errorf(&declaration->source_position,
4097                        "initializers not allowed for function types at declator '%Y' (type '%T')",
4098                        declaration->symbol, orig_type);
4099         } else {
4100                 declaration->init.initializer = initializer;
4101         }
4102 }
4103
4104 /* parse rest of a declaration without any declarator */
4105 static void parse_anonymous_declaration_rest(
4106                 const declaration_specifiers_t *specifiers,
4107                 parsed_declaration_func finished_declaration)
4108 {
4109         eat(';');
4110
4111         declaration_t *const declaration    = allocate_declaration_zero();
4112         declaration->type                   = specifiers->type;
4113         declaration->declared_storage_class = specifiers->declared_storage_class;
4114         declaration->source_position        = specifiers->source_position;
4115         declaration->modifiers              = specifiers->modifiers;
4116
4117         if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4118                 warningf(&declaration->source_position,
4119                          "useless storage class in empty declaration");
4120         }
4121         declaration->storage_class = STORAGE_CLASS_NONE;
4122
4123         type_t *type = declaration->type;
4124         switch (type->kind) {
4125                 case TYPE_COMPOUND_STRUCT:
4126                 case TYPE_COMPOUND_UNION: {
4127                         if (type->compound.declaration->symbol == NULL) {
4128                                 warningf(&declaration->source_position,
4129                                          "unnamed struct/union that defines no instances");
4130                         }
4131                         break;
4132                 }
4133
4134                 case TYPE_ENUM:
4135                         break;
4136
4137                 default:
4138                         warningf(&declaration->source_position, "empty declaration");
4139                         break;
4140         }
4141
4142         finished_declaration(declaration);
4143 }
4144
4145 static void parse_declaration_rest(declaration_t *ndeclaration,
4146                 const declaration_specifiers_t *specifiers,
4147                 parsed_declaration_func finished_declaration)
4148 {
4149         add_anchor_token(';');
4150         add_anchor_token('=');
4151         add_anchor_token(',');
4152         while(true) {
4153                 declaration_t *declaration = finished_declaration(ndeclaration);
4154
4155                 type_t *orig_type = declaration->type;
4156                 type_t *type      = skip_typeref(orig_type);
4157
4158                 if (type->kind != TYPE_FUNCTION &&
4159                     declaration->is_inline &&
4160                     is_type_valid(type)) {
4161                         warningf(&declaration->source_position,
4162                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
4163                 }
4164
4165                 if(token.type == '=') {
4166                         parse_init_declarator_rest(declaration);
4167                 }
4168
4169                 if(token.type != ',')
4170                         break;
4171                 eat(',');
4172
4173                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4174         }
4175         expect(';');
4176
4177 end_error:
4178         rem_anchor_token(';');
4179         rem_anchor_token('=');
4180         rem_anchor_token(',');
4181 }
4182
4183 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4184 {
4185         symbol_t *symbol  = declaration->symbol;
4186         if(symbol == NULL) {
4187                 errorf(HERE, "anonymous declaration not valid as function parameter");
4188                 return declaration;
4189         }
4190         namespace_t namespc = (namespace_t) declaration->namespc;
4191         if(namespc != NAMESPACE_NORMAL) {
4192                 return record_declaration(declaration);
4193         }
4194
4195         declaration_t *previous_declaration = get_declaration(symbol, namespc);
4196         if(previous_declaration == NULL ||
4197                         previous_declaration->parent_scope != scope) {
4198                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4199                        symbol);
4200                 return declaration;
4201         }
4202
4203         if(previous_declaration->type == NULL) {
4204                 previous_declaration->type          = declaration->type;
4205                 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4206                 previous_declaration->storage_class = declaration->storage_class;
4207                 previous_declaration->parent_scope  = scope;
4208                 return previous_declaration;
4209         } else {
4210                 return record_declaration(declaration);
4211         }
4212 }
4213
4214 static void parse_declaration(parsed_declaration_func finished_declaration)
4215 {
4216         declaration_specifiers_t specifiers;
4217         memset(&specifiers, 0, sizeof(specifiers));
4218         parse_declaration_specifiers(&specifiers);
4219
4220         if(token.type == ';') {
4221                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4222         } else {
4223                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4224                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4225         }
4226 }
4227
4228 static type_t *get_default_promoted_type(type_t *orig_type)
4229 {
4230         type_t *result = orig_type;
4231
4232         type_t *type = skip_typeref(orig_type);
4233         if(is_type_integer(type)) {
4234                 result = promote_integer(type);
4235         } else if(type == type_float) {
4236                 result = type_double;
4237         }
4238
4239         return result;
4240 }
4241
4242 static void parse_kr_declaration_list(declaration_t *declaration)
4243 {
4244         type_t *type = skip_typeref(declaration->type);
4245         if (!is_type_function(type))
4246                 return;
4247
4248         if (!type->function.kr_style_parameters)
4249                 return;
4250
4251         /* push function parameters */
4252         int       top        = environment_top();
4253         scope_t  *last_scope = scope;
4254         set_scope(&declaration->scope);
4255
4256         declaration_t *parameter = declaration->scope.declarations;
4257         for ( ; parameter != NULL; parameter = parameter->next) {
4258                 assert(parameter->parent_scope == NULL);
4259                 parameter->parent_scope = scope;
4260                 environment_push(parameter);
4261         }
4262
4263         /* parse declaration list */
4264         while (is_declaration_specifier(&token, false)) {
4265                 parse_declaration(finished_kr_declaration);
4266         }
4267
4268         /* pop function parameters */
4269         assert(scope == &declaration->scope);
4270         set_scope(last_scope);
4271         environment_pop_to(top);
4272
4273         /* update function type */
4274         type_t *new_type = duplicate_type(type);
4275
4276         function_parameter_t *parameters     = NULL;
4277         function_parameter_t *last_parameter = NULL;
4278
4279         declaration_t *parameter_declaration = declaration->scope.declarations;
4280         for( ; parameter_declaration != NULL;
4281                         parameter_declaration = parameter_declaration->next) {
4282                 type_t *parameter_type = parameter_declaration->type;
4283                 if(parameter_type == NULL) {
4284                         if (strict_mode) {
4285                                 errorf(HERE, "no type specified for function parameter '%Y'",
4286                                        parameter_declaration->symbol);
4287                         } else {
4288                                 if (warning.implicit_int) {
4289                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4290                                                 parameter_declaration->symbol);
4291                                 }
4292                                 parameter_type              = type_int;
4293                                 parameter_declaration->type = parameter_type;
4294                         }
4295                 }
4296
4297                 semantic_parameter(parameter_declaration);
4298                 parameter_type = parameter_declaration->type;
4299
4300                 /*
4301                  * we need the default promoted types for the function type
4302                  */
4303                 parameter_type = get_default_promoted_type(parameter_type);
4304
4305                 function_parameter_t *function_parameter
4306                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4307                 memset(function_parameter, 0, sizeof(function_parameter[0]));
4308
4309                 function_parameter->type = parameter_type;
4310                 if(last_parameter != NULL) {
4311                         last_parameter->next = function_parameter;
4312                 } else {
4313                         parameters = function_parameter;
4314                 }
4315                 last_parameter = function_parameter;
4316         }
4317
4318         /* Â§ 6.9.1.7: A K&R style parameter list does NOT act as a function
4319          * prototype */
4320         new_type->function.parameters             = parameters;
4321         new_type->function.unspecified_parameters = true;
4322
4323         type = typehash_insert(new_type);
4324         if(type != new_type) {
4325                 obstack_free(type_obst, new_type);
4326         }
4327
4328         declaration->type = type;
4329 }
4330
4331 static bool first_err = true;
4332
4333 /**
4334  * When called with first_err set, prints the name of the current function,
4335  * else does noting.
4336  */
4337 static void print_in_function(void) {
4338         if (first_err) {
4339                 first_err = false;
4340                 diagnosticf("%s: In function '%Y':\n",
4341                         current_function->source_position.input_name,
4342                         current_function->symbol);
4343         }
4344 }
4345
4346 /**
4347  * Check if all labels are defined in the current function.
4348  * Check if all labels are used in the current function.
4349  */
4350 static void check_labels(void)
4351 {
4352         for (const goto_statement_t *goto_statement = goto_first;
4353             goto_statement != NULL;
4354             goto_statement = goto_statement->next) {
4355                 declaration_t *label = goto_statement->label;
4356
4357                 label->used = true;
4358                 if (label->source_position.input_name == NULL) {
4359                         print_in_function();
4360                         errorf(&goto_statement->base.source_position,
4361                                "label '%Y' used but not defined", label->symbol);
4362                  }
4363         }
4364         goto_first = goto_last = NULL;
4365
4366         if (warning.unused_label) {
4367                 for (const label_statement_t *label_statement = label_first;
4368                          label_statement != NULL;
4369                          label_statement = label_statement->next) {
4370                         const declaration_t *label = label_statement->label;
4371
4372                         if (! label->used) {
4373                                 print_in_function();
4374                                 warningf(&label_statement->base.source_position,
4375                                         "label '%Y' defined but not used", label->symbol);
4376                         }
4377                 }
4378         }
4379         label_first = label_last = NULL;
4380 }
4381
4382 /**
4383  * Check declarations of current_function for unused entities.
4384  */
4385 static void check_declarations(void)
4386 {
4387         if (warning.unused_parameter) {
4388                 const scope_t *scope = &current_function->scope;
4389
4390                 const declaration_t *parameter = scope->declarations;
4391                 for (; parameter != NULL; parameter = parameter->next) {
4392                         if (! parameter->used) {
4393                                 print_in_function();
4394                                 warningf(&parameter->source_position,
4395                                          "unused parameter '%Y'", parameter->symbol);
4396                         }
4397                 }
4398         }
4399         if (warning.unused_variable) {
4400         }
4401 }
4402
4403 static void parse_external_declaration(void)
4404 {
4405         /* function-definitions and declarations both start with declaration
4406          * specifiers */
4407         declaration_specifiers_t specifiers;
4408         memset(&specifiers, 0, sizeof(specifiers));
4409
4410         add_anchor_token(';');
4411         parse_declaration_specifiers(&specifiers);
4412         rem_anchor_token(';');
4413
4414         /* must be a declaration */
4415         if(token.type == ';') {
4416                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4417                 return;
4418         }
4419
4420         add_anchor_token(',');
4421         add_anchor_token('=');
4422         rem_anchor_token(';');
4423
4424         /* declarator is common to both function-definitions and declarations */
4425         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4426
4427         rem_anchor_token(',');
4428         rem_anchor_token('=');
4429         rem_anchor_token(';');
4430
4431         /* must be a declaration */
4432         if(token.type == ',' || token.type == '=' || token.type == ';') {
4433                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4434                 return;
4435         }
4436
4437         /* must be a function definition */
4438         parse_kr_declaration_list(ndeclaration);
4439
4440         if(token.type != '{') {
4441                 parse_error_expected("while parsing function definition", '{', NULL);
4442                 eat_until_matching_token(';');
4443                 return;
4444         }
4445
4446         type_t *type = ndeclaration->type;
4447
4448         /* note that we don't skip typerefs: the standard doesn't allow them here
4449          * (so we can't use is_type_function here) */
4450         if(type->kind != TYPE_FUNCTION) {
4451                 if (is_type_valid(type)) {
4452                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
4453                                type, ndeclaration->symbol);
4454                 }
4455                 eat_block();
4456                 return;
4457         }
4458
4459         /* Â§ 6.7.5.3 (14) a function definition with () means no
4460          * parameters (and not unspecified parameters) */
4461         if(type->function.unspecified_parameters
4462                         && type->function.parameters == NULL
4463                         && !type->function.kr_style_parameters) {
4464                 type_t *duplicate = duplicate_type(type);
4465                 duplicate->function.unspecified_parameters = false;
4466
4467                 type = typehash_insert(duplicate);
4468                 if(type != duplicate) {
4469                         obstack_free(type_obst, duplicate);
4470                 }
4471                 ndeclaration->type = type;
4472         }
4473
4474         declaration_t *const declaration = record_function_definition(ndeclaration);
4475         if(ndeclaration != declaration) {
4476                 declaration->scope = ndeclaration->scope;
4477         }
4478         type = skip_typeref(declaration->type);
4479
4480         /* push function parameters and switch scope */
4481         int       top        = environment_top();
4482         scope_t  *last_scope = scope;
4483         set_scope(&declaration->scope);
4484
4485         declaration_t *parameter = declaration->scope.declarations;
4486         for( ; parameter != NULL; parameter = parameter->next) {
4487                 if(parameter->parent_scope == &ndeclaration->scope) {
4488                         parameter->parent_scope = scope;
4489                 }
4490                 assert(parameter->parent_scope == NULL
4491                                 || parameter->parent_scope == scope);
4492                 parameter->parent_scope = scope;
4493                 environment_push(parameter);
4494         }
4495
4496         if(declaration->init.statement != NULL) {
4497                 parser_error_multiple_definition(declaration, HERE);
4498                 eat_block();
4499                 goto end_of_parse_external_declaration;
4500         } else {
4501                 /* parse function body */
4502                 int            label_stack_top      = label_top();
4503                 declaration_t *old_current_function = current_function;
4504                 current_function                    = declaration;
4505
4506                 declaration->init.statement = parse_compound_statement(false);
4507                 first_err = true;
4508                 check_labels();
4509                 check_declarations();
4510
4511                 assert(current_function == declaration);
4512                 current_function = old_current_function;
4513                 label_pop_to(label_stack_top);
4514         }
4515
4516 end_of_parse_external_declaration:
4517         assert(scope == &declaration->scope);
4518         set_scope(last_scope);
4519         environment_pop_to(top);
4520 }
4521
4522 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4523                                   source_position_t *source_position)
4524 {
4525         type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4526
4527         type->bitfield.base_type = base_type;
4528         type->bitfield.size      = size;
4529
4530         return type;
4531 }
4532
4533 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4534                                           symbol_t *symbol)
4535 {
4536         declaration_t *iter = compound_declaration->scope.declarations;
4537         for( ; iter != NULL; iter = iter->next) {
4538                 if(iter->namespc != NAMESPACE_NORMAL)
4539                         continue;
4540
4541                 if(iter->symbol == NULL) {
4542                         type_t *type = skip_typeref(iter->type);
4543                         if(is_type_compound(type)) {
4544                                 declaration_t *result
4545                                         = find_compound_entry(type->compound.declaration, symbol);
4546                                 if(result != NULL)
4547                                         return result;
4548                         }
4549                         continue;
4550                 }
4551
4552                 if(iter->symbol == symbol) {
4553                         return iter;
4554                 }
4555         }
4556
4557         return NULL;
4558 }
4559
4560 static void parse_compound_declarators(declaration_t *struct_declaration,
4561                 const declaration_specifiers_t *specifiers)
4562 {
4563         declaration_t *last_declaration = struct_declaration->scope.declarations;
4564         if(last_declaration != NULL) {
4565                 while(last_declaration->next != NULL) {
4566                         last_declaration = last_declaration->next;
4567                 }
4568         }
4569
4570         while(1) {
4571                 declaration_t *declaration;
4572
4573                 if(token.type == ':') {
4574                         source_position_t source_position = *HERE;
4575                         next_token();
4576
4577                         type_t *base_type = specifiers->type;
4578                         expression_t *size = parse_constant_expression();
4579
4580                         if(!is_type_integer(skip_typeref(base_type))) {
4581                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
4582                                        base_type);
4583                         }
4584
4585                         type_t *type = make_bitfield_type(base_type, size, &source_position);
4586
4587                         declaration                         = allocate_declaration_zero();
4588                         declaration->namespc                = NAMESPACE_NORMAL;
4589                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
4590                         declaration->storage_class          = STORAGE_CLASS_NONE;
4591                         declaration->source_position        = source_position;
4592                         declaration->modifiers              = specifiers->modifiers;
4593                         declaration->type                   = type;
4594                 } else {
4595                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4596
4597                         type_t *orig_type = declaration->type;
4598                         type_t *type      = skip_typeref(orig_type);
4599
4600                         if(token.type == ':') {
4601                                 source_position_t source_position = *HERE;
4602                                 next_token();
4603                                 expression_t *size = parse_constant_expression();
4604
4605                                 if(!is_type_integer(type)) {
4606                                         errorf(HERE, "bitfield base type '%T' is not an "
4607                                                "integer type", orig_type);
4608                                 }
4609
4610                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4611                                 declaration->type = bitfield_type;
4612                         } else {
4613                                 /* TODO we ignore arrays for now... what is missing is a check
4614                                  * that they're at the end of the struct */
4615                                 if(is_type_incomplete(type) && !is_type_array(type)) {
4616                                         errorf(HERE,
4617                                                "compound member '%Y' has incomplete type '%T'",
4618                                                declaration->symbol, orig_type);
4619                                 } else if(is_type_function(type)) {
4620                                         errorf(HERE, "compound member '%Y' must not have function "
4621                                                "type '%T'", declaration->symbol, orig_type);
4622                                 }
4623                         }
4624                 }
4625
4626                 /* make sure we don't define a symbol multiple times */
4627                 symbol_t *symbol = declaration->symbol;
4628                 if(symbol != NULL) {
4629                         declaration_t *prev_decl
4630                                 = find_compound_entry(struct_declaration, symbol);
4631
4632                         if(prev_decl != NULL) {
4633                                 assert(prev_decl->symbol == symbol);
4634                                 errorf(&declaration->source_position,
4635                                        "multiple declarations of symbol '%Y' (declared %P)",
4636                                        symbol, &prev_decl->source_position);
4637                         }
4638                 }
4639
4640                 /* append declaration */
4641                 if(last_declaration != NULL) {
4642                         last_declaration->next = declaration;
4643                 } else {
4644                         struct_declaration->scope.declarations = declaration;
4645                 }
4646                 last_declaration = declaration;
4647
4648                 if(token.type != ',')
4649                         break;
4650                 next_token();
4651         }
4652         expect(';');
4653
4654 end_error:
4655         ;
4656 }
4657
4658 static void parse_compound_type_entries(declaration_t *compound_declaration)
4659 {
4660         eat('{');
4661         add_anchor_token('}');
4662
4663         while(token.type != '}' && token.type != T_EOF) {
4664                 declaration_specifiers_t specifiers;
4665                 memset(&specifiers, 0, sizeof(specifiers));
4666                 parse_declaration_specifiers(&specifiers);
4667
4668                 parse_compound_declarators(compound_declaration, &specifiers);
4669         }
4670         rem_anchor_token('}');
4671
4672         if(token.type == T_EOF) {
4673                 errorf(HERE, "EOF while parsing struct");
4674         }
4675         next_token();
4676 }
4677
4678 static type_t *parse_typename(void)
4679 {
4680         declaration_specifiers_t specifiers;
4681         memset(&specifiers, 0, sizeof(specifiers));
4682         parse_declaration_specifiers(&specifiers);
4683         if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4684                 /* TODO: improve error message, user does probably not know what a
4685                  * storage class is...
4686                  */
4687                 errorf(HERE, "typename may not have a storage class");
4688         }
4689
4690         type_t *result = parse_abstract_declarator(specifiers.type);
4691
4692         return result;
4693 }
4694
4695
4696
4697
4698 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4699 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4700                                                           expression_t *left);
4701
4702 typedef struct expression_parser_function_t expression_parser_function_t;
4703 struct expression_parser_function_t {
4704         unsigned                         precedence;
4705         parse_expression_function        parser;
4706         unsigned                         infix_precedence;
4707         parse_expression_infix_function  infix_parser;
4708 };
4709
4710 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4711
4712 /**
4713  * Prints an error message if an expression was expected but not read
4714  */
4715 static expression_t *expected_expression_error(void)
4716 {
4717         /* skip the error message if the error token was read */
4718         if (token.type != T_ERROR) {
4719                 errorf(HERE, "expected expression, got token '%K'", &token);
4720         }
4721         next_token();
4722
4723         return create_invalid_expression();
4724 }
4725
4726 /**
4727  * Parse a string constant.
4728  */
4729 static expression_t *parse_string_const(void)
4730 {
4731         wide_string_t wres;
4732         if (token.type == T_STRING_LITERAL) {
4733                 string_t res = token.v.string;
4734                 next_token();
4735                 while (token.type == T_STRING_LITERAL) {
4736                         res = concat_strings(&res, &token.v.string);
4737                         next_token();
4738                 }
4739                 if (token.type != T_WIDE_STRING_LITERAL) {
4740                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4741                         /* note: that we use type_char_ptr here, which is already the
4742                          * automatic converted type. revert_automatic_type_conversion
4743                          * will construct the array type */
4744                         cnst->base.type    = type_char_ptr;
4745                         cnst->string.value = res;
4746                         return cnst;
4747                 }
4748
4749                 wres = concat_string_wide_string(&res, &token.v.wide_string);
4750         } else {
4751                 wres = token.v.wide_string;
4752         }
4753         next_token();
4754
4755         for (;;) {
4756                 switch (token.type) {
4757                         case T_WIDE_STRING_LITERAL:
4758                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
4759                                 break;
4760
4761                         case T_STRING_LITERAL:
4762                                 wres = concat_wide_string_string(&wres, &token.v.string);
4763                                 break;
4764
4765                         default: {
4766                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4767                                 cnst->base.type         = type_wchar_t_ptr;
4768                                 cnst->wide_string.value = wres;
4769                                 return cnst;
4770                         }
4771                 }
4772                 next_token();
4773         }
4774 }
4775
4776 /**
4777  * Parse an integer constant.
4778  */
4779 static expression_t *parse_int_const(void)
4780 {
4781         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
4782         cnst->base.source_position = *HERE;
4783         cnst->base.type            = token.datatype;
4784         cnst->conste.v.int_value   = token.v.intvalue;
4785
4786         next_token();
4787
4788         return cnst;
4789 }
4790
4791 /**
4792  * Parse a character constant.
4793  */
4794 static expression_t *parse_character_constant(void)
4795 {
4796         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4797
4798         cnst->base.source_position = *HERE;
4799         cnst->base.type            = token.datatype;
4800         cnst->conste.v.character   = token.v.string;
4801
4802         if (cnst->conste.v.character.size != 1) {
4803                 if (warning.multichar && (c_mode & _GNUC)) {
4804                         /* TODO */
4805                         warningf(HERE, "multi-character character constant");
4806                 } else {
4807                         errorf(HERE, "more than 1 characters in character constant");
4808                 }
4809         }
4810         next_token();
4811
4812         return cnst;
4813 }
4814
4815 /**
4816  * Parse a wide character constant.
4817  */
4818 static expression_t *parse_wide_character_constant(void)
4819 {
4820         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4821
4822         cnst->base.source_position    = *HERE;
4823         cnst->base.type               = token.datatype;
4824         cnst->conste.v.wide_character = token.v.wide_string;
4825
4826         if (cnst->conste.v.wide_character.size != 1) {
4827                 if (warning.multichar && (c_mode & _GNUC)) {
4828                         /* TODO */
4829                         warningf(HERE, "multi-character character constant");
4830                 } else {
4831                         errorf(HERE, "more than 1 characters in character constant");
4832                 }
4833         }
4834         next_token();
4835
4836         return cnst;
4837 }
4838
4839 /**
4840  * Parse a float constant.
4841  */
4842 static expression_t *parse_float_const(void)
4843 {
4844         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
4845         cnst->base.type            = token.datatype;
4846         cnst->conste.v.float_value = token.v.floatvalue;
4847
4848         next_token();
4849
4850         return cnst;
4851 }
4852
4853 static declaration_t *create_implicit_function(symbol_t *symbol,
4854                 const source_position_t *source_position)
4855 {
4856         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
4857         ntype->function.return_type            = type_int;
4858         ntype->function.unspecified_parameters = true;
4859
4860         type_t *type = typehash_insert(ntype);
4861         if(type != ntype) {
4862                 free_type(ntype);
4863         }
4864
4865         declaration_t *const declaration    = allocate_declaration_zero();
4866         declaration->storage_class          = STORAGE_CLASS_EXTERN;
4867         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4868         declaration->type                   = type;
4869         declaration->symbol                 = symbol;
4870         declaration->source_position        = *source_position;
4871
4872         bool strict_prototypes_old = warning.strict_prototypes;
4873         warning.strict_prototypes  = false;
4874         record_declaration(declaration);
4875         warning.strict_prototypes = strict_prototypes_old;
4876
4877         return declaration;
4878 }
4879
4880 /**
4881  * Creates a return_type (func)(argument_type) function type if not
4882  * already exists.
4883  *
4884  * @param return_type    the return type
4885  * @param argument_type  the argument type
4886  */
4887 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4888 {
4889         function_parameter_t *parameter
4890                 = obstack_alloc(type_obst, sizeof(parameter[0]));
4891         memset(parameter, 0, sizeof(parameter[0]));
4892         parameter->type = argument_type;
4893
4894         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4895         type->function.return_type = return_type;
4896         type->function.parameters  = parameter;
4897
4898         type_t *result = typehash_insert(type);
4899         if(result != type) {
4900                 free_type(type);
4901         }
4902
4903         return result;
4904 }
4905
4906 static type_t *make_function_0_type(type_t *return_type)
4907 {
4908         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
4909         type->function.return_type = return_type;
4910         type->function.parameters  = NULL;
4911
4912         type_t *result = typehash_insert(type);
4913         if(result != type) {
4914                 free_type(type);
4915         }
4916
4917         return result;
4918 }
4919
4920 /**
4921  * Creates a function type for some function like builtins.
4922  *
4923  * @param symbol   the symbol describing the builtin
4924  */
4925 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4926 {
4927         switch(symbol->ID) {
4928         case T___builtin_alloca:
4929                 return make_function_1_type(type_void_ptr, type_size_t);
4930         case T___builtin_huge_val:
4931                 return make_function_0_type(type_double);
4932         case T___builtin_nan:
4933                 return make_function_1_type(type_double, type_char_ptr);
4934         case T___builtin_nanf:
4935                 return make_function_1_type(type_float, type_char_ptr);
4936         case T___builtin_nand:
4937                 return make_function_1_type(type_long_double, type_char_ptr);
4938         case T___builtin_va_end:
4939                 return make_function_1_type(type_void, type_valist);
4940         default:
4941                 internal_errorf(HERE, "not implemented builtin symbol found");
4942         }
4943 }
4944
4945 /**
4946  * Performs automatic type cast as described in Â§ 6.3.2.1.
4947  *
4948  * @param orig_type  the original type
4949  */
4950 static type_t *automatic_type_conversion(type_t *orig_type)
4951 {
4952         type_t *type = skip_typeref(orig_type);
4953         if(is_type_array(type)) {
4954                 array_type_t *array_type   = &type->array;
4955                 type_t       *element_type = array_type->element_type;
4956                 unsigned      qualifiers   = array_type->base.qualifiers;
4957
4958                 return make_pointer_type(element_type, qualifiers);
4959         }
4960
4961         if(is_type_function(type)) {
4962                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4963         }
4964
4965         return orig_type;
4966 }
4967
4968 /**
4969  * reverts the automatic casts of array to pointer types and function
4970  * to function-pointer types as defined Â§ 6.3.2.1
4971  */
4972 type_t *revert_automatic_type_conversion(const expression_t *expression)
4973 {
4974         switch (expression->kind) {
4975                 case EXPR_REFERENCE: return expression->reference.declaration->type;
4976                 case EXPR_SELECT:    return expression->select.compound_entry->type;
4977
4978                 case EXPR_UNARY_DEREFERENCE: {
4979                         const expression_t *const value = expression->unary.value;
4980                         type_t             *const type  = skip_typeref(value->base.type);
4981                         assert(is_type_pointer(type));
4982                         return type->pointer.points_to;
4983                 }
4984
4985                 case EXPR_BUILTIN_SYMBOL:
4986                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4987
4988                 case EXPR_ARRAY_ACCESS: {
4989                         const expression_t *array_ref = expression->array_access.array_ref;
4990                         type_t             *type_left = skip_typeref(array_ref->base.type);
4991                         if (!is_type_valid(type_left))
4992                                 return type_left;
4993                         assert(is_type_pointer(type_left));
4994                         return type_left->pointer.points_to;
4995                 }
4996
4997                 case EXPR_STRING_LITERAL: {
4998                         size_t size = expression->string.value.size;
4999                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5000                 }
5001
5002                 case EXPR_WIDE_STRING_LITERAL: {
5003                         size_t size = expression->wide_string.value.size;
5004                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5005                 }
5006
5007                 case EXPR_COMPOUND_LITERAL:
5008                         return expression->compound_literal.type;
5009
5010                 default: break;
5011         }
5012
5013         return expression->base.type;
5014 }
5015
5016 static expression_t *parse_reference(void)
5017 {
5018         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5019
5020         reference_expression_t *ref = &expression->reference;
5021         symbol_t *const symbol = token.v.symbol;
5022
5023         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5024
5025         source_position_t source_position = token.source_position;
5026         next_token();
5027
5028         if(declaration == NULL) {
5029                 if (! strict_mode && token.type == '(') {
5030                         /* an implicitly defined function */
5031                         if (warning.implicit_function_declaration) {
5032                                 warningf(HERE, "implicit declaration of function '%Y'",
5033                                         symbol);
5034                         }
5035
5036                         declaration = create_implicit_function(symbol,
5037                                                                &source_position);
5038                 } else {
5039                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
5040                         return create_invalid_expression();
5041                 }
5042         }
5043
5044         type_t *type         = declaration->type;
5045
5046         /* we always do the auto-type conversions; the & and sizeof parser contains
5047          * code to revert this! */
5048         type = automatic_type_conversion(type);
5049
5050         ref->declaration = declaration;
5051         ref->base.type   = type;
5052
5053         /* this declaration is used */
5054         declaration->used = true;
5055
5056         /* check for deprecated functions */
5057         if(declaration->deprecated != 0) {
5058                 const char *prefix = "";
5059                 if (is_type_function(declaration->type))
5060                         prefix = "function ";
5061
5062                 if (declaration->deprecated_string != NULL) {
5063                         warningf(&source_position,
5064                                 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5065                                 declaration->deprecated_string);
5066                 } else {
5067                         warningf(&source_position,
5068                                 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5069                 }
5070         }
5071
5072         return expression;
5073 }
5074
5075 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5076 {
5077         (void) expression;
5078         (void) dest_type;
5079         /* TODO check if explicit cast is allowed and issue warnings/errors */
5080 }
5081
5082 static expression_t *parse_compound_literal(type_t *type)
5083 {
5084         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5085
5086         parse_initializer_env_t env;
5087         env.type             = type;
5088         env.declaration      = NULL;
5089         env.must_be_constant = false;
5090         initializer_t *initializer = parse_initializer(&env);
5091         type = env.type;
5092
5093         expression->compound_literal.initializer = initializer;
5094         expression->compound_literal.type        = type;
5095         expression->base.type                    = automatic_type_conversion(type);
5096
5097         return expression;
5098 }
5099
5100 /**
5101  * Parse a cast expression.
5102  */
5103 static expression_t *parse_cast(void)
5104 {
5105         source_position_t source_position = token.source_position;
5106
5107         type_t *type  = parse_typename();
5108
5109         /* matching add_anchor_token() is at call site */
5110         rem_anchor_token(')');
5111         expect(')');
5112
5113         if(token.type == '{') {
5114                 return parse_compound_literal(type);
5115         }
5116
5117         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5118         cast->base.source_position = source_position;
5119
5120         expression_t *value = parse_sub_expression(20);
5121
5122         check_cast_allowed(value, type);
5123
5124         cast->base.type   = type;
5125         cast->unary.value = value;
5126
5127         return cast;
5128 end_error:
5129         return create_invalid_expression();
5130 }
5131
5132 /**
5133  * Parse a statement expression.
5134  */
5135 static expression_t *parse_statement_expression(void)
5136 {
5137         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5138
5139         statement_t *statement           = parse_compound_statement(true);
5140         expression->statement.statement  = statement;
5141         expression->base.source_position = statement->base.source_position;
5142
5143         /* find last statement and use its type */
5144         type_t *type = type_void;
5145         const statement_t *stmt = statement->compound.statements;
5146         if (stmt != NULL) {
5147                 while (stmt->base.next != NULL)
5148                         stmt = stmt->base.next;
5149
5150                 if (stmt->kind == STATEMENT_EXPRESSION) {
5151                         type = stmt->expression.expression->base.type;
5152                 }
5153         } else {
5154                 warningf(&expression->base.source_position, "empty statement expression ({})");
5155         }
5156         expression->base.type = type;
5157
5158         expect(')');
5159
5160         return expression;
5161 end_error:
5162         return create_invalid_expression();
5163 }
5164
5165 /**
5166  * Parse a braced expression.
5167  */
5168 static expression_t *parse_brace_expression(void)
5169 {
5170         eat('(');
5171         add_anchor_token(')');
5172
5173         switch(token.type) {
5174         case '{':
5175                 /* gcc extension: a statement expression */
5176                 return parse_statement_expression();
5177
5178         TYPE_QUALIFIERS
5179         TYPE_SPECIFIERS
5180                 return parse_cast();
5181         case T_IDENTIFIER:
5182                 if(is_typedef_symbol(token.v.symbol)) {
5183                         return parse_cast();
5184                 }
5185         }
5186
5187         expression_t *result = parse_expression();
5188         rem_anchor_token(')');
5189         expect(')');
5190
5191         return result;
5192 end_error:
5193         return create_invalid_expression();
5194 }
5195
5196 static expression_t *parse_function_keyword(void)
5197 {
5198         next_token();
5199         /* TODO */
5200
5201         if (current_function == NULL) {
5202                 errorf(HERE, "'__func__' used outside of a function");
5203         }
5204
5205         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5206         expression->base.type     = type_char_ptr;
5207         expression->funcname.kind = FUNCNAME_FUNCTION;
5208
5209         return expression;
5210 }
5211
5212 static expression_t *parse_pretty_function_keyword(void)
5213 {
5214         eat(T___PRETTY_FUNCTION__);
5215
5216         if (current_function == NULL) {
5217                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5218         }
5219
5220         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5221         expression->base.type     = type_char_ptr;
5222         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5223
5224         return expression;
5225 }
5226
5227 static expression_t *parse_funcsig_keyword(void)
5228 {
5229         eat(T___FUNCSIG__);
5230
5231         if (current_function == NULL) {
5232                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5233         }
5234
5235         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5236         expression->base.type     = type_char_ptr;
5237         expression->funcname.kind = FUNCNAME_FUNCSIG;
5238
5239         return expression;
5240 }
5241
5242 static expression_t *parse_funcdname_keyword(void)
5243 {
5244         eat(T___FUNCDNAME__);
5245
5246         if (current_function == NULL) {
5247                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5248         }
5249
5250         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5251         expression->base.type     = type_char_ptr;
5252         expression->funcname.kind = FUNCNAME_FUNCDNAME;
5253
5254         return expression;
5255 }
5256
5257 static designator_t *parse_designator(void)
5258 {
5259         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
5260         result->source_position = *HERE;
5261
5262         if(token.type != T_IDENTIFIER) {
5263                 parse_error_expected("while parsing member designator",
5264                                      T_IDENTIFIER, NULL);
5265                 return NULL;
5266         }
5267         result->symbol = token.v.symbol;
5268         next_token();
5269
5270         designator_t *last_designator = result;
5271         while(true) {
5272                 if(token.type == '.') {
5273                         next_token();
5274                         if(token.type != T_IDENTIFIER) {
5275                                 parse_error_expected("while parsing member designator",
5276                                                      T_IDENTIFIER, NULL);
5277                                 return NULL;
5278                         }
5279                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5280                         designator->source_position = *HERE;
5281                         designator->symbol          = token.v.symbol;
5282                         next_token();
5283
5284                         last_designator->next = designator;
5285                         last_designator       = designator;
5286                         continue;
5287                 }
5288                 if(token.type == '[') {
5289                         next_token();
5290                         add_anchor_token(']');
5291                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5292                         designator->source_position = *HERE;
5293                         designator->array_index     = parse_expression();
5294                         rem_anchor_token(']');
5295                         expect(']');
5296                         if(designator->array_index == NULL) {
5297                                 return NULL;
5298                         }
5299
5300                         last_designator->next = designator;
5301                         last_designator       = designator;
5302                         continue;
5303                 }
5304                 break;
5305         }
5306
5307         return result;
5308 end_error:
5309         return NULL;
5310 }
5311
5312 /**
5313  * Parse the __builtin_offsetof() expression.
5314  */
5315 static expression_t *parse_offsetof(void)
5316 {
5317         eat(T___builtin_offsetof);
5318
5319         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5320         expression->base.type    = type_size_t;
5321
5322         expect('(');
5323         add_anchor_token(',');
5324         type_t *type = parse_typename();
5325         rem_anchor_token(',');
5326         expect(',');
5327         add_anchor_token(')');
5328         designator_t *designator = parse_designator();
5329         rem_anchor_token(')');
5330         expect(')');
5331
5332         expression->offsetofe.type       = type;
5333         expression->offsetofe.designator = designator;
5334
5335         type_path_t path;
5336         memset(&path, 0, sizeof(path));
5337         path.top_type = type;
5338         path.path     = NEW_ARR_F(type_path_entry_t, 0);
5339
5340         descend_into_subtype(&path);
5341
5342         if(!walk_designator(&path, designator, true)) {
5343                 return create_invalid_expression();
5344         }
5345
5346         DEL_ARR_F(path.path);
5347
5348         return expression;
5349 end_error:
5350         return create_invalid_expression();
5351 }
5352
5353 /**
5354  * Parses a _builtin_va_start() expression.
5355  */
5356 static expression_t *parse_va_start(void)
5357 {
5358         eat(T___builtin_va_start);
5359
5360         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5361
5362         expect('(');
5363         add_anchor_token(',');
5364         expression->va_starte.ap = parse_assignment_expression();
5365         rem_anchor_token(',');
5366         expect(',');
5367         expression_t *const expr = parse_assignment_expression();
5368         if (expr->kind == EXPR_REFERENCE) {
5369                 declaration_t *const decl = expr->reference.declaration;
5370                 if (decl == NULL)
5371                         return create_invalid_expression();
5372                 if (decl->parent_scope == &current_function->scope &&
5373                     decl->next == NULL) {
5374                         expression->va_starte.parameter = decl;
5375                         expect(')');
5376                         return expression;
5377                 }
5378         }
5379         errorf(&expr->base.source_position,
5380                "second argument of 'va_start' must be last parameter of the current function");
5381 end_error:
5382         return create_invalid_expression();
5383 }
5384
5385 /**
5386  * Parses a _builtin_va_arg() expression.
5387  */
5388 static expression_t *parse_va_arg(void)
5389 {
5390         eat(T___builtin_va_arg);
5391
5392         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5393
5394         expect('(');
5395         expression->va_arge.ap = parse_assignment_expression();
5396         expect(',');
5397         expression->base.type = parse_typename();
5398         expect(')');
5399
5400         return expression;
5401 end_error:
5402         return create_invalid_expression();
5403 }
5404
5405 static expression_t *parse_builtin_symbol(void)
5406 {
5407         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5408
5409         symbol_t *symbol = token.v.symbol;
5410
5411         expression->builtin_symbol.symbol = symbol;
5412         next_token();
5413
5414         type_t *type = get_builtin_symbol_type(symbol);
5415         type = automatic_type_conversion(type);
5416
5417         expression->base.type = type;
5418         return expression;
5419 }
5420
5421 /**
5422  * Parses a __builtin_constant() expression.
5423  */
5424 static expression_t *parse_builtin_constant(void)
5425 {
5426         eat(T___builtin_constant_p);
5427
5428         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5429
5430         expect('(');
5431         add_anchor_token(')');
5432         expression->builtin_constant.value = parse_assignment_expression();
5433         rem_anchor_token(')');
5434         expect(')');
5435         expression->base.type = type_int;
5436
5437         return expression;
5438 end_error:
5439         return create_invalid_expression();
5440 }
5441
5442 /**
5443  * Parses a __builtin_prefetch() expression.
5444  */
5445 static expression_t *parse_builtin_prefetch(void)
5446 {
5447         eat(T___builtin_prefetch);
5448
5449         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5450
5451         expect('(');
5452         add_anchor_token(')');
5453         expression->builtin_prefetch.adr = parse_assignment_expression();
5454         if (token.type == ',') {
5455                 next_token();
5456                 expression->builtin_prefetch.rw = parse_assignment_expression();
5457         }
5458         if (token.type == ',') {
5459                 next_token();
5460                 expression->builtin_prefetch.locality = parse_assignment_expression();
5461         }
5462         rem_anchor_token(')');
5463         expect(')');
5464         expression->base.type = type_void;
5465
5466         return expression;
5467 end_error:
5468         return create_invalid_expression();
5469 }
5470
5471 /**
5472  * Parses a __builtin_is_*() compare expression.
5473  */
5474 static expression_t *parse_compare_builtin(void)
5475 {
5476         expression_t *expression;
5477
5478         switch(token.type) {
5479         case T___builtin_isgreater:
5480                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5481                 break;
5482         case T___builtin_isgreaterequal:
5483                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5484                 break;
5485         case T___builtin_isless:
5486                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5487                 break;
5488         case T___builtin_islessequal:
5489                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5490                 break;
5491         case T___builtin_islessgreater:
5492                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5493                 break;
5494         case T___builtin_isunordered:
5495                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5496                 break;
5497         default:
5498                 internal_errorf(HERE, "invalid compare builtin found");
5499                 break;
5500         }
5501         expression->base.source_position = *HERE;
5502         next_token();
5503
5504         expect('(');
5505         expression->binary.left = parse_assignment_expression();
5506         expect(',');
5507         expression->binary.right = parse_assignment_expression();
5508         expect(')');
5509
5510         type_t *const orig_type_left  = expression->binary.left->base.type;
5511         type_t *const orig_type_right = expression->binary.right->base.type;
5512
5513         type_t *const type_left  = skip_typeref(orig_type_left);
5514         type_t *const type_right = skip_typeref(orig_type_right);
5515         if(!is_type_float(type_left) && !is_type_float(type_right)) {
5516                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5517                         type_error_incompatible("invalid operands in comparison",
5518                                 &expression->base.source_position, orig_type_left, orig_type_right);
5519                 }
5520         } else {
5521                 semantic_comparison(&expression->binary);
5522         }
5523
5524         return expression;
5525 end_error:
5526         return create_invalid_expression();
5527 }
5528
5529 /**
5530  * Parses a __builtin_expect() expression.
5531  */
5532 static expression_t *parse_builtin_expect(void)
5533 {
5534         eat(T___builtin_expect);
5535
5536         expression_t *expression
5537                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5538
5539         expect('(');
5540         expression->binary.left = parse_assignment_expression();
5541         expect(',');
5542         expression->binary.right = parse_constant_expression();
5543         expect(')');
5544
5545         expression->base.type = expression->binary.left->base.type;
5546
5547         return expression;
5548 end_error:
5549         return create_invalid_expression();
5550 }
5551
5552 /**
5553  * Parses a MS assume() expression.
5554  */
5555 static expression_t *parse_assume(void) {
5556         eat(T__assume);
5557
5558         expression_t *expression
5559                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5560
5561         expect('(');
5562         add_anchor_token(')');
5563         expression->unary.value = parse_assignment_expression();
5564         rem_anchor_token(')');
5565         expect(')');
5566
5567         expression->base.type = type_void;
5568         return expression;
5569 end_error:
5570         return create_invalid_expression();
5571 }
5572
5573 /**
5574  * Parse a microsoft __noop expression.
5575  */
5576 static expression_t *parse_noop_expression(void) {
5577         source_position_t source_position = *HERE;
5578         eat(T___noop);
5579
5580         if (token.type == '(') {
5581                 /* parse arguments */
5582                 eat('(');
5583                 add_anchor_token(')');
5584                 add_anchor_token(',');
5585
5586                 if(token.type != ')') {
5587                         while(true) {
5588                                 (void)parse_assignment_expression();
5589                                 if(token.type != ',')
5590                                         break;
5591                                 next_token();
5592                         }
5593                 }
5594         }
5595         rem_anchor_token(',');
5596         rem_anchor_token(')');
5597         expect(')');
5598
5599         /* the result is a (int)0 */
5600         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5601         cnst->base.source_position = source_position;
5602         cnst->base.type            = type_int;
5603         cnst->conste.v.int_value   = 0;
5604         cnst->conste.is_ms_noop    = true;
5605
5606         return cnst;
5607
5608 end_error:
5609         return create_invalid_expression();
5610 }
5611
5612 /**
5613  * Parses a primary expression.
5614  */
5615 static expression_t *parse_primary_expression(void)
5616 {
5617         switch (token.type) {
5618                 case T_INTEGER:                  return parse_int_const();
5619                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
5620                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
5621                 case T_FLOATINGPOINT:            return parse_float_const();
5622                 case T_STRING_LITERAL:
5623                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
5624                 case T_IDENTIFIER:               return parse_reference();
5625                 case T___FUNCTION__:
5626                 case T___func__:                 return parse_function_keyword();
5627                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
5628                 case T___FUNCSIG__:              return parse_funcsig_keyword();
5629                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
5630                 case T___builtin_offsetof:       return parse_offsetof();
5631                 case T___builtin_va_start:       return parse_va_start();
5632                 case T___builtin_va_arg:         return parse_va_arg();
5633                 case T___builtin_expect:         return parse_builtin_expect();
5634                 case T___builtin_alloca:
5635                 case T___builtin_nan:
5636                 case T___builtin_nand:
5637                 case T___builtin_nanf:
5638                 case T___builtin_huge_val:
5639                 case T___builtin_va_end:         return parse_builtin_symbol();
5640                 case T___builtin_isgreater:
5641                 case T___builtin_isgreaterequal:
5642                 case T___builtin_isless:
5643                 case T___builtin_islessequal:
5644                 case T___builtin_islessgreater:
5645                 case T___builtin_isunordered:    return parse_compare_builtin();
5646                 case T___builtin_constant_p:     return parse_builtin_constant();
5647                 case T___builtin_prefetch:       return parse_builtin_prefetch();
5648                 case T__assume:                  return parse_assume();
5649
5650                 case '(':                        return parse_brace_expression();
5651                 case T___noop:                   return parse_noop_expression();
5652         }
5653
5654         errorf(HERE, "unexpected token %K, expected an expression", &token);
5655         return create_invalid_expression();
5656 }
5657
5658 /**
5659  * Check if the expression has the character type and issue a warning then.
5660  */
5661 static void check_for_char_index_type(const expression_t *expression) {
5662         type_t       *const type      = expression->base.type;
5663         const type_t *const base_type = skip_typeref(type);
5664
5665         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5666                         warning.char_subscripts) {
5667                 warningf(&expression->base.source_position,
5668                          "array subscript has type '%T'", type);
5669         }
5670 }
5671
5672 static expression_t *parse_array_expression(unsigned precedence,
5673                                             expression_t *left)
5674 {
5675         (void) precedence;
5676
5677         eat('[');
5678         add_anchor_token(']');
5679
5680         expression_t *inside = parse_expression();
5681
5682         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5683
5684         array_access_expression_t *array_access = &expression->array_access;
5685
5686         type_t *const orig_type_left   = left->base.type;
5687         type_t *const orig_type_inside = inside->base.type;
5688
5689         type_t *const type_left   = skip_typeref(orig_type_left);
5690         type_t *const type_inside = skip_typeref(orig_type_inside);
5691
5692         type_t *return_type;
5693         if (is_type_pointer(type_left)) {
5694                 return_type             = type_left->pointer.points_to;
5695                 array_access->array_ref = left;
5696                 array_access->index     = inside;
5697                 check_for_char_index_type(inside);
5698         } else if (is_type_pointer(type_inside)) {
5699                 return_type             = type_inside->pointer.points_to;
5700                 array_access->array_ref = inside;
5701                 array_access->index     = left;
5702                 array_access->flipped   = true;
5703                 check_for_char_index_type(left);
5704         } else {
5705                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5706                         errorf(HERE,
5707                                 "array access on object with non-pointer types '%T', '%T'",
5708                                 orig_type_left, orig_type_inside);
5709                 }
5710                 return_type             = type_error_type;
5711                 array_access->array_ref = create_invalid_expression();
5712         }
5713
5714         rem_anchor_token(']');
5715         if(token.type != ']') {
5716                 parse_error_expected("Problem while parsing array access", ']', NULL);
5717                 return expression;
5718         }
5719         next_token();
5720
5721         return_type           = automatic_type_conversion(return_type);
5722         expression->base.type = return_type;
5723
5724         return expression;
5725 }
5726
5727 static expression_t *parse_typeprop(expression_kind_t const kind,
5728                                     source_position_t const pos,
5729                                     unsigned const precedence)
5730 {
5731         expression_t *tp_expression = allocate_expression_zero(kind);
5732         tp_expression->base.type            = type_size_t;
5733         tp_expression->base.source_position = pos;
5734
5735         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5736
5737         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5738                 next_token();
5739                 add_anchor_token(')');
5740                 type_t* const orig_type = parse_typename();
5741                 tp_expression->typeprop.type = orig_type;
5742
5743                 type_t const* const type = skip_typeref(orig_type);
5744                 char const* const wrong_type =
5745                         is_type_incomplete(type)    ? "incomplete"          :
5746                         type->kind == TYPE_FUNCTION ? "function designator" :
5747                         type->kind == TYPE_BITFIELD ? "bitfield"            :
5748                         NULL;
5749                 if (wrong_type != NULL) {
5750                         errorf(&pos, "operand of %s expression must not be %s type '%T'",
5751                                what, wrong_type, type);
5752                 }
5753
5754                 rem_anchor_token(')');
5755                 expect(')');
5756         } else {
5757                 expression_t *expression = parse_sub_expression(precedence);
5758
5759                 type_t* const orig_type = revert_automatic_type_conversion(expression);
5760                 expression->base.type = orig_type;
5761
5762                 type_t const* const type = skip_typeref(orig_type);
5763                 char const* const wrong_type =
5764                         is_type_incomplete(type)    ? "incomplete"          :
5765                         type->kind == TYPE_FUNCTION ? "function designator" :
5766                         type->kind == TYPE_BITFIELD ? "bitfield"            :
5767                         NULL;
5768                 if (wrong_type != NULL) {
5769                         errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5770                 }
5771
5772                 tp_expression->typeprop.type          = expression->base.type;
5773                 tp_expression->typeprop.tp_expression = expression;
5774         }
5775
5776         return tp_expression;
5777 end_error:
5778         return create_invalid_expression();
5779 }
5780
5781 static expression_t *parse_sizeof(unsigned precedence)
5782 {
5783         source_position_t pos = *HERE;
5784         eat(T_sizeof);
5785         return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5786 }
5787
5788 static expression_t *parse_alignof(unsigned precedence)
5789 {
5790         source_position_t pos = *HERE;
5791         eat(T___alignof__);
5792         return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5793 }
5794
5795 static expression_t *parse_select_expression(unsigned precedence,
5796                                              expression_t *compound)
5797 {
5798         (void) precedence;
5799         assert(token.type == '.' || token.type == T_MINUSGREATER);
5800
5801         bool is_pointer = (token.type == T_MINUSGREATER);
5802         next_token();
5803
5804         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
5805         select->select.compound = compound;
5806
5807         if (token.type != T_IDENTIFIER) {
5808                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5809                 return select;
5810         }
5811         symbol_t *symbol      = token.v.symbol;
5812         select->select.symbol = symbol;
5813         next_token();
5814
5815         type_t *const orig_type = compound->base.type;
5816         type_t *const type      = skip_typeref(orig_type);
5817
5818         type_t *type_left = type;
5819         if (is_pointer) {
5820                 if (!is_type_pointer(type)) {
5821                         if (is_type_valid(type)) {
5822                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5823                         }
5824                         return create_invalid_expression();
5825                 }
5826                 type_left = type->pointer.points_to;
5827         }
5828         type_left = skip_typeref(type_left);
5829
5830         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5831             type_left->kind != TYPE_COMPOUND_UNION) {
5832                 if (is_type_valid(type_left)) {
5833                         errorf(HERE, "request for member '%Y' in something not a struct or "
5834                                "union, but '%T'", symbol, type_left);
5835                 }
5836                 return create_invalid_expression();
5837         }
5838
5839         declaration_t *const declaration = type_left->compound.declaration;
5840
5841         if (!declaration->init.complete) {
5842                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5843                        symbol, type_left);
5844                 return create_invalid_expression();
5845         }
5846
5847         declaration_t *iter = find_compound_entry(declaration, symbol);
5848         if (iter == NULL) {
5849                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5850                 return create_invalid_expression();
5851         }
5852
5853         /* we always do the auto-type conversions; the & and sizeof parser contains
5854          * code to revert this! */
5855         type_t *expression_type = automatic_type_conversion(iter->type);
5856
5857         select->select.compound_entry = iter;
5858         select->base.type             = expression_type;
5859
5860         type_t *skipped = skip_typeref(iter->type);
5861         if (skipped->kind == TYPE_BITFIELD) {
5862                 select->base.type = skipped->bitfield.base_type;
5863         }
5864
5865         return select;
5866 }
5867
5868 /**
5869  * Parse a call expression, ie. expression '( ... )'.
5870  *
5871  * @param expression  the function address
5872  */
5873 static expression_t *parse_call_expression(unsigned precedence,
5874                                            expression_t *expression)
5875 {
5876         (void) precedence;
5877         expression_t *result = allocate_expression_zero(EXPR_CALL);
5878         result->base.source_position = expression->base.source_position;
5879
5880         call_expression_t *call = &result->call;
5881         call->function          = expression;
5882
5883         type_t *const orig_type = expression->base.type;
5884         type_t *const type      = skip_typeref(orig_type);
5885
5886         function_type_t *function_type = NULL;
5887         if (is_type_pointer(type)) {
5888                 type_t *const to_type = skip_typeref(type->pointer.points_to);
5889
5890                 if (is_type_function(to_type)) {
5891                         function_type   = &to_type->function;
5892                         call->base.type = function_type->return_type;
5893                 }
5894         }
5895
5896         if (function_type == NULL && is_type_valid(type)) {
5897                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5898         }
5899
5900         /* parse arguments */
5901         eat('(');
5902         add_anchor_token(')');
5903         add_anchor_token(',');
5904
5905         if(token.type != ')') {
5906                 call_argument_t *last_argument = NULL;
5907
5908                 while(true) {
5909                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5910
5911                         argument->expression = parse_assignment_expression();
5912                         if(last_argument == NULL) {
5913                                 call->arguments = argument;
5914                         } else {
5915                                 last_argument->next = argument;
5916                         }
5917                         last_argument = argument;
5918
5919                         if(token.type != ',')
5920                                 break;
5921                         next_token();
5922                 }
5923         }
5924         rem_anchor_token(',');
5925         rem_anchor_token(')');
5926         expect(')');
5927
5928         if(function_type == NULL)
5929                 return result;
5930
5931         function_parameter_t *parameter = function_type->parameters;
5932         call_argument_t      *argument  = call->arguments;
5933         if (!function_type->unspecified_parameters) {
5934                 for( ; parameter != NULL && argument != NULL;
5935                                 parameter = parameter->next, argument = argument->next) {
5936                         type_t *expected_type = parameter->type;
5937                         /* TODO report scope in error messages */
5938                         expression_t *const arg_expr = argument->expression;
5939                         type_t       *const res_type = semantic_assign(expected_type, arg_expr,
5940                                                                                                                    "function call",
5941                                                                                                                    &arg_expr->base.source_position);
5942                         if (res_type == NULL) {
5943                                 /* TODO improve error message */
5944                                 errorf(&arg_expr->base.source_position,
5945                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5946                                         arg_expr, arg_expr->base.type, expected_type);
5947                         } else {
5948                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
5949                         }
5950                 }
5951
5952                 if (parameter != NULL) {
5953                         errorf(HERE, "too few arguments to function '%E'", expression);
5954                 } else if (argument != NULL && !function_type->variadic) {
5955                         errorf(HERE, "too many arguments to function '%E'", expression);
5956                 }
5957         }
5958
5959         /* do default promotion */
5960         for( ; argument != NULL; argument = argument->next) {
5961                 type_t *type = argument->expression->base.type;
5962
5963                 type = get_default_promoted_type(type);
5964
5965                 argument->expression
5966                         = create_implicit_cast(argument->expression, type);
5967         }
5968
5969         check_format(&result->call);
5970
5971         return result;
5972 end_error:
5973         return create_invalid_expression();
5974 }
5975
5976 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5977
5978 static bool same_compound_type(const type_t *type1, const type_t *type2)
5979 {
5980         return
5981                 is_type_compound(type1) &&
5982                 type1->kind == type2->kind &&
5983                 type1->compound.declaration == type2->compound.declaration;
5984 }
5985
5986 /**
5987  * Parse a conditional expression, ie. 'expression ? ... : ...'.
5988  *
5989  * @param expression  the conditional expression
5990  */
5991 static expression_t *parse_conditional_expression(unsigned precedence,
5992                                                   expression_t *expression)
5993 {
5994         eat('?');
5995         add_anchor_token(':');
5996
5997         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5998
5999         conditional_expression_t *conditional = &result->conditional;
6000         conditional->condition = expression;
6001
6002         /* 6.5.15.2 */
6003         type_t *const condition_type_orig = expression->base.type;
6004         type_t *const condition_type      = skip_typeref(condition_type_orig);
6005         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6006                 type_error("expected a scalar type in conditional condition",
6007                            &expression->base.source_position, condition_type_orig);
6008         }
6009
6010         expression_t *true_expression = parse_expression();
6011         rem_anchor_token(':');
6012         expect(':');
6013         expression_t *false_expression = parse_sub_expression(precedence);
6014
6015         type_t *const orig_true_type  = true_expression->base.type;
6016         type_t *const orig_false_type = false_expression->base.type;
6017         type_t *const true_type       = skip_typeref(orig_true_type);
6018         type_t *const false_type      = skip_typeref(orig_false_type);
6019
6020         /* 6.5.15.3 */
6021         type_t *result_type;
6022         if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6023                 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6024                 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6025                     || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6026                         warningf(&expression->base.source_position,
6027                                         "ISO C forbids conditional expression with only one void side");
6028                 }
6029                 result_type = type_void;
6030         } else if (is_type_arithmetic(true_type)
6031                    && is_type_arithmetic(false_type)) {
6032                 result_type = semantic_arithmetic(true_type, false_type);
6033
6034                 true_expression  = create_implicit_cast(true_expression, result_type);
6035                 false_expression = create_implicit_cast(false_expression, result_type);
6036
6037                 conditional->true_expression  = true_expression;
6038                 conditional->false_expression = false_expression;
6039                 conditional->base.type        = result_type;
6040         } else if (same_compound_type(true_type, false_type)) {
6041                 /* just take 1 of the 2 types */
6042                 result_type = true_type;
6043         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6044                 type_t *pointer_type;
6045                 type_t *other_type;
6046                 expression_t *other_expression;
6047                 if (is_type_pointer(true_type)) {
6048                         pointer_type     = true_type;
6049                         other_type       = false_type;
6050                         other_expression = false_expression;
6051                 } else {
6052                         pointer_type     = false_type;
6053                         other_type       = true_type;
6054                         other_expression = true_expression;
6055                 }
6056
6057                 if(is_type_pointer(other_type)) {
6058                         if(!pointers_compatible(true_type, false_type)) {
6059                                 warningf(&expression->base.source_position,
6060                                                 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
6061                         }
6062                         result_type = true_type;
6063                 } else if(is_null_pointer_constant(other_expression)) {
6064                         result_type = pointer_type;
6065                 } else if(is_type_integer(other_type)) {
6066                         warningf(&expression->base.source_position,
6067                                         "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6068                         result_type = pointer_type;
6069                 } else {
6070                         type_error_incompatible("while parsing conditional",
6071                                         &expression->base.source_position, true_type, false_type);
6072                         result_type = type_error_type;
6073                 }
6074         } else {
6075                 /* TODO: one pointer to void*, other some pointer */
6076
6077                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6078                         type_error_incompatible("while parsing conditional",
6079                                                 &expression->base.source_position, true_type,
6080                                                 false_type);
6081                 }
6082                 result_type = type_error_type;
6083         }
6084
6085         conditional->true_expression
6086                 = create_implicit_cast(true_expression, result_type);
6087         conditional->false_expression
6088                 = create_implicit_cast(false_expression, result_type);
6089         conditional->base.type = result_type;
6090         return result;
6091 end_error:
6092         return create_invalid_expression();
6093 }
6094
6095 /**
6096  * Parse an extension expression.
6097  */
6098 static expression_t *parse_extension(unsigned precedence)
6099 {
6100         eat(T___extension__);
6101
6102         /* TODO enable extensions */
6103         expression_t *expression = parse_sub_expression(precedence);
6104         /* TODO disable extensions */
6105         return expression;
6106 }
6107
6108 /**
6109  * Parse a __builtin_classify_type() expression.
6110  */
6111 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6112 {
6113         eat(T___builtin_classify_type);
6114
6115         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6116         result->base.type    = type_int;
6117
6118         expect('(');
6119         add_anchor_token(')');
6120         expression_t *expression = parse_sub_expression(precedence);
6121         rem_anchor_token(')');
6122         expect(')');
6123         result->classify_type.type_expression = expression;
6124
6125         return result;
6126 end_error:
6127         return create_invalid_expression();
6128 }
6129
6130 static void check_pointer_arithmetic(const source_position_t *source_position,
6131                                      type_t *pointer_type,
6132                                      type_t *orig_pointer_type)
6133 {
6134         type_t *points_to = pointer_type->pointer.points_to;
6135         points_to = skip_typeref(points_to);
6136
6137         if (is_type_incomplete(points_to) &&
6138                         (! (c_mode & _GNUC)
6139                          || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6140                 errorf(source_position,
6141                            "arithmetic with pointer to incomplete type '%T' not allowed",
6142                            orig_pointer_type);
6143         } else if (is_type_function(points_to)) {
6144                 errorf(source_position,
6145                            "arithmetic with pointer to function type '%T' not allowed",
6146                            orig_pointer_type);
6147         }
6148 }
6149
6150 static void semantic_incdec(unary_expression_t *expression)
6151 {
6152         type_t *const orig_type = expression->value->base.type;
6153         type_t *const type      = skip_typeref(orig_type);
6154         if (is_type_pointer(type)) {
6155                 check_pointer_arithmetic(&expression->base.source_position,
6156                                          type, orig_type);
6157         } else if (!is_type_real(type) && is_type_valid(type)) {
6158                 /* TODO: improve error message */
6159                 errorf(HERE, "operation needs an arithmetic or pointer type");
6160         }
6161         expression->base.type = orig_type;
6162 }
6163
6164 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6165 {
6166         type_t *const orig_type = expression->value->base.type;
6167         type_t *const type      = skip_typeref(orig_type);
6168         if(!is_type_arithmetic(type)) {
6169                 if (is_type_valid(type)) {
6170                         /* TODO: improve error message */
6171                         errorf(HERE, "operation needs an arithmetic type");
6172                 }
6173                 return;
6174         }
6175
6176         expression->base.type = orig_type;
6177 }
6178
6179 static void semantic_unexpr_scalar(unary_expression_t *expression)
6180 {
6181         type_t *const orig_type = expression->value->base.type;
6182         type_t *const type      = skip_typeref(orig_type);
6183         if (!is_type_scalar(type)) {
6184                 if (is_type_valid(type)) {
6185                         errorf(HERE, "operand of ! must be of scalar type");
6186                 }
6187                 return;
6188         }
6189
6190         expression->base.type = orig_type;
6191 }
6192
6193 static void semantic_unexpr_integer(unary_expression_t *expression)
6194 {
6195         type_t *const orig_type = expression->value->base.type;
6196         type_t *const type      = skip_typeref(orig_type);
6197         if (!is_type_integer(type)) {
6198                 if (is_type_valid(type)) {
6199                         errorf(HERE, "operand of ~ must be of integer type");
6200                 }
6201                 return;
6202         }
6203
6204         expression->base.type = orig_type;
6205 }
6206
6207 static void semantic_dereference(unary_expression_t *expression)
6208 {
6209         type_t *const orig_type = expression->value->base.type;
6210         type_t *const type      = skip_typeref(orig_type);
6211         if(!is_type_pointer(type)) {
6212                 if (is_type_valid(type)) {
6213                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6214                 }
6215                 return;
6216         }
6217
6218         type_t *result_type   = type->pointer.points_to;
6219         result_type           = automatic_type_conversion(result_type);
6220         expression->base.type = result_type;
6221 }
6222
6223 /**
6224  * Check the semantic of the address taken expression.
6225  */
6226 static void semantic_take_addr(unary_expression_t *expression)
6227 {
6228         expression_t *value = expression->value;
6229         value->base.type    = revert_automatic_type_conversion(value);
6230
6231         type_t *orig_type = value->base.type;
6232         if(!is_type_valid(orig_type))
6233                 return;
6234
6235         if(value->kind == EXPR_REFERENCE) {
6236                 declaration_t *const declaration = value->reference.declaration;
6237                 if(declaration != NULL) {
6238                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6239                                 errorf(&expression->base.source_position,
6240                                        "address of register variable '%Y' requested",
6241                                        declaration->symbol);
6242                         }
6243                         declaration->address_taken = 1;
6244                 }
6245         }
6246
6247         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6248 }
6249
6250 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
6251 static expression_t *parse_##unexpression_type(unsigned precedence)            \
6252 {                                                                              \
6253         eat(token_type);                                                           \
6254                                                                                    \
6255         expression_t *unary_expression                                             \
6256                 = allocate_expression_zero(unexpression_type);                         \
6257         unary_expression->base.source_position = *HERE;                            \
6258         unary_expression->unary.value = parse_sub_expression(precedence);          \
6259                                                                                    \
6260         sfunc(&unary_expression->unary);                                           \
6261                                                                                    \
6262         return unary_expression;                                                   \
6263 }
6264
6265 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6266                                semantic_unexpr_arithmetic)
6267 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6268                                semantic_unexpr_arithmetic)
6269 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6270                                semantic_unexpr_scalar)
6271 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6272                                semantic_dereference)
6273 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6274                                semantic_take_addr)
6275 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6276                                semantic_unexpr_integer)
6277 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
6278                                semantic_incdec)
6279 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6280                                semantic_incdec)
6281
6282 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6283                                                sfunc)                         \
6284 static expression_t *parse_##unexpression_type(unsigned precedence,           \
6285                                                expression_t *left)            \
6286 {                                                                             \
6287         (void) precedence;                                                        \
6288         eat(token_type);                                                          \
6289                                                                               \
6290         expression_t *unary_expression                                            \
6291                 = allocate_expression_zero(unexpression_type);                        \
6292         unary_expression->unary.value = left;                                     \
6293                                                                                   \
6294         sfunc(&unary_expression->unary);                                          \
6295                                                                               \
6296         return unary_expression;                                                  \
6297 }
6298
6299 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6300                                        EXPR_UNARY_POSTFIX_INCREMENT,
6301                                        semantic_incdec)
6302 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6303                                        EXPR_UNARY_POSTFIX_DECREMENT,
6304                                        semantic_incdec)
6305
6306 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6307 {
6308         /* TODO: handle complex + imaginary types */
6309
6310         /* Â§ 6.3.1.8 Usual arithmetic conversions */
6311         if(type_left == type_long_double || type_right == type_long_double) {
6312                 return type_long_double;
6313         } else if(type_left == type_double || type_right == type_double) {
6314                 return type_double;
6315         } else if(type_left == type_float || type_right == type_float) {
6316                 return type_float;
6317         }
6318
6319         type_right = promote_integer(type_right);
6320         type_left  = promote_integer(type_left);
6321
6322         if(type_left == type_right)
6323                 return type_left;
6324
6325         bool signed_left  = is_type_signed(type_left);
6326         bool signed_right = is_type_signed(type_right);
6327         int  rank_left    = get_rank(type_left);
6328         int  rank_right   = get_rank(type_right);
6329         if(rank_left < rank_right) {
6330                 if(signed_left == signed_right || !signed_right) {
6331                         return type_right;
6332                 } else {
6333                         return type_left;
6334                 }
6335         } else {
6336                 if(signed_left == signed_right || !signed_left) {
6337                         return type_left;
6338                 } else {
6339                         return type_right;
6340                 }
6341         }
6342 }
6343
6344 /**
6345  * Check the semantic restrictions for a binary expression.
6346  */
6347 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6348 {
6349         expression_t *const left            = expression->left;
6350         expression_t *const right           = expression->right;
6351         type_t       *const orig_type_left  = left->base.type;
6352         type_t       *const orig_type_right = right->base.type;
6353         type_t       *const type_left       = skip_typeref(orig_type_left);
6354         type_t       *const type_right      = skip_typeref(orig_type_right);
6355
6356         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6357                 /* TODO: improve error message */
6358                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6359                         errorf(HERE, "operation needs arithmetic types");
6360                 }
6361                 return;
6362         }
6363
6364         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6365         expression->left      = create_implicit_cast(left, arithmetic_type);
6366         expression->right     = create_implicit_cast(right, arithmetic_type);
6367         expression->base.type = arithmetic_type;
6368 }
6369
6370 static void semantic_shift_op(binary_expression_t *expression)
6371 {
6372         expression_t *const left            = expression->left;
6373         expression_t *const right           = expression->right;
6374         type_t       *const orig_type_left  = left->base.type;
6375         type_t       *const orig_type_right = right->base.type;
6376         type_t       *      type_left       = skip_typeref(orig_type_left);
6377         type_t       *      type_right      = skip_typeref(orig_type_right);
6378
6379         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6380                 /* TODO: improve error message */
6381                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6382                         errorf(HERE, "operation needs integer types");
6383                 }
6384                 return;
6385         }
6386
6387         type_left  = promote_integer(type_left);
6388         type_right = promote_integer(type_right);
6389
6390         expression->left      = create_implicit_cast(left, type_left);
6391         expression->right     = create_implicit_cast(right, type_right);
6392         expression->base.type = type_left;
6393 }
6394
6395 static void semantic_add(binary_expression_t *expression)
6396 {
6397         expression_t *const left            = expression->left;
6398         expression_t *const right           = expression->right;
6399         type_t       *const orig_type_left  = left->base.type;
6400         type_t       *const orig_type_right = right->base.type;
6401         type_t       *const type_left       = skip_typeref(orig_type_left);
6402         type_t       *const type_right      = skip_typeref(orig_type_right);
6403
6404         /* Â§ 6.5.6 */
6405         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6406                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6407                 expression->left  = create_implicit_cast(left, arithmetic_type);
6408                 expression->right = create_implicit_cast(right, arithmetic_type);
6409                 expression->base.type = arithmetic_type;
6410                 return;
6411         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6412                 check_pointer_arithmetic(&expression->base.source_position,
6413                                          type_left, orig_type_left);
6414                 expression->base.type = type_left;
6415         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6416                 check_pointer_arithmetic(&expression->base.source_position,
6417                                          type_right, orig_type_right);
6418                 expression->base.type = type_right;
6419         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6420                 errorf(&expression->base.source_position,
6421                        "invalid operands to binary + ('%T', '%T')",
6422                        orig_type_left, orig_type_right);
6423         }
6424 }
6425
6426 static void semantic_sub(binary_expression_t *expression)
6427 {
6428         expression_t *const left            = expression->left;
6429         expression_t *const right           = expression->right;
6430         type_t       *const orig_type_left  = left->base.type;
6431         type_t       *const orig_type_right = right->base.type;
6432         type_t       *const type_left       = skip_typeref(orig_type_left);
6433         type_t       *const type_right      = skip_typeref(orig_type_right);
6434
6435         /* Â§ 5.6.5 */
6436         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6437                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6438                 expression->left        = create_implicit_cast(left, arithmetic_type);
6439                 expression->right       = create_implicit_cast(right, arithmetic_type);
6440                 expression->base.type =  arithmetic_type;
6441                 return;
6442         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6443                 check_pointer_arithmetic(&expression->base.source_position,
6444                                          type_left, orig_type_left);
6445                 expression->base.type = type_left;
6446         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6447                 if(!pointers_compatible(type_left, type_right)) {
6448                         errorf(HERE,
6449                                "pointers to incompatible objects to binary '-' ('%T', '%T')",
6450                                orig_type_left, orig_type_right);
6451                 } else {
6452                         expression->base.type = type_ptrdiff_t;
6453                 }
6454         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6455                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6456                        orig_type_left, orig_type_right);
6457         }
6458 }
6459
6460 /**
6461  * Check the semantics of comparison expressions.
6462  *
6463  * @param expression   The expression to check.
6464  */
6465 static void semantic_comparison(binary_expression_t *expression)
6466 {
6467         expression_t *left            = expression->left;
6468         expression_t *right           = expression->right;
6469         type_t       *orig_type_left  = left->base.type;
6470         type_t       *orig_type_right = right->base.type;
6471
6472         type_t *type_left  = skip_typeref(orig_type_left);
6473         type_t *type_right = skip_typeref(orig_type_right);
6474
6475         /* TODO non-arithmetic types */
6476         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6477                 /* test for signed vs unsigned compares */
6478                 if (warning.sign_compare &&
6479                     (expression->base.kind != EXPR_BINARY_EQUAL &&
6480                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6481                     (is_type_signed(type_left) != is_type_signed(type_right))) {
6482
6483                         /* check if 1 of the operands is a constant, in this case we just
6484                          * check wether we can safely represent the resulting constant in
6485                          * the type of the other operand. */
6486                         expression_t *const_expr = NULL;
6487                         expression_t *other_expr = NULL;
6488
6489                         if(is_constant_expression(left)) {
6490                                 const_expr = left;
6491                                 other_expr = right;
6492                         } else if(is_constant_expression(right)) {
6493                                 const_expr = right;
6494                                 other_expr = left;
6495                         }
6496
6497                         if(const_expr != NULL) {
6498                                 type_t *other_type = skip_typeref(other_expr->base.type);
6499                                 long    val        = fold_constant(const_expr);
6500                                 /* TODO: check if val can be represented by other_type */
6501                                 (void) other_type;
6502                                 (void) val;
6503                         }
6504                         warningf(&expression->base.source_position,
6505                                  "comparison between signed and unsigned");
6506                 }
6507                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6508                 expression->left        = create_implicit_cast(left, arithmetic_type);
6509                 expression->right       = create_implicit_cast(right, arithmetic_type);
6510                 expression->base.type   = arithmetic_type;
6511                 if (warning.float_equal &&
6512                     (expression->base.kind == EXPR_BINARY_EQUAL ||
6513                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6514                     is_type_float(arithmetic_type)) {
6515                         warningf(&expression->base.source_position,
6516                                  "comparing floating point with == or != is unsafe");
6517                 }
6518         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6519                 /* TODO check compatibility */
6520         } else if (is_type_pointer(type_left)) {
6521                 expression->right = create_implicit_cast(right, type_left);
6522         } else if (is_type_pointer(type_right)) {
6523                 expression->left = create_implicit_cast(left, type_right);
6524         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6525                 type_error_incompatible("invalid operands in comparison",
6526                                         &expression->base.source_position,
6527                                         type_left, type_right);
6528         }
6529         expression->base.type = type_int;
6530 }
6531
6532 /**
6533  * Checks if a compound type has constant fields.
6534  */
6535 static bool has_const_fields(const compound_type_t *type)
6536 {
6537         const scope_t       *scope       = &type->declaration->scope;
6538         const declaration_t *declaration = scope->declarations;
6539
6540         for (; declaration != NULL; declaration = declaration->next) {
6541                 if (declaration->namespc != NAMESPACE_NORMAL)
6542                         continue;
6543
6544                 const type_t *decl_type = skip_typeref(declaration->type);
6545                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6546                         return true;
6547         }
6548         /* TODO */
6549         return false;
6550 }
6551
6552 static bool is_lvalue(const expression_t *expression)
6553 {
6554         switch (expression->kind) {
6555         case EXPR_REFERENCE:
6556         case EXPR_ARRAY_ACCESS:
6557         case EXPR_SELECT:
6558         case EXPR_UNARY_DEREFERENCE:
6559                 return true;
6560
6561         default:
6562                 return false;
6563         }
6564 }
6565
6566 static bool is_valid_assignment_lhs(expression_t const* const left)
6567 {
6568         type_t *const orig_type_left = revert_automatic_type_conversion(left);
6569         type_t *const type_left      = skip_typeref(orig_type_left);
6570
6571         if (!is_lvalue(left)) {
6572                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6573                        left);
6574                 return false;
6575         }
6576
6577         if (is_type_array(type_left)) {
6578                 errorf(HERE, "cannot assign to arrays ('%E')", left);
6579                 return false;
6580         }
6581         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6582                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6583                        orig_type_left);
6584                 return false;
6585         }
6586         if (is_type_incomplete(type_left)) {
6587                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6588                        left, orig_type_left);
6589                 return false;
6590         }
6591         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6592                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6593                        left, orig_type_left);
6594                 return false;
6595         }
6596
6597         return true;
6598 }
6599
6600 static void semantic_arithmetic_assign(binary_expression_t *expression)
6601 {
6602         expression_t *left            = expression->left;
6603         expression_t *right           = expression->right;
6604         type_t       *orig_type_left  = left->base.type;
6605         type_t       *orig_type_right = right->base.type;
6606
6607         if (!is_valid_assignment_lhs(left))
6608                 return;
6609
6610         type_t *type_left  = skip_typeref(orig_type_left);
6611         type_t *type_right = skip_typeref(orig_type_right);
6612
6613         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6614                 /* TODO: improve error message */
6615                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6616                         errorf(HERE, "operation needs arithmetic types");
6617                 }
6618                 return;
6619         }
6620
6621         /* combined instructions are tricky. We can't create an implicit cast on
6622          * the left side, because we need the uncasted form for the store.
6623          * The ast2firm pass has to know that left_type must be right_type
6624          * for the arithmetic operation and create a cast by itself */
6625         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6626         expression->right       = create_implicit_cast(right, arithmetic_type);
6627         expression->base.type   = type_left;
6628 }
6629
6630 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6631 {
6632         expression_t *const left            = expression->left;
6633         expression_t *const right           = expression->right;
6634         type_t       *const orig_type_left  = left->base.type;
6635         type_t       *const orig_type_right = right->base.type;
6636         type_t       *const type_left       = skip_typeref(orig_type_left);
6637         type_t       *const type_right      = skip_typeref(orig_type_right);
6638
6639         if (!is_valid_assignment_lhs(left))
6640                 return;
6641
6642         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6643                 /* combined instructions are tricky. We can't create an implicit cast on
6644                  * the left side, because we need the uncasted form for the store.
6645                  * The ast2firm pass has to know that left_type must be right_type
6646                  * for the arithmetic operation and create a cast by itself */
6647                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6648                 expression->right     = create_implicit_cast(right, arithmetic_type);
6649                 expression->base.type = type_left;
6650         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6651                 check_pointer_arithmetic(&expression->base.source_position,
6652                                          type_left, orig_type_left);
6653                 expression->base.type = type_left;
6654         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6655                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6656         }
6657 }
6658
6659 /**
6660  * Check the semantic restrictions of a logical expression.
6661  */
6662 static void semantic_logical_op(binary_expression_t *expression)
6663 {
6664         expression_t *const left            = expression->left;
6665         expression_t *const right           = expression->right;
6666         type_t       *const orig_type_left  = left->base.type;
6667         type_t       *const orig_type_right = right->base.type;
6668         type_t       *const type_left       = skip_typeref(orig_type_left);
6669         type_t       *const type_right      = skip_typeref(orig_type_right);
6670
6671         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6672                 /* TODO: improve error message */
6673                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6674                         errorf(HERE, "operation needs scalar types");
6675                 }
6676                 return;
6677         }
6678
6679         expression->base.type = type_int;
6680 }
6681
6682 /**
6683  * Check the semantic restrictions of a binary assign expression.
6684  */
6685 static void semantic_binexpr_assign(binary_expression_t *expression)
6686 {
6687         expression_t *left           = expression->left;
6688         type_t       *orig_type_left = left->base.type;
6689
6690         type_t *type_left = revert_automatic_type_conversion(left);
6691         type_left         = skip_typeref(orig_type_left);
6692
6693         if (!is_valid_assignment_lhs(left))
6694                 return;
6695
6696         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6697                         "assignment", &left->base.source_position);
6698         if (res_type == NULL) {
6699                 errorf(&expression->base.source_position,
6700                         "cannot assign to '%T' from '%T'",
6701                         orig_type_left, expression->right->base.type);
6702         } else {
6703                 expression->right = create_implicit_cast(expression->right, res_type);
6704         }
6705
6706         expression->base.type = orig_type_left;
6707 }
6708
6709 /**
6710  * Determine if the outermost operation (or parts thereof) of the given
6711  * expression has no effect in order to generate a warning about this fact.
6712  * Therefore in some cases this only examines some of the operands of the
6713  * expression (see comments in the function and examples below).
6714  * Examples:
6715  *   f() + 23;    // warning, because + has no effect
6716  *   x || f();    // no warning, because x controls execution of f()
6717  *   x ? y : f(); // warning, because y has no effect
6718  *   (void)x;     // no warning to be able to suppress the warning
6719  * This function can NOT be used for an "expression has definitely no effect"-
6720  * analysis. */
6721 static bool expression_has_effect(const expression_t *const expr)
6722 {
6723         switch (expr->kind) {
6724                 case EXPR_UNKNOWN:                   break;
6725                 case EXPR_INVALID:                   return true; /* do NOT warn */
6726                 case EXPR_REFERENCE:                 return false;
6727                 /* suppress the warning for microsoft __noop operations */
6728                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
6729                 case EXPR_CHARACTER_CONSTANT:        return false;
6730                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
6731                 case EXPR_STRING_LITERAL:            return false;
6732                 case EXPR_WIDE_STRING_LITERAL:       return false;
6733
6734                 case EXPR_CALL: {
6735                         const call_expression_t *const call = &expr->call;
6736                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6737                                 return true;
6738
6739                         switch (call->function->builtin_symbol.symbol->ID) {
6740                                 case T___builtin_va_end: return true;
6741                                 default:                 return false;
6742                         }
6743                 }
6744
6745                 /* Generate the warning if either the left or right hand side of a
6746                  * conditional expression has no effect */
6747                 case EXPR_CONDITIONAL: {
6748                         const conditional_expression_t *const cond = &expr->conditional;
6749                         return
6750                                 expression_has_effect(cond->true_expression) &&
6751                                 expression_has_effect(cond->false_expression);
6752                 }
6753
6754                 case EXPR_SELECT:                    return false;
6755                 case EXPR_ARRAY_ACCESS:              return false;
6756                 case EXPR_SIZEOF:                    return false;
6757                 case EXPR_CLASSIFY_TYPE:             return false;
6758                 case EXPR_ALIGNOF:                   return false;
6759
6760                 case EXPR_FUNCNAME:                  return false;
6761                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
6762                 case EXPR_BUILTIN_CONSTANT_P:        return false;
6763                 case EXPR_BUILTIN_PREFETCH:          return true;
6764                 case EXPR_OFFSETOF:                  return false;
6765                 case EXPR_VA_START:                  return true;
6766                 case EXPR_VA_ARG:                    return true;
6767                 case EXPR_STATEMENT:                 return true; // TODO
6768                 case EXPR_COMPOUND_LITERAL:          return false;
6769
6770                 case EXPR_UNARY_NEGATE:              return false;
6771                 case EXPR_UNARY_PLUS:                return false;
6772                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
6773                 case EXPR_UNARY_NOT:                 return false;
6774                 case EXPR_UNARY_DEREFERENCE:         return false;
6775                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
6776                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
6777                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
6778                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
6779                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
6780
6781                 /* Treat void casts as if they have an effect in order to being able to
6782                  * suppress the warning */
6783                 case EXPR_UNARY_CAST: {
6784                         type_t *const type = skip_typeref(expr->base.type);
6785                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
6786                 }
6787
6788                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
6789                 case EXPR_UNARY_ASSUME:              return true;
6790
6791                 case EXPR_BINARY_ADD:                return false;
6792                 case EXPR_BINARY_SUB:                return false;
6793                 case EXPR_BINARY_MUL:                return false;
6794                 case EXPR_BINARY_DIV:                return false;
6795                 case EXPR_BINARY_MOD:                return false;
6796                 case EXPR_BINARY_EQUAL:              return false;
6797                 case EXPR_BINARY_NOTEQUAL:           return false;
6798                 case EXPR_BINARY_LESS:               return false;
6799                 case EXPR_BINARY_LESSEQUAL:          return false;
6800                 case EXPR_BINARY_GREATER:            return false;
6801                 case EXPR_BINARY_GREATEREQUAL:       return false;
6802                 case EXPR_BINARY_BITWISE_AND:        return false;
6803                 case EXPR_BINARY_BITWISE_OR:         return false;
6804                 case EXPR_BINARY_BITWISE_XOR:        return false;
6805                 case EXPR_BINARY_SHIFTLEFT:          return false;
6806                 case EXPR_BINARY_SHIFTRIGHT:         return false;
6807                 case EXPR_BINARY_ASSIGN:             return true;
6808                 case EXPR_BINARY_MUL_ASSIGN:         return true;
6809                 case EXPR_BINARY_DIV_ASSIGN:         return true;
6810                 case EXPR_BINARY_MOD_ASSIGN:         return true;
6811                 case EXPR_BINARY_ADD_ASSIGN:         return true;
6812                 case EXPR_BINARY_SUB_ASSIGN:         return true;
6813                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
6814                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
6815                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6816                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6817                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
6818
6819                 /* Only examine the right hand side of && and ||, because the left hand
6820                  * side already has the effect of controlling the execution of the right
6821                  * hand side */
6822                 case EXPR_BINARY_LOGICAL_AND:
6823                 case EXPR_BINARY_LOGICAL_OR:
6824                 /* Only examine the right hand side of a comma expression, because the left
6825                  * hand side has a separate warning */
6826                 case EXPR_BINARY_COMMA:
6827                         return expression_has_effect(expr->binary.right);
6828
6829                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
6830                 case EXPR_BINARY_ISGREATER:          return false;
6831                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
6832                 case EXPR_BINARY_ISLESS:             return false;
6833                 case EXPR_BINARY_ISLESSEQUAL:        return false;
6834                 case EXPR_BINARY_ISLESSGREATER:      return false;
6835                 case EXPR_BINARY_ISUNORDERED:        return false;
6836         }
6837
6838         internal_errorf(HERE, "unexpected expression");
6839 }
6840
6841 static void semantic_comma(binary_expression_t *expression)
6842 {
6843         if (warning.unused_value) {
6844                 const expression_t *const left = expression->left;
6845                 if (!expression_has_effect(left)) {
6846                         warningf(&left->base.source_position,
6847                                  "left-hand operand of comma expression has no effect");
6848                 }
6849         }
6850         expression->base.type = expression->right->base.type;
6851 }
6852
6853 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
6854 static expression_t *parse_##binexpression_type(unsigned precedence,      \
6855                                                 expression_t *left)       \
6856 {                                                                         \
6857         eat(token_type);                                                      \
6858         source_position_t pos = *HERE;                                        \
6859                                                                           \
6860         expression_t *right = parse_sub_expression(precedence + lr);          \
6861                                                                           \
6862         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6863         binexpr->base.source_position = pos;                                  \
6864         binexpr->binary.left  = left;                                         \
6865         binexpr->binary.right = right;                                        \
6866         sfunc(&binexpr->binary);                                              \
6867                                                                           \
6868         return binexpr;                                                       \
6869 }
6870
6871 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
6872 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
6873 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
6874 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
6875 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
6876 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
6877 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
6878 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
6879 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
6880
6881 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
6882                       semantic_comparison, 1)
6883 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6884                       semantic_comparison, 1)
6885 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
6886                       semantic_comparison, 1)
6887 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
6888                       semantic_comparison, 1)
6889
6890 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6891                       semantic_binexpr_arithmetic, 1)
6892 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6893                       semantic_binexpr_arithmetic, 1)
6894 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6895                       semantic_binexpr_arithmetic, 1)
6896 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6897                       semantic_logical_op, 1)
6898 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6899                       semantic_logical_op, 1)
6900 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6901                       semantic_shift_op, 1)
6902 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6903                       semantic_shift_op, 1)
6904 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6905                       semantic_arithmetic_addsubb_assign, 0)
6906 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6907                       semantic_arithmetic_addsubb_assign, 0)
6908 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6909                       semantic_arithmetic_assign, 0)
6910 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6911                       semantic_arithmetic_assign, 0)
6912 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6913                       semantic_arithmetic_assign, 0)
6914 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6915                       semantic_arithmetic_assign, 0)
6916 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6917                       semantic_arithmetic_assign, 0)
6918 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6919                       semantic_arithmetic_assign, 0)
6920 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6921                       semantic_arithmetic_assign, 0)
6922 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6923                       semantic_arithmetic_assign, 0)
6924
6925 static expression_t *parse_sub_expression(unsigned precedence)
6926 {
6927         if(token.type < 0) {
6928                 return expected_expression_error();
6929         }
6930
6931         expression_parser_function_t *parser
6932                 = &expression_parsers[token.type];
6933         source_position_t             source_position = token.source_position;
6934         expression_t                 *left;
6935
6936         if(parser->parser != NULL) {
6937                 left = parser->parser(parser->precedence);
6938         } else {
6939                 left = parse_primary_expression();
6940         }
6941         assert(left != NULL);
6942         left->base.source_position = source_position;
6943
6944         while(true) {
6945                 if(token.type < 0) {
6946                         return expected_expression_error();
6947                 }
6948
6949                 parser = &expression_parsers[token.type];
6950                 if(parser->infix_parser == NULL)
6951                         break;
6952                 if(parser->infix_precedence < precedence)
6953                         break;
6954
6955                 left = parser->infix_parser(parser->infix_precedence, left);
6956
6957                 assert(left != NULL);
6958                 assert(left->kind != EXPR_UNKNOWN);
6959                 left->base.source_position = source_position;
6960         }
6961
6962         return left;
6963 }
6964
6965 /**
6966  * Parse an expression.
6967  */
6968 static expression_t *parse_expression(void)
6969 {
6970         return parse_sub_expression(1);
6971 }
6972
6973 /**
6974  * Register a parser for a prefix-like operator with given precedence.
6975  *
6976  * @param parser      the parser function
6977  * @param token_type  the token type of the prefix token
6978  * @param precedence  the precedence of the operator
6979  */
6980 static void register_expression_parser(parse_expression_function parser,
6981                                        int token_type, unsigned precedence)
6982 {
6983         expression_parser_function_t *entry = &expression_parsers[token_type];
6984
6985         if(entry->parser != NULL) {
6986                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6987                 panic("trying to register multiple expression parsers for a token");
6988         }
6989         entry->parser     = parser;
6990         entry->precedence = precedence;
6991 }
6992
6993 /**
6994  * Register a parser for an infix operator with given precedence.
6995  *
6996  * @param parser      the parser function
6997  * @param token_type  the token type of the infix operator
6998  * @param precedence  the precedence of the operator
6999  */
7000 static void register_infix_parser(parse_expression_infix_function parser,
7001                 int token_type, unsigned precedence)
7002 {
7003         expression_parser_function_t *entry = &expression_parsers[token_type];
7004
7005         if(entry->infix_parser != NULL) {
7006                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7007                 panic("trying to register multiple infix expression parsers for a "
7008                       "token");
7009         }
7010         entry->infix_parser     = parser;
7011         entry->infix_precedence = precedence;
7012 }
7013
7014 /**
7015  * Initialize the expression parsers.
7016  */
7017 static void init_expression_parsers(void)
7018 {
7019         memset(&expression_parsers, 0, sizeof(expression_parsers));
7020
7021         register_infix_parser(parse_array_expression,         '[',              30);
7022         register_infix_parser(parse_call_expression,          '(',              30);
7023         register_infix_parser(parse_select_expression,        '.',              30);
7024         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
7025         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7026                                                               T_PLUSPLUS,       30);
7027         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7028                                                               T_MINUSMINUS,     30);
7029
7030         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              17);
7031         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              17);
7032         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              17);
7033         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              16);
7034         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              16);
7035         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       15);
7036         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 15);
7037         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
7038         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
7039         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
7040         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
7041         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
7042         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7043                                                     T_EXCLAMATIONMARKEQUAL, 13);
7044         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
7045         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
7046         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
7047         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
7048         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
7049         register_infix_parser(parse_conditional_expression,   '?',               7);
7050         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
7051         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
7052         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
7053         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
7054         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
7055         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
7056         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7057                                                                 T_LESSLESSEQUAL, 2);
7058         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7059                                                           T_GREATERGREATEREQUAL, 2);
7060         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7061                                                                      T_ANDEQUAL, 2);
7062         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7063                                                                     T_PIPEEQUAL, 2);
7064         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7065                                                                    T_CARETEQUAL, 2);
7066
7067         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
7068
7069         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
7070         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
7071         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
7072         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
7073         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
7074         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
7075         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7076                                                                   T_PLUSPLUS,   25);
7077         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7078                                                                   T_MINUSMINUS, 25);
7079         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
7080         register_expression_parser(parse_alignof,                T___alignof__, 25);
7081         register_expression_parser(parse_extension,            T___extension__, 25);
7082         register_expression_parser(parse_builtin_classify_type,
7083                                                      T___builtin_classify_type, 25);
7084 }
7085
7086 /**
7087  * Parse a asm statement arguments specification.
7088  */
7089 static asm_argument_t *parse_asm_arguments(bool is_out)
7090 {
7091         asm_argument_t *result = NULL;
7092         asm_argument_t *last   = NULL;
7093
7094         while(token.type == T_STRING_LITERAL || token.type == '[') {
7095                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7096                 memset(argument, 0, sizeof(argument[0]));
7097
7098                 if(token.type == '[') {
7099                         eat('[');
7100                         if(token.type != T_IDENTIFIER) {
7101                                 parse_error_expected("while parsing asm argument",
7102                                                      T_IDENTIFIER, NULL);
7103                                 return NULL;
7104                         }
7105                         argument->symbol = token.v.symbol;
7106
7107                         expect(']');
7108                 }
7109
7110                 argument->constraints = parse_string_literals();
7111                 expect('(');
7112                 argument->expression = parse_expression();
7113                 if (is_out && !is_lvalue(argument->expression)) {
7114                         errorf(&argument->expression->base.source_position,
7115                                "asm output argument is not an lvalue");
7116                 }
7117                 expect(')');
7118
7119                 if(last != NULL) {
7120                         last->next = argument;
7121                 } else {
7122                         result = argument;
7123                 }
7124                 last = argument;
7125
7126                 if(token.type != ',')
7127                         break;
7128                 eat(',');
7129         }
7130
7131         return result;
7132 end_error:
7133         return NULL;
7134 }
7135
7136 /**
7137  * Parse a asm statement clobber specification.
7138  */
7139 static asm_clobber_t *parse_asm_clobbers(void)
7140 {
7141         asm_clobber_t *result = NULL;
7142         asm_clobber_t *last   = NULL;
7143
7144         while(token.type == T_STRING_LITERAL) {
7145                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7146                 clobber->clobber       = parse_string_literals();
7147
7148                 if(last != NULL) {
7149                         last->next = clobber;
7150                 } else {
7151                         result = clobber;
7152                 }
7153                 last = clobber;
7154
7155                 if(token.type != ',')
7156                         break;
7157                 eat(',');
7158         }
7159
7160         return result;
7161 }
7162
7163 /**
7164  * Parse an asm statement.
7165  */
7166 static statement_t *parse_asm_statement(void)
7167 {
7168         eat(T_asm);
7169
7170         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
7171         statement->base.source_position = token.source_position;
7172
7173         asm_statement_t *asm_statement = &statement->asms;
7174
7175         if(token.type == T_volatile) {
7176                 next_token();
7177                 asm_statement->is_volatile = true;
7178         }
7179
7180         expect('(');
7181         add_anchor_token(')');
7182         add_anchor_token(':');
7183         asm_statement->asm_text = parse_string_literals();
7184
7185         if(token.type != ':') {
7186                 rem_anchor_token(':');
7187                 goto end_of_asm;
7188         }
7189         eat(':');
7190
7191         asm_statement->outputs = parse_asm_arguments(true);
7192         if(token.type != ':') {
7193                 rem_anchor_token(':');
7194                 goto end_of_asm;
7195         }
7196         eat(':');
7197
7198         asm_statement->inputs = parse_asm_arguments(false);
7199         if(token.type != ':') {
7200                 rem_anchor_token(':');
7201                 goto end_of_asm;
7202         }
7203         rem_anchor_token(':');
7204         eat(':');
7205
7206         asm_statement->clobbers = parse_asm_clobbers();
7207
7208 end_of_asm:
7209         rem_anchor_token(')');
7210         expect(')');
7211         expect(';');
7212         return statement;
7213 end_error:
7214         return create_invalid_statement();
7215 }
7216
7217 /**
7218  * Parse a case statement.
7219  */
7220 static statement_t *parse_case_statement(void)
7221 {
7222         eat(T_case);
7223
7224         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7225
7226         statement->base.source_position  = token.source_position;
7227         statement->case_label.expression = parse_expression();
7228
7229         if (c_mode & _GNUC) {
7230                 if (token.type == T_DOTDOTDOT) {
7231                         next_token();
7232                         statement->case_label.end_range = parse_expression();
7233                 }
7234         }
7235
7236         expect(':');
7237
7238         if (! is_constant_expression(statement->case_label.expression)) {
7239                 errorf(&statement->base.source_position,
7240                        "case label does not reduce to an integer constant");
7241         } else {
7242                 /* TODO: check if the case label is already known */
7243                 if (current_switch != NULL) {
7244                         /* link all cases into the switch statement */
7245                         if (current_switch->last_case == NULL) {
7246                                 current_switch->first_case =
7247                                 current_switch->last_case  = &statement->case_label;
7248                         } else {
7249                                 current_switch->last_case->next = &statement->case_label;
7250                         }
7251                 } else {
7252                         errorf(&statement->base.source_position,
7253                                "case label not within a switch statement");
7254                 }
7255         }
7256         statement->case_label.statement = parse_statement();
7257
7258         return statement;
7259 end_error:
7260         return create_invalid_statement();
7261 }
7262
7263 /**
7264  * Finds an existing default label of a switch statement.
7265  */
7266 static case_label_statement_t *
7267 find_default_label(const switch_statement_t *statement)
7268 {
7269         case_label_statement_t *label = statement->first_case;
7270         for ( ; label != NULL; label = label->next) {
7271                 if (label->expression == NULL)
7272                         return label;
7273         }
7274         return NULL;
7275 }
7276
7277 /**
7278  * Parse a default statement.
7279  */
7280 static statement_t *parse_default_statement(void)
7281 {
7282         eat(T_default);
7283
7284         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7285
7286         statement->base.source_position = token.source_position;
7287
7288         expect(':');
7289         if (current_switch != NULL) {
7290                 const case_label_statement_t *def_label = find_default_label(current_switch);
7291                 if (def_label != NULL) {
7292                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7293                                &def_label->base.source_position);
7294                 } else {
7295                         /* link all cases into the switch statement */
7296                         if (current_switch->last_case == NULL) {
7297                                 current_switch->first_case =
7298                                         current_switch->last_case  = &statement->case_label;
7299                         } else {
7300                                 current_switch->last_case->next = &statement->case_label;
7301                         }
7302                 }
7303         } else {
7304                 errorf(&statement->base.source_position,
7305                         "'default' label not within a switch statement");
7306         }
7307         statement->case_label.statement = parse_statement();
7308
7309         return statement;
7310 end_error:
7311         return create_invalid_statement();
7312 }
7313
7314 /**
7315  * Return the declaration for a given label symbol or create a new one.
7316  */
7317 static declaration_t *get_label(symbol_t *symbol)
7318 {
7319         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7320         assert(current_function != NULL);
7321         /* if we found a label in the same function, then we already created the
7322          * declaration */
7323         if(candidate != NULL
7324                         && candidate->parent_scope == &current_function->scope) {
7325                 return candidate;
7326         }
7327
7328         /* otherwise we need to create a new one */
7329         declaration_t *const declaration = allocate_declaration_zero();
7330         declaration->namespc       = NAMESPACE_LABEL;
7331         declaration->symbol        = symbol;
7332
7333         label_push(declaration);
7334
7335         return declaration;
7336 }
7337
7338 /**
7339  * Parse a label statement.
7340  */
7341 static statement_t *parse_label_statement(void)
7342 {
7343         assert(token.type == T_IDENTIFIER);
7344         symbol_t *symbol = token.v.symbol;
7345         next_token();
7346
7347         declaration_t *label = get_label(symbol);
7348
7349         /* if source position is already set then the label is defined twice,
7350          * otherwise it was just mentioned in a goto so far */
7351         if(label->source_position.input_name != NULL) {
7352                 errorf(HERE, "duplicate label '%Y' (declared %P)",
7353                        symbol, &label->source_position);
7354         } else {
7355                 label->source_position = token.source_position;
7356         }
7357
7358         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7359
7360         statement->base.source_position = token.source_position;
7361         statement->label.label          = label;
7362
7363         eat(':');
7364
7365         if(token.type == '}') {
7366                 /* TODO only warn? */
7367                 if(false) {
7368                         warningf(HERE, "label at end of compound statement");
7369                         statement->label.statement = create_empty_statement();
7370                 } else {
7371                         errorf(HERE, "label at end of compound statement");
7372                         statement->label.statement = create_invalid_statement();
7373                 }
7374                 return statement;
7375         } else {
7376                 if (token.type == ';') {
7377                         /* eat an empty statement here, to avoid the warning about an empty
7378                          * after a label.  label:; is commonly used to have a label before
7379                          * a }. */
7380                         statement->label.statement = create_empty_statement();
7381                         next_token();
7382                 } else {
7383                         statement->label.statement = parse_statement();
7384                 }
7385         }
7386
7387         /* remember the labels's in a list for later checking */
7388         if (label_last == NULL) {
7389                 label_first = &statement->label;
7390         } else {
7391                 label_last->next = &statement->label;
7392         }
7393         label_last = &statement->label;
7394
7395         return statement;
7396 }
7397
7398 /**
7399  * Parse an if statement.
7400  */
7401 static statement_t *parse_if(void)
7402 {
7403         eat(T_if);
7404
7405         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
7406         statement->base.source_position = token.source_position;
7407
7408         expect('(');
7409         add_anchor_token(')');
7410         statement->ifs.condition = parse_expression();
7411         rem_anchor_token(')');
7412         expect(')');
7413
7414         add_anchor_token(T_else);
7415         statement->ifs.true_statement = parse_statement();
7416         rem_anchor_token(T_else);
7417
7418         if(token.type == T_else) {
7419                 next_token();
7420                 statement->ifs.false_statement = parse_statement();
7421         }
7422
7423         return statement;
7424 end_error:
7425         return create_invalid_statement();
7426 }
7427
7428 /**
7429  * Parse a switch statement.
7430  */
7431 static statement_t *parse_switch(void)
7432 {
7433         eat(T_switch);
7434
7435         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
7436         statement->base.source_position = token.source_position;
7437
7438         expect('(');
7439         expression_t *const expr = parse_expression();
7440         type_t       *      type = skip_typeref(expr->base.type);
7441         if (is_type_integer(type)) {
7442                 type = promote_integer(type);
7443         } else if (is_type_valid(type)) {
7444                 errorf(&expr->base.source_position,
7445                        "switch quantity is not an integer, but '%T'", type);
7446                 type = type_error_type;
7447         }
7448         statement->switchs.expression = create_implicit_cast(expr, type);
7449         expect(')');
7450
7451         switch_statement_t *rem = current_switch;
7452         current_switch          = &statement->switchs;
7453         statement->switchs.body = parse_statement();
7454         current_switch          = rem;
7455
7456         if(warning.switch_default &&
7457            find_default_label(&statement->switchs) == NULL) {
7458                 warningf(&statement->base.source_position, "switch has no default case");
7459         }
7460
7461         return statement;
7462 end_error:
7463         return create_invalid_statement();
7464 }
7465
7466 static statement_t *parse_loop_body(statement_t *const loop)
7467 {
7468         statement_t *const rem = current_loop;
7469         current_loop = loop;
7470
7471         statement_t *const body = parse_statement();
7472
7473         current_loop = rem;
7474         return body;
7475 }
7476
7477 /**
7478  * Parse a while statement.
7479  */
7480 static statement_t *parse_while(void)
7481 {
7482         eat(T_while);
7483
7484         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
7485         statement->base.source_position = token.source_position;
7486
7487         expect('(');
7488         add_anchor_token(')');
7489         statement->whiles.condition = parse_expression();
7490         rem_anchor_token(')');
7491         expect(')');
7492
7493         statement->whiles.body = parse_loop_body(statement);
7494
7495         return statement;
7496 end_error:
7497         return create_invalid_statement();
7498 }
7499
7500 /**
7501  * Parse a do statement.
7502  */
7503 static statement_t *parse_do(void)
7504 {
7505         eat(T_do);
7506
7507         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7508
7509         statement->base.source_position = token.source_position;
7510
7511         add_anchor_token(T_while);
7512         statement->do_while.body = parse_loop_body(statement);
7513         rem_anchor_token(T_while);
7514
7515         expect(T_while);
7516         expect('(');
7517         add_anchor_token(')');
7518         statement->do_while.condition = parse_expression();
7519         rem_anchor_token(')');
7520         expect(')');
7521         expect(';');
7522
7523         return statement;
7524 end_error:
7525         return create_invalid_statement();
7526 }
7527
7528 /**
7529  * Parse a for statement.
7530  */
7531 static statement_t *parse_for(void)
7532 {
7533         eat(T_for);
7534
7535         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
7536         statement->base.source_position = token.source_position;
7537
7538         int      top        = environment_top();
7539         scope_t *last_scope = scope;
7540         set_scope(&statement->fors.scope);
7541
7542         expect('(');
7543         add_anchor_token(')');
7544
7545         if(token.type != ';') {
7546                 if(is_declaration_specifier(&token, false)) {
7547                         parse_declaration(record_declaration);
7548                 } else {
7549                         add_anchor_token(';');
7550                         expression_t *const init = parse_expression();
7551                         statement->fors.initialisation = init;
7552                         if (warning.unused_value && !expression_has_effect(init)) {
7553                                 warningf(&init->base.source_position,
7554                                          "initialisation of 'for'-statement has no effect");
7555                         }
7556                         rem_anchor_token(';');
7557                         expect(';');
7558                 }
7559         } else {
7560                 expect(';');
7561         }
7562
7563         if(token.type != ';') {
7564                 add_anchor_token(';');
7565                 statement->fors.condition = parse_expression();
7566                 rem_anchor_token(';');
7567         }
7568         expect(';');
7569         if(token.type != ')') {
7570                 expression_t *const step = parse_expression();
7571                 statement->fors.step = step;
7572                 if (warning.unused_value && !expression_has_effect(step)) {
7573                         warningf(&step->base.source_position,
7574                                  "step of 'for'-statement has no effect");
7575                 }
7576         }
7577         rem_anchor_token(')');
7578         expect(')');
7579         statement->fors.body = parse_loop_body(statement);
7580
7581         assert(scope == &statement->fors.scope);
7582         set_scope(last_scope);
7583         environment_pop_to(top);
7584
7585         return statement;
7586
7587 end_error:
7588         rem_anchor_token(')');
7589         assert(scope == &statement->fors.scope);
7590         set_scope(last_scope);
7591         environment_pop_to(top);
7592
7593         return create_invalid_statement();
7594 }
7595
7596 /**
7597  * Parse a goto statement.
7598  */
7599 static statement_t *parse_goto(void)
7600 {
7601         eat(T_goto);
7602
7603         if(token.type != T_IDENTIFIER) {
7604                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7605                 eat_statement();
7606                 goto end_error;
7607         }
7608         symbol_t *symbol = token.v.symbol;
7609         next_token();
7610
7611         declaration_t *label = get_label(symbol);
7612
7613         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
7614         statement->base.source_position = token.source_position;
7615
7616         statement->gotos.label = label;
7617
7618         /* remember the goto's in a list for later checking */
7619         if (goto_last == NULL) {
7620                 goto_first = &statement->gotos;
7621         } else {
7622                 goto_last->next = &statement->gotos;
7623         }
7624         goto_last = &statement->gotos;
7625
7626         expect(';');
7627
7628         return statement;
7629 end_error:
7630         return create_invalid_statement();
7631 }
7632
7633 /**
7634  * Parse a continue statement.
7635  */
7636 static statement_t *parse_continue(void)
7637 {
7638         statement_t *statement;
7639         if (current_loop == NULL) {
7640                 errorf(HERE, "continue statement not within loop");
7641                 statement = create_invalid_statement();
7642         } else {
7643                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7644
7645                 statement->base.source_position = token.source_position;
7646         }
7647
7648         eat(T_continue);
7649         expect(';');
7650
7651         return statement;
7652 end_error:
7653         return create_invalid_statement();
7654 }
7655
7656 /**
7657  * Parse a break statement.
7658  */
7659 static statement_t *parse_break(void)
7660 {
7661         statement_t *statement;
7662         if (current_switch == NULL && current_loop == NULL) {
7663                 errorf(HERE, "break statement not within loop or switch");
7664                 statement = create_invalid_statement();
7665         } else {
7666                 statement = allocate_statement_zero(STATEMENT_BREAK);
7667
7668                 statement->base.source_position = token.source_position;
7669         }
7670
7671         eat(T_break);
7672         expect(';');
7673
7674         return statement;
7675 end_error:
7676         return create_invalid_statement();
7677 }
7678
7679 /**
7680  * Parse a __leave statement.
7681  */
7682 static statement_t *parse_leave(void)
7683 {
7684         statement_t *statement;
7685         if (current_try == NULL) {
7686                 errorf(HERE, "__leave statement not within __try");
7687                 statement = create_invalid_statement();
7688         } else {
7689                 statement = allocate_statement_zero(STATEMENT_LEAVE);
7690
7691                 statement->base.source_position = token.source_position;
7692         }
7693
7694         eat(T___leave);
7695         expect(';');
7696
7697         return statement;
7698 end_error:
7699         return create_invalid_statement();
7700 }
7701
7702 /**
7703  * Check if a given declaration represents a local variable.
7704  */
7705 static bool is_local_var_declaration(const declaration_t *declaration) {
7706         switch ((storage_class_tag_t) declaration->storage_class) {
7707         case STORAGE_CLASS_AUTO:
7708         case STORAGE_CLASS_REGISTER: {
7709                 const type_t *type = skip_typeref(declaration->type);
7710                 if(is_type_function(type)) {
7711                         return false;
7712                 } else {
7713                         return true;
7714                 }
7715         }
7716         default:
7717                 return false;
7718         }
7719 }
7720
7721 /**
7722  * Check if a given declaration represents a variable.
7723  */
7724 static bool is_var_declaration(const declaration_t *declaration) {
7725         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7726                 return false;
7727
7728         const type_t *type = skip_typeref(declaration->type);
7729         return !is_type_function(type);
7730 }
7731
7732 /**
7733  * Check if a given expression represents a local variable.
7734  */
7735 static bool is_local_variable(const expression_t *expression)
7736 {
7737         if (expression->base.kind != EXPR_REFERENCE) {
7738                 return false;
7739         }
7740         const declaration_t *declaration = expression->reference.declaration;
7741         return is_local_var_declaration(declaration);
7742 }
7743
7744 /**
7745  * Check if a given expression represents a local variable and
7746  * return its declaration then, else return NULL.
7747  */
7748 declaration_t *expr_is_variable(const expression_t *expression)
7749 {
7750         if (expression->base.kind != EXPR_REFERENCE) {
7751                 return NULL;
7752         }
7753         declaration_t *declaration = expression->reference.declaration;
7754         if (is_var_declaration(declaration))
7755                 return declaration;
7756         return NULL;
7757 }
7758
7759 /**
7760  * Parse a return statement.
7761  */
7762 static statement_t *parse_return(void)
7763 {
7764         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
7765         statement->base.source_position = token.source_position;
7766
7767         eat(T_return);
7768
7769         expression_t *return_value = NULL;
7770         if(token.type != ';') {
7771                 return_value = parse_expression();
7772         }
7773         expect(';');
7774
7775         const type_t *const func_type = current_function->type;
7776         assert(is_type_function(func_type));
7777         type_t *const return_type = skip_typeref(func_type->function.return_type);
7778
7779         if(return_value != NULL) {
7780                 type_t *return_value_type = skip_typeref(return_value->base.type);
7781
7782                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7783                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7784                         warningf(&statement->base.source_position,
7785                                  "'return' with a value, in function returning void");
7786                         return_value = NULL;
7787                 } else {
7788                         type_t *const res_type = semantic_assign(return_type,
7789                                 return_value, "'return'", &statement->base.source_position);
7790                         if (res_type == NULL) {
7791                                 errorf(&statement->base.source_position,
7792                                        "cannot return something of type '%T' in function returning '%T'",
7793                                        return_value->base.type, return_type);
7794                         } else {
7795                                 return_value = create_implicit_cast(return_value, res_type);
7796                         }
7797                 }
7798                 /* check for returning address of a local var */
7799                 if (return_value != NULL &&
7800                                 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7801                         const expression_t *expression = return_value->unary.value;
7802                         if (is_local_variable(expression)) {
7803                                 warningf(&statement->base.source_position,
7804                                          "function returns address of local variable");
7805                         }
7806                 }
7807         } else {
7808                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7809                         warningf(&statement->base.source_position,
7810                                  "'return' without value, in function returning non-void");
7811                 }
7812         }
7813         statement->returns.value = return_value;
7814
7815         return statement;
7816 end_error:
7817         return create_invalid_statement();
7818 }
7819
7820 /**
7821  * Parse a declaration statement.
7822  */
7823 static statement_t *parse_declaration_statement(void)
7824 {
7825         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7826
7827         statement->base.source_position = token.source_position;
7828
7829         declaration_t *before = last_declaration;
7830         parse_declaration(record_declaration);
7831
7832         if(before == NULL) {
7833                 statement->declaration.declarations_begin = scope->declarations;
7834         } else {
7835                 statement->declaration.declarations_begin = before->next;
7836         }
7837         statement->declaration.declarations_end = last_declaration;
7838
7839         return statement;
7840 }
7841
7842 /**
7843  * Parse an expression statement, ie. expr ';'.
7844  */
7845 static statement_t *parse_expression_statement(void)
7846 {
7847         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7848
7849         statement->base.source_position  = token.source_position;
7850         expression_t *const expr         = parse_expression();
7851         statement->expression.expression = expr;
7852
7853         expect(';');
7854
7855         return statement;
7856 end_error:
7857         return create_invalid_statement();
7858 }
7859
7860 /**
7861  * Parse a microsoft __try { } __finally { } or
7862  * __try{ } __except() { }
7863  */
7864 static statement_t *parse_ms_try_statment(void) {
7865         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
7866
7867         statement->base.source_position  = token.source_position;
7868         eat(T___try);
7869
7870         ms_try_statement_t *rem = current_try;
7871         current_try = &statement->ms_try;
7872         statement->ms_try.try_statement = parse_compound_statement(false);
7873         current_try = rem;
7874
7875         if(token.type == T___except) {
7876                 eat(T___except);
7877                 expect('(');
7878                 add_anchor_token(')');
7879                 expression_t *const expr = parse_expression();
7880                 type_t       *      type = skip_typeref(expr->base.type);
7881                 if (is_type_integer(type)) {
7882                         type = promote_integer(type);
7883                 } else if (is_type_valid(type)) {
7884                         errorf(&expr->base.source_position,
7885                                "__expect expression is not an integer, but '%T'", type);
7886                         type = type_error_type;
7887                 }
7888                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
7889                 rem_anchor_token(')');
7890                 expect(')');
7891                 statement->ms_try.final_statement = parse_compound_statement(false);
7892         } else if(token.type == T__finally) {
7893                 eat(T___finally);
7894                 statement->ms_try.final_statement = parse_compound_statement(false);
7895         } else {
7896                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
7897                 return create_invalid_statement();
7898         }
7899         return statement;
7900 end_error:
7901         return create_invalid_statement();
7902 }
7903
7904 /**
7905  * Parse a statement.
7906  * There's also parse_statement() which additionally checks for
7907  * "statement has no effect" warnings
7908  */
7909 static statement_t *intern_parse_statement(void)
7910 {
7911         statement_t *statement = NULL;
7912
7913         /* declaration or statement */
7914         add_anchor_token(';');
7915         switch(token.type) {
7916         case T_asm:
7917                 statement = parse_asm_statement();
7918                 break;
7919
7920         case T_case:
7921                 statement = parse_case_statement();
7922                 break;
7923
7924         case T_default:
7925                 statement = parse_default_statement();
7926                 break;
7927
7928         case '{':
7929                 statement = parse_compound_statement(false);
7930                 break;
7931
7932         case T_if:
7933                 statement = parse_if();
7934                 break;
7935
7936         case T_switch:
7937                 statement = parse_switch();
7938                 break;
7939
7940         case T_while:
7941                 statement = parse_while();
7942                 break;
7943
7944         case T_do:
7945                 statement = parse_do();
7946                 break;
7947
7948         case T_for:
7949                 statement = parse_for();
7950                 break;
7951
7952         case T_goto:
7953                 statement = parse_goto();
7954                 break;
7955
7956         case T_continue:
7957                 statement = parse_continue();
7958                 break;
7959
7960         case T_break:
7961                 statement = parse_break();
7962                 break;
7963
7964         case T___leave:
7965                 statement = parse_leave();
7966                 break;
7967
7968         case T_return:
7969                 statement = parse_return();
7970                 break;
7971
7972         case ';':
7973                 if(warning.empty_statement) {
7974                         warningf(HERE, "statement is empty");
7975                 }
7976                 statement = create_empty_statement();
7977                 next_token();
7978                 break;
7979
7980         case T_IDENTIFIER:
7981                 if(look_ahead(1)->type == ':') {
7982                         statement = parse_label_statement();
7983                         break;
7984                 }
7985
7986                 if(is_typedef_symbol(token.v.symbol)) {
7987                         statement = parse_declaration_statement();
7988                         break;
7989                 }
7990
7991                 statement = parse_expression_statement();
7992                 break;
7993
7994         case T___extension__:
7995                 /* this can be a prefix to a declaration or an expression statement */
7996                 /* we simply eat it now and parse the rest with tail recursion */
7997                 do {
7998                         next_token();
7999                 } while(token.type == T___extension__);
8000                 statement = parse_statement();
8001                 break;
8002
8003         DECLARATION_START
8004                 statement = parse_declaration_statement();
8005                 break;
8006
8007         case T___try:
8008                 statement = parse_ms_try_statment();
8009                 break;
8010
8011         default:
8012                 statement = parse_expression_statement();
8013                 break;
8014         }
8015         rem_anchor_token(';');
8016
8017         assert(statement != NULL
8018                         && statement->base.source_position.input_name != NULL);
8019
8020         return statement;
8021 }
8022
8023 /**
8024  * parse a statement and emits "statement has no effect" warning if needed
8025  * (This is really a wrapper around intern_parse_statement with check for 1
8026  *  single warning. It is needed, because for statement expressions we have
8027  *  to avoid the warning on the last statement)
8028  */
8029 static statement_t *parse_statement(void)
8030 {
8031         statement_t *statement = intern_parse_statement();
8032
8033         if(statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8034                 expression_t *expression = statement->expression.expression;
8035                 if(!expression_has_effect(expression)) {
8036                         warningf(&expression->base.source_position,
8037                                         "statement has no effect");
8038                 }
8039         }
8040
8041         return statement;
8042 }
8043
8044 /**
8045  * Parse a compound statement.
8046  */
8047 static statement_t *parse_compound_statement(bool inside_expression_statement)
8048 {
8049         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8050
8051         statement->base.source_position = token.source_position;
8052
8053         eat('{');
8054         add_anchor_token('}');
8055
8056         int      top        = environment_top();
8057         scope_t *last_scope = scope;
8058         set_scope(&statement->compound.scope);
8059
8060         statement_t *last_statement = NULL;
8061
8062         while(token.type != '}' && token.type != T_EOF) {
8063                 statement_t *sub_statement = intern_parse_statement();
8064                 if(is_invalid_statement(sub_statement)) {
8065                         /* an error occurred. if we are at an anchor, return */
8066                         if(at_anchor())
8067                                 goto end_error;
8068                         continue;
8069                 }
8070
8071                 if(last_statement != NULL) {
8072                         last_statement->base.next = sub_statement;
8073                 } else {
8074                         statement->compound.statements = sub_statement;
8075                 }
8076
8077                 while(sub_statement->base.next != NULL)
8078                         sub_statement = sub_statement->base.next;
8079
8080                 last_statement = sub_statement;
8081         }
8082
8083         if(token.type == '}') {
8084                 next_token();
8085         } else {
8086                 errorf(&statement->base.source_position,
8087                        "end of file while looking for closing '}'");
8088         }
8089
8090         /* look over all statements again to produce no effect warnings */
8091         if(warning.unused_value) {
8092                 statement_t *sub_statement = statement->compound.statements;
8093                 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8094                         if(sub_statement->kind != STATEMENT_EXPRESSION)
8095                                 continue;
8096                         /* don't emit a warning for the last expression in an expression
8097                          * statement as it has always an effect */
8098                         if(inside_expression_statement && sub_statement->base.next == NULL)
8099                                 continue;
8100
8101                         expression_t *expression = sub_statement->expression.expression;
8102                         if(!expression_has_effect(expression)) {
8103                                 warningf(&expression->base.source_position,
8104                                          "statement has no effect");
8105                         }
8106                 }
8107         }
8108
8109 end_error:
8110         rem_anchor_token('}');
8111         assert(scope == &statement->compound.scope);
8112         set_scope(last_scope);
8113         environment_pop_to(top);
8114
8115         return statement;
8116 }
8117
8118 /**
8119  * Initialize builtin types.
8120  */
8121 static void initialize_builtin_types(void)
8122 {
8123         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
8124         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
8125         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
8126         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
8127         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
8128         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8129         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
8130         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
8131
8132         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
8133         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8134         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
8135         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
8136 }
8137
8138 /**
8139  * Check for unused global static functions and variables
8140  */
8141 static void check_unused_globals(void)
8142 {
8143         if (!warning.unused_function && !warning.unused_variable)
8144                 return;
8145
8146         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8147                 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
8148                         continue;
8149
8150                 type_t *const type = decl->type;
8151                 const char *s;
8152                 if (is_type_function(skip_typeref(type))) {
8153                         if (!warning.unused_function || decl->is_inline)
8154                                 continue;
8155
8156                         s = (decl->init.statement != NULL ? "defined" : "declared");
8157                 } else {
8158                         if (!warning.unused_variable)
8159                                 continue;
8160
8161                         s = "defined";
8162                 }
8163
8164                 warningf(&decl->source_position, "'%#T' %s but not used",
8165                         type, decl->symbol, s);
8166         }
8167 }
8168
8169 /**
8170  * Parse a translation unit.
8171  */
8172 static void parse_translation_unit(void)
8173 {
8174         while(token.type != T_EOF) {
8175                 if (token.type == ';') {
8176                         /* TODO error in strict mode */
8177                         warningf(HERE, "stray ';' outside of function");
8178                         next_token();
8179                 } else {
8180                         parse_external_declaration();
8181                 }
8182         }
8183 }
8184
8185 /**
8186  * Parse the input.
8187  *
8188  * @return  the translation unit or NULL if errors occurred.
8189  */
8190 void start_parsing(void)
8191 {
8192         environment_stack = NEW_ARR_F(stack_entry_t, 0);
8193         label_stack       = NEW_ARR_F(stack_entry_t, 0);
8194         diagnostic_count  = 0;
8195         error_count       = 0;
8196         warning_count     = 0;
8197
8198         type_set_output(stderr);
8199         ast_set_output(stderr);
8200
8201         assert(unit == NULL);
8202         unit = allocate_ast_zero(sizeof(unit[0]));
8203
8204         assert(global_scope == NULL);
8205         global_scope = &unit->scope;
8206
8207         assert(scope == NULL);
8208         set_scope(&unit->scope);
8209
8210         initialize_builtin_types();
8211 }
8212
8213 translation_unit_t *finish_parsing(void)
8214 {
8215         assert(scope == &unit->scope);
8216         scope          = NULL;
8217         last_declaration = NULL;
8218
8219         assert(global_scope == &unit->scope);
8220         check_unused_globals();
8221         global_scope = NULL;
8222
8223         DEL_ARR_F(environment_stack);
8224         DEL_ARR_F(label_stack);
8225
8226         translation_unit_t *result = unit;
8227         unit = NULL;
8228         return result;
8229 }
8230
8231 void parse(void)
8232 {
8233         lookahead_bufpos = 0;
8234         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8235                 next_token();
8236         }
8237         parse_translation_unit();
8238 }
8239
8240 /**
8241  * Initialize the parser.
8242  */
8243 void init_parser(void)
8244 {
8245         if(c_mode & _MS) {
8246                 /* add predefined symbols for extended-decl-modifier */
8247                 sym_align      = symbol_table_insert("align");
8248                 sym_allocate   = symbol_table_insert("allocate");
8249                 sym_dllimport  = symbol_table_insert("dllimport");
8250                 sym_dllexport  = symbol_table_insert("dllexport");
8251                 sym_naked      = symbol_table_insert("naked");
8252                 sym_noinline   = symbol_table_insert("noinline");
8253                 sym_noreturn   = symbol_table_insert("noreturn");
8254                 sym_nothrow    = symbol_table_insert("nothrow");
8255                 sym_novtable   = symbol_table_insert("novtable");
8256                 sym_property   = symbol_table_insert("property");
8257                 sym_get        = symbol_table_insert("get");
8258                 sym_put        = symbol_table_insert("put");
8259                 sym_selectany  = symbol_table_insert("selectany");
8260                 sym_thread     = symbol_table_insert("thread");
8261                 sym_uuid       = symbol_table_insert("uuid");
8262                 sym_deprecated = symbol_table_insert("deprecated");
8263                 sym_restrict   = symbol_table_insert("restrict");
8264                 sym_noalias    = symbol_table_insert("noalias");
8265         }
8266         memset(token_anchor_set, 0, sizeof(token_anchor_set));
8267
8268         init_expression_parsers();
8269         obstack_init(&temp_obst);
8270
8271         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8272         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8273 }
8274
8275 /**
8276  * Terminate the parser.
8277  */
8278 void exit_parser(void)
8279 {
8280         obstack_free(&temp_obst, NULL);
8281 }