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