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