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