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