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