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