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