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