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