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