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