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