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