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