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