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