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