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