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