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