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