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