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