6ae0ed7fe5f1438148ee23fc215ca4f85dd07c44
[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         parse_declaration_specifiers(&specifiers);
4711
4712         if (token.type == ';') {
4713                 parse_anonymous_declaration_rest(&specifiers);
4714         } else {
4715                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4716                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4717         }
4718 }
4719
4720 static type_t *get_default_promoted_type(type_t *orig_type)
4721 {
4722         type_t *result = orig_type;
4723
4724         type_t *type = skip_typeref(orig_type);
4725         if (is_type_integer(type)) {
4726                 result = promote_integer(type);
4727         } else if (type == type_float) {
4728                 result = type_double;
4729         }
4730
4731         return result;
4732 }
4733
4734 static void parse_kr_declaration_list(declaration_t *declaration)
4735 {
4736         type_t *type = skip_typeref(declaration->type);
4737         if (!is_type_function(type))
4738                 return;
4739
4740         if (!type->function.kr_style_parameters)
4741                 return;
4742
4743         /* push function parameters */
4744         int       top        = environment_top();
4745         scope_t  *last_scope = scope;
4746         set_scope(&declaration->scope);
4747
4748         declaration_t *parameter = declaration->scope.declarations;
4749         for ( ; parameter != NULL; parameter = parameter->next) {
4750                 assert(parameter->parent_scope == NULL);
4751                 parameter->parent_scope = scope;
4752                 environment_push(parameter);
4753         }
4754
4755         /* parse declaration list */
4756         while (is_declaration_specifier(&token, false)) {
4757                 parse_declaration(finished_kr_declaration);
4758         }
4759
4760         /* pop function parameters */
4761         assert(scope == &declaration->scope);
4762         set_scope(last_scope);
4763         environment_pop_to(top);
4764
4765         /* update function type */
4766         type_t *new_type = duplicate_type(type);
4767
4768         function_parameter_t *parameters     = NULL;
4769         function_parameter_t *last_parameter = NULL;
4770
4771         declaration_t *parameter_declaration = declaration->scope.declarations;
4772         for( ; parameter_declaration != NULL;
4773                         parameter_declaration = parameter_declaration->next) {
4774                 type_t *parameter_type = parameter_declaration->type;
4775                 if (parameter_type == NULL) {
4776                         if (strict_mode) {
4777                                 errorf(HERE, "no type specified for function parameter '%Y'",
4778                                        parameter_declaration->symbol);
4779                         } else {
4780                                 if (warning.implicit_int) {
4781                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4782                                                 parameter_declaration->symbol);
4783                                 }
4784                                 parameter_type              = type_int;
4785                                 parameter_declaration->type = parameter_type;
4786                         }
4787                 }
4788
4789                 semantic_parameter(parameter_declaration);
4790                 parameter_type = parameter_declaration->type;
4791
4792                 /*
4793                  * we need the default promoted types for the function type
4794                  */
4795                 parameter_type = get_default_promoted_type(parameter_type);
4796
4797                 function_parameter_t *function_parameter
4798                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4799                 memset(function_parameter, 0, sizeof(function_parameter[0]));
4800
4801                 function_parameter->type = parameter_type;
4802                 if (last_parameter != NULL) {
4803                         last_parameter->next = function_parameter;
4804                 } else {
4805                         parameters = function_parameter;
4806                 }
4807                 last_parameter = function_parameter;
4808         }
4809
4810         /* Â§ 6.9.1.7: A K&R style parameter list does NOT act as a function
4811          * prototype */
4812         new_type->function.parameters             = parameters;
4813         new_type->function.unspecified_parameters = true;
4814
4815         type = typehash_insert(new_type);
4816         if (type != new_type) {
4817                 obstack_free(type_obst, new_type);
4818         }
4819
4820         declaration->type = type;
4821 }
4822
4823 static bool first_err = true;
4824
4825 /**
4826  * When called with first_err set, prints the name of the current function,
4827  * else does noting.
4828  */
4829 static void print_in_function(void)
4830 {
4831         if (first_err) {
4832                 first_err = false;
4833                 diagnosticf("%s: In function '%Y':\n",
4834                         current_function->source_position.input_name,
4835                         current_function->symbol);
4836         }
4837 }
4838
4839 /**
4840  * Check if all labels are defined in the current function.
4841  * Check if all labels are used in the current function.
4842  */
4843 static void check_labels(void)
4844 {
4845         for (const goto_statement_t *goto_statement = goto_first;
4846             goto_statement != NULL;
4847             goto_statement = goto_statement->next) {
4848                 /* skip computed gotos */
4849                 if (goto_statement->expression != NULL)
4850                         continue;
4851
4852                 declaration_t *label = goto_statement->label;
4853
4854                 label->used = true;
4855                 if (label->source_position.input_name == NULL) {
4856                         print_in_function();
4857                         errorf(&goto_statement->base.source_position,
4858                                "label '%Y' used but not defined", label->symbol);
4859                  }
4860         }
4861         goto_first = goto_last = NULL;
4862
4863         if (warning.unused_label) {
4864                 for (const label_statement_t *label_statement = label_first;
4865                          label_statement != NULL;
4866                          label_statement = label_statement->next) {
4867                         const declaration_t *label = label_statement->label;
4868
4869                         if (! label->used) {
4870                                 print_in_function();
4871                                 warningf(&label_statement->base.source_position,
4872                                         "label '%Y' defined but not used", label->symbol);
4873                         }
4874                 }
4875         }
4876         label_first = label_last = NULL;
4877 }
4878
4879 /**
4880  * Check declarations of current_function for unused entities.
4881  */
4882 static void check_declarations(void)
4883 {
4884         if (warning.unused_parameter) {
4885                 const scope_t *scope = &current_function->scope;
4886
4887                 if (is_sym_main(current_function->symbol)) {
4888                         /* do not issue unused warnings for main */
4889                         return;
4890                 }
4891                 const declaration_t *parameter = scope->declarations;
4892                 for (; parameter != NULL; parameter = parameter->next) {
4893                         if (! parameter->used) {
4894                                 print_in_function();
4895                                 warningf(&parameter->source_position,
4896                                          "unused parameter '%Y'", parameter->symbol);
4897                         }
4898                 }
4899         }
4900         if (warning.unused_variable) {
4901         }
4902 }
4903
4904 static int determine_truth(expression_t const* const cond)
4905 {
4906         return
4907                 !is_constant_expression(cond) ? 0 :
4908                 fold_constant(cond) != 0      ? 1 :
4909                 -1;
4910 }
4911
4912 static bool noreturn_candidate;
4913
4914 static void check_reachable(statement_t *const stmt)
4915 {
4916         if (stmt->base.reachable)
4917                 return;
4918         if (stmt->kind != STATEMENT_DO_WHILE)
4919                 stmt->base.reachable = true;
4920
4921         statement_t *last = stmt;
4922         statement_t *next;
4923         switch (stmt->kind) {
4924                 case STATEMENT_INVALID:
4925                 case STATEMENT_EMPTY:
4926                 case STATEMENT_DECLARATION:
4927                 case STATEMENT_ASM:
4928                         next = stmt->base.next;
4929                         break;
4930
4931                 case STATEMENT_COMPOUND:
4932                         next = stmt->compound.statements;
4933                         break;
4934
4935                 case STATEMENT_RETURN:
4936                         noreturn_candidate = false;
4937                         return;
4938
4939                 case STATEMENT_IF: {
4940                         if_statement_t const* const ifs = &stmt->ifs;
4941                         int            const        val = determine_truth(ifs->condition);
4942
4943                         if (val >= 0)
4944                                 check_reachable(ifs->true_statement);
4945
4946                         if (val > 0)
4947                                 return;
4948
4949                         if (ifs->false_statement != NULL) {
4950                                 check_reachable(ifs->false_statement);
4951                                 return;
4952                         }
4953
4954                         next = stmt->base.next;
4955                         break;
4956                 }
4957
4958                 case STATEMENT_SWITCH: {
4959                         switch_statement_t const *const switchs = &stmt->switchs;
4960                         expression_t       const *const expr    = switchs->expression;
4961
4962                         if (is_constant_expression(expr)) {
4963                                 long                    const val      = fold_constant(expr);
4964                                 case_label_statement_t *      defaults = NULL;
4965                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4966                                         if (i->expression == NULL) {
4967                                                 defaults = i;
4968                                                 continue;
4969                                         }
4970
4971                                         if (i->first_case <= val && val <= i->last_case) {
4972                                                 check_reachable((statement_t*)i);
4973                                                 return;
4974                                         }
4975                                 }
4976
4977                                 if (defaults != NULL) {
4978                                         check_reachable((statement_t*)defaults);
4979                                         return;
4980                                 }
4981                         } else {
4982                                 bool has_default = false;
4983                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4984                                         if (i->expression == NULL)
4985                                                 has_default = true;
4986
4987                                         check_reachable((statement_t*)i);
4988                                 }
4989
4990                                 if (has_default)
4991                                         return;
4992                         }
4993
4994                         next = stmt->base.next;
4995                         break;
4996                 }
4997
4998                 case STATEMENT_EXPRESSION: {
4999                         /* Check for noreturn function call */
5000                         expression_t const *const expr = stmt->expression.expression;
5001                         if (expr->kind == EXPR_CALL) {
5002                                 expression_t const *const func = expr->call.function;
5003                                 if (func->kind == EXPR_REFERENCE) {
5004                                         declaration_t const *const decl = func->reference.declaration;
5005                                         if (decl != NULL && decl->modifiers & DM_NORETURN) {
5006                                                 return;
5007                                         }
5008                                 }
5009                         }
5010
5011                         next = stmt->base.next;
5012                         break;
5013                 }
5014
5015                 case STATEMENT_CONTINUE: {
5016                         statement_t *parent = stmt;
5017                         for (;;) {
5018                                 parent = parent->base.parent;
5019                                 if (parent == NULL) /* continue not within loop */
5020                                         return;
5021
5022                                 next = parent;
5023                                 switch (parent->kind) {
5024                                         case STATEMENT_WHILE:    goto continue_while;
5025                                         case STATEMENT_DO_WHILE: goto continue_do_while;
5026                                         case STATEMENT_FOR:      goto continue_for;
5027
5028                                         default: break;
5029                                 }
5030                         }
5031                 }
5032
5033                 case STATEMENT_BREAK: {
5034                         statement_t *parent = stmt;
5035                         for (;;) {
5036                                 parent = parent->base.parent;
5037                                 if (parent == NULL) /* break not within loop/switch */
5038                                         return;
5039
5040                                 switch (parent->kind) {
5041                                         case STATEMENT_SWITCH:
5042                                         case STATEMENT_WHILE:
5043                                         case STATEMENT_DO_WHILE:
5044                                         case STATEMENT_FOR:
5045                                                 last = parent;
5046                                                 next = parent->base.next;
5047                                                 goto found_break_parent;
5048
5049                                         default: break;
5050                                 }
5051                         }
5052 found_break_parent:
5053                         break;
5054                 }
5055
5056                 case STATEMENT_GOTO:
5057                         if (stmt->gotos.expression) {
5058                                 statement_t *parent = stmt->base.parent;
5059                                 if (parent == NULL) /* top level goto */
5060                                         return;
5061                                 next = parent;
5062                         } else {
5063                                 next = stmt->gotos.label->init.statement;
5064                                 if (next == NULL) /* missing label */
5065                                         return;
5066                         }
5067                         break;
5068
5069                 case STATEMENT_LABEL:
5070                         next = stmt->label.statement;
5071                         break;
5072
5073                 case STATEMENT_CASE_LABEL:
5074                         next = stmt->case_label.statement;
5075                         break;
5076
5077                 case STATEMENT_WHILE: {
5078                         while_statement_t const *const whiles = &stmt->whiles;
5079                         int                      const val    = determine_truth(whiles->condition);
5080
5081                         if (val >= 0)
5082                                 check_reachable(whiles->body);
5083
5084                         if (val > 0)
5085                                 return;
5086
5087                         next = stmt->base.next;
5088                         break;
5089                 }
5090
5091                 case STATEMENT_DO_WHILE:
5092                         next = stmt->do_while.body;
5093                         break;
5094
5095                 case STATEMENT_FOR: {
5096                         for_statement_t *const fors = &stmt->fors;
5097
5098                         if (fors->condition_reachable)
5099                                 return;
5100                         fors->condition_reachable = true;
5101
5102                         expression_t const *const cond = fors->condition;
5103                         int          const        val  =
5104                                 cond == NULL ? 1 : determine_truth(cond);
5105
5106                         if (val >= 0)
5107                                 check_reachable(fors->body);
5108
5109                         if (val > 0)
5110                                 return;
5111
5112                         next = stmt->base.next;
5113                         break;
5114                 }
5115
5116                 case STATEMENT_MS_TRY: {
5117                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
5118                         check_reachable(ms_try->try_statement);
5119                         next = ms_try->final_statement;
5120                         break;
5121                 }
5122
5123                 case STATEMENT_LEAVE: {
5124                         statement_t *parent = stmt;
5125                         for (;;) {
5126                                 parent = parent->base.parent;
5127                                 if (parent == NULL) /* __leave not within __try */
5128                                         return;
5129
5130                                 if (parent->kind == STATEMENT_MS_TRY) {
5131                                         last = parent;
5132                                         next = parent->ms_try.final_statement;
5133                                         break;
5134                                 }
5135                         }
5136                         break;
5137                 }
5138         }
5139
5140         while (next == NULL) {
5141                 next = last->base.parent;
5142                 if (next == NULL) {
5143                         noreturn_candidate = false;
5144
5145                         type_t *const type = current_function->type;
5146                         assert(is_type_function(type));
5147                         type_t *const ret  = skip_typeref(type->function.return_type);
5148                         if (warning.return_type                    &&
5149                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5150                             is_type_valid(ret)                     &&
5151                             !is_sym_main(current_function->symbol)) {
5152                                 warningf(&stmt->base.source_position,
5153                                          "control reaches end of non-void function");
5154                         }
5155                         return;
5156                 }
5157
5158                 switch (next->kind) {
5159                         case STATEMENT_INVALID:
5160                         case STATEMENT_EMPTY:
5161                         case STATEMENT_DECLARATION:
5162                         case STATEMENT_EXPRESSION:
5163                         case STATEMENT_ASM:
5164                         case STATEMENT_RETURN:
5165                         case STATEMENT_CONTINUE:
5166                         case STATEMENT_BREAK:
5167                         case STATEMENT_GOTO:
5168                         case STATEMENT_LEAVE:
5169                                 panic("invalid control flow in function");
5170
5171                         case STATEMENT_COMPOUND:
5172                         case STATEMENT_IF:
5173                         case STATEMENT_SWITCH:
5174                         case STATEMENT_LABEL:
5175                         case STATEMENT_CASE_LABEL:
5176                                 last = next;
5177                                 next = next->base.next;
5178                                 break;
5179
5180                         case STATEMENT_WHILE: {
5181 continue_while:
5182                                 if (next->base.reachable)
5183                                         return;
5184                                 next->base.reachable = true;
5185
5186                                 while_statement_t const *const whiles = &next->whiles;
5187                                 int                      const val    = determine_truth(whiles->condition);
5188
5189                                 if (val >= 0)
5190                                         check_reachable(whiles->body);
5191
5192                                 if (val > 0)
5193                                         return;
5194
5195                                 last = next;
5196                                 next = next->base.next;
5197                                 break;
5198                         }
5199
5200                         case STATEMENT_DO_WHILE: {
5201 continue_do_while:
5202                                 if (next->base.reachable)
5203                                         return;
5204                                 next->base.reachable = true;
5205
5206                                 do_while_statement_t const *const dw  = &next->do_while;
5207                                 int                  const        val = determine_truth(dw->condition);
5208
5209                                 if (val >= 0)
5210                                         check_reachable(dw->body);
5211
5212                                 if (val > 0)
5213                                         return;
5214
5215                                 last = next;
5216                                 next = next->base.next;
5217                                 break;
5218                         }
5219
5220                         case STATEMENT_FOR: {
5221 continue_for:;
5222                                 for_statement_t *const fors = &next->fors;
5223
5224                                 fors->step_reachable = true;
5225
5226                                 if (fors->condition_reachable)
5227                                         return;
5228                                 fors->condition_reachable = true;
5229
5230                                 expression_t const *const cond = fors->condition;
5231                                 int          const        val  =
5232                                         cond == NULL ? 1 : determine_truth(cond);
5233
5234                                 if (val >= 0)
5235                                         check_reachable(fors->body);
5236
5237                                 if (val > 0)
5238                                         return;
5239
5240                                 last = next;
5241                                 next = next->base.next;
5242                                 break;
5243                         }
5244
5245                         case STATEMENT_MS_TRY:
5246                                 last = next;
5247                                 next = next->ms_try.final_statement;
5248                                 break;
5249                 }
5250         }
5251
5252         if (next == NULL) {
5253                 next = stmt->base.parent;
5254                 if (next == NULL) {
5255                         warningf(&stmt->base.source_position,
5256                                  "control reaches end of non-void function");
5257                 }
5258         }
5259
5260         check_reachable(next);
5261 }
5262
5263 static void check_unreachable(statement_t const* const stmt)
5264 {
5265         if (!stmt->base.reachable            &&
5266             stmt->kind != STATEMENT_DO_WHILE &&
5267             stmt->kind != STATEMENT_FOR      &&
5268             (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5269                 warningf(&stmt->base.source_position, "statement is unreachable");
5270         }
5271
5272         switch (stmt->kind) {
5273                 case STATEMENT_INVALID:
5274                 case STATEMENT_EMPTY:
5275                 case STATEMENT_RETURN:
5276                 case STATEMENT_DECLARATION:
5277                 case STATEMENT_EXPRESSION:
5278                 case STATEMENT_CONTINUE:
5279                 case STATEMENT_BREAK:
5280                 case STATEMENT_GOTO:
5281                 case STATEMENT_ASM:
5282                 case STATEMENT_LEAVE:
5283                         break;
5284
5285                 case STATEMENT_COMPOUND:
5286                         if (stmt->compound.statements)
5287                                 check_unreachable(stmt->compound.statements);
5288                         break;
5289
5290                 case STATEMENT_IF:
5291                         check_unreachable(stmt->ifs.true_statement);
5292                         if (stmt->ifs.false_statement != NULL)
5293                                 check_unreachable(stmt->ifs.false_statement);
5294                         break;
5295
5296                 case STATEMENT_SWITCH:
5297                         check_unreachable(stmt->switchs.body);
5298                         break;
5299
5300                 case STATEMENT_LABEL:
5301                         check_unreachable(stmt->label.statement);
5302                         break;
5303
5304                 case STATEMENT_CASE_LABEL:
5305                         check_unreachable(stmt->case_label.statement);
5306                         break;
5307
5308                 case STATEMENT_WHILE:
5309                         check_unreachable(stmt->whiles.body);
5310                         break;
5311
5312                 case STATEMENT_DO_WHILE:
5313                         check_unreachable(stmt->do_while.body);
5314                         if (!stmt->base.reachable) {
5315                                 expression_t const *const cond = stmt->do_while.condition;
5316                                 if (determine_truth(cond) >= 0) {
5317                                         warningf(&cond->base.source_position,
5318                                                  "condition of do-while-loop is unreachable");
5319                                 }
5320                         }
5321                         break;
5322
5323                 case STATEMENT_FOR: {
5324                         for_statement_t const* const fors = &stmt->fors;
5325
5326                         // if init and step are unreachable, cond is unreachable, too
5327                         if (!stmt->base.reachable && !fors->step_reachable) {
5328                                 warningf(&stmt->base.source_position, "statement is unreachable");
5329                         } else {
5330                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
5331                                         warningf(&fors->initialisation->base.source_position,
5332                                                  "initialisation of for-statement is unreachable");
5333                                 }
5334
5335                                 if (!fors->condition_reachable && fors->condition != NULL) {
5336                                         warningf(&fors->condition->base.source_position,
5337                                                  "condition of for-statement is unreachable");
5338                                 }
5339
5340                                 if (!fors->step_reachable && fors->step != NULL) {
5341                                         warningf(&fors->step->base.source_position,
5342                                                  "step of for-statement is unreachable");
5343                                 }
5344                         }
5345
5346                         check_unreachable(fors->body);
5347                         break;
5348                 }
5349
5350                 case STATEMENT_MS_TRY: {
5351                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
5352                         check_unreachable(ms_try->try_statement);
5353                         check_unreachable(ms_try->final_statement);
5354                 }
5355         }
5356
5357         if (stmt->base.next)
5358                 check_unreachable(stmt->base.next);
5359 }
5360
5361 static void parse_external_declaration(void)
5362 {
5363         /* function-definitions and declarations both start with declaration
5364          * specifiers */
5365         declaration_specifiers_t specifiers;
5366         memset(&specifiers, 0, sizeof(specifiers));
5367
5368         add_anchor_token(';');
5369         parse_declaration_specifiers(&specifiers);
5370         rem_anchor_token(';');
5371
5372         /* must be a declaration */
5373         if (token.type == ';') {
5374                 parse_anonymous_declaration_rest(&specifiers);
5375                 return;
5376         }
5377
5378         add_anchor_token(',');
5379         add_anchor_token('=');
5380         add_anchor_token(';');
5381
5382         /* declarator is common to both function-definitions and declarations */
5383         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5384
5385         rem_anchor_token(',');
5386         rem_anchor_token('=');
5387         rem_anchor_token(';');
5388
5389         /* must be a declaration */
5390         switch (token.type) {
5391                 case ',':
5392                 case ';':
5393                 case '=':
5394                         parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5395                         return;
5396         }
5397
5398         /* must be a function definition */
5399         parse_kr_declaration_list(ndeclaration);
5400
5401         if (token.type != '{') {
5402                 parse_error_expected("while parsing function definition", '{', NULL);
5403                 eat_until_matching_token(';');
5404                 return;
5405         }
5406
5407         type_t *type = ndeclaration->type;
5408
5409         /* note that we don't skip typerefs: the standard doesn't allow them here
5410          * (so we can't use is_type_function here) */
5411         if (type->kind != TYPE_FUNCTION) {
5412                 if (is_type_valid(type)) {
5413                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
5414                                type, ndeclaration->symbol);
5415                 }
5416                 eat_block();
5417                 return;
5418         }
5419
5420         if (warning.aggregate_return &&
5421             is_type_compound(skip_typeref(type->function.return_type))) {
5422                 warningf(HERE, "function '%Y' returns an aggregate",
5423                          ndeclaration->symbol);
5424         }
5425         if (warning.traditional && !type->function.unspecified_parameters) {
5426                 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5427                         ndeclaration->symbol);
5428         }
5429         if (warning.old_style_definition && type->function.unspecified_parameters) {
5430                 warningf(HERE, "old-style function definition '%Y'",
5431                         ndeclaration->symbol);
5432         }
5433
5434         /* Â§ 6.7.5.3 (14) a function definition with () means no
5435          * parameters (and not unspecified parameters) */
5436         if (type->function.unspecified_parameters
5437                         && type->function.parameters == NULL
5438                         && !type->function.kr_style_parameters) {
5439                 type_t *duplicate = duplicate_type(type);
5440                 duplicate->function.unspecified_parameters = false;
5441
5442                 type = typehash_insert(duplicate);
5443                 if (type != duplicate) {
5444                         obstack_free(type_obst, duplicate);
5445                 }
5446                 ndeclaration->type = type;
5447         }
5448
5449         declaration_t *const declaration = record_declaration(ndeclaration, true);
5450         if (ndeclaration != declaration) {
5451                 declaration->scope = ndeclaration->scope;
5452         }
5453         type = skip_typeref(declaration->type);
5454
5455         /* push function parameters and switch scope */
5456         int       top        = environment_top();
5457         scope_t  *last_scope = scope;
5458         set_scope(&declaration->scope);
5459
5460         declaration_t *parameter = declaration->scope.declarations;
5461         for( ; parameter != NULL; parameter = parameter->next) {
5462                 if (parameter->parent_scope == &ndeclaration->scope) {
5463                         parameter->parent_scope = scope;
5464                 }
5465                 assert(parameter->parent_scope == NULL
5466                                 || parameter->parent_scope == scope);
5467                 parameter->parent_scope = scope;
5468                 if (parameter->symbol == NULL) {
5469                         errorf(&parameter->source_position, "parameter name omitted");
5470                         continue;
5471                 }
5472                 environment_push(parameter);
5473         }
5474
5475         if (declaration->init.statement != NULL) {
5476                 parser_error_multiple_definition(declaration, HERE);
5477                 eat_block();
5478         } else {
5479                 /* parse function body */
5480                 int            label_stack_top      = label_top();
5481                 declaration_t *old_current_function = current_function;
5482                 current_function                    = declaration;
5483                 current_parent                      = NULL;
5484
5485                 statement_t *const body = parse_compound_statement(false);
5486                 declaration->init.statement = body;
5487                 first_err = true;
5488                 check_labels();
5489                 check_declarations();
5490                 if (warning.return_type      ||
5491                     warning.unreachable_code ||
5492                     (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5493                         noreturn_candidate = true;
5494                         check_reachable(body);
5495                         if (warning.unreachable_code)
5496                                 check_unreachable(body);
5497                         if (warning.missing_noreturn &&
5498                             noreturn_candidate       &&
5499                             !(declaration->modifiers & DM_NORETURN)) {
5500                                 warningf(&body->base.source_position,
5501                                          "function '%#T' is candidate for attribute 'noreturn'",
5502                                          type, declaration->symbol);
5503                         }
5504                 }
5505
5506                 assert(current_parent   == NULL);
5507                 assert(current_function == declaration);
5508                 current_function = old_current_function;
5509                 label_pop_to(label_stack_top);
5510         }
5511
5512         assert(scope == &declaration->scope);
5513         set_scope(last_scope);
5514         environment_pop_to(top);
5515 }
5516
5517 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5518                                   source_position_t *source_position,
5519                                   const symbol_t *symbol)
5520 {
5521         type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5522
5523         type->bitfield.base_type       = base_type;
5524         type->bitfield.size_expression = size;
5525
5526         il_size_t bit_size;
5527         type_t *skipped_type = skip_typeref(base_type);
5528         if (!is_type_integer(skipped_type)) {
5529                 errorf(HERE, "bitfield base type '%T' is not an integer type",
5530                         base_type);
5531                 bit_size = 0;
5532         } else {
5533                 bit_size = skipped_type->base.size * 8;
5534         }
5535
5536         if (is_constant_expression(size)) {
5537                 long v = fold_constant(size);
5538
5539                 if (v < 0) {
5540                         errorf(source_position, "negative width in bit-field '%Y'",
5541                                 symbol);
5542                 } else if (v == 0) {
5543                         errorf(source_position, "zero width for bit-field '%Y'",
5544                                 symbol);
5545                 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5546                         errorf(source_position, "width of '%Y' exceeds its type",
5547                                 symbol);
5548                 } else {
5549                         type->bitfield.bit_size = v;
5550                 }
5551         }
5552
5553         return type;
5554 }
5555
5556 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5557                                           symbol_t *symbol)
5558 {
5559         declaration_t *iter = compound_declaration->scope.declarations;
5560         for( ; iter != NULL; iter = iter->next) {
5561                 if (iter->namespc != NAMESPACE_NORMAL)
5562                         continue;
5563
5564                 if (iter->symbol == NULL) {
5565                         type_t *type = skip_typeref(iter->type);
5566                         if (is_type_compound(type)) {
5567                                 declaration_t *result
5568                                         = find_compound_entry(type->compound.declaration, symbol);
5569                                 if (result != NULL)
5570                                         return result;
5571                         }
5572                         continue;
5573                 }
5574
5575                 if (iter->symbol == symbol) {
5576                         return iter;
5577                 }
5578         }
5579
5580         return NULL;
5581 }
5582
5583 static void parse_compound_declarators(declaration_t *struct_declaration,
5584                 const declaration_specifiers_t *specifiers)
5585 {
5586         declaration_t *last_declaration = struct_declaration->scope.declarations;
5587         if (last_declaration != NULL) {
5588                 while (last_declaration->next != NULL) {
5589                         last_declaration = last_declaration->next;
5590                 }
5591         }
5592
5593         while (true) {
5594                 declaration_t *declaration;
5595
5596                 if (token.type == ':') {
5597                         source_position_t source_position = *HERE;
5598                         next_token();
5599
5600                         type_t *base_type = specifiers->type;
5601                         expression_t *size = parse_constant_expression();
5602
5603                         type_t *type = make_bitfield_type(base_type, size,
5604                                         &source_position, sym_anonymous);
5605
5606                         declaration                         = allocate_declaration_zero();
5607                         declaration->namespc                = NAMESPACE_NORMAL;
5608                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
5609                         declaration->storage_class          = STORAGE_CLASS_NONE;
5610                         declaration->source_position        = source_position;
5611                         declaration->modifiers              = specifiers->modifiers;
5612                         declaration->type                   = type;
5613                 } else {
5614                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5615
5616                         type_t *orig_type = declaration->type;
5617                         type_t *type      = skip_typeref(orig_type);
5618
5619                         if (token.type == ':') {
5620                                 source_position_t source_position = *HERE;
5621                                 next_token();
5622                                 expression_t *size = parse_constant_expression();
5623
5624                                 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5625                                                 &source_position, declaration->symbol);
5626                                 declaration->type = bitfield_type;
5627                         } else {
5628                                 /* TODO we ignore arrays for now... what is missing is a check
5629                                  * that they're at the end of the struct */
5630                                 if (is_type_incomplete(type) && !is_type_array(type)) {
5631                                         errorf(HERE,
5632                                                "compound member '%Y' has incomplete type '%T'",
5633                                                declaration->symbol, orig_type);
5634                                 } else if (is_type_function(type)) {
5635                                         errorf(HERE, "compound member '%Y' must not have function type '%T'",
5636                                                declaration->symbol, orig_type);
5637                                 }
5638                         }
5639                 }
5640
5641                 /* make sure we don't define a symbol multiple times */
5642                 symbol_t *symbol = declaration->symbol;
5643                 if (symbol != NULL) {
5644                         declaration_t *prev_decl
5645                                 = find_compound_entry(struct_declaration, symbol);
5646
5647                         if (prev_decl != NULL) {
5648                                 assert(prev_decl->symbol == symbol);
5649                                 errorf(&declaration->source_position,
5650                                        "multiple declarations of symbol '%Y' (declared %P)",
5651                                        symbol, &prev_decl->source_position);
5652                         }
5653                 }
5654
5655                 /* append declaration */
5656                 if (last_declaration != NULL) {
5657                         last_declaration->next = declaration;
5658                 } else {
5659                         struct_declaration->scope.declarations = declaration;
5660                 }
5661                 last_declaration = declaration;
5662
5663                 if (token.type != ',')
5664                         break;
5665                 next_token();
5666         }
5667         expect(';');
5668
5669 end_error:
5670         ;
5671 }
5672
5673 static void parse_compound_type_entries(declaration_t *compound_declaration)
5674 {
5675         eat('{');
5676         add_anchor_token('}');
5677
5678         while (token.type != '}' && token.type != T_EOF) {
5679                 declaration_specifiers_t specifiers;
5680                 memset(&specifiers, 0, sizeof(specifiers));
5681                 parse_declaration_specifiers(&specifiers);
5682
5683                 parse_compound_declarators(compound_declaration, &specifiers);
5684         }
5685         rem_anchor_token('}');
5686
5687         if (token.type == T_EOF) {
5688                 errorf(HERE, "EOF while parsing struct");
5689         }
5690         next_token();
5691 }
5692
5693 static type_t *parse_typename(void)
5694 {
5695         declaration_specifiers_t specifiers;
5696         memset(&specifiers, 0, sizeof(specifiers));
5697         parse_declaration_specifiers(&specifiers);
5698         if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5699                 /* TODO: improve error message, user does probably not know what a
5700                  * storage class is...
5701                  */
5702                 errorf(HERE, "typename may not have a storage class");
5703         }
5704
5705         type_t *result = parse_abstract_declarator(specifiers.type);
5706
5707         return result;
5708 }
5709
5710
5711
5712
5713 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5714 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5715                                                           expression_t *left);
5716
5717 typedef struct expression_parser_function_t expression_parser_function_t;
5718 struct expression_parser_function_t {
5719         unsigned                         precedence;
5720         parse_expression_function        parser;
5721         unsigned                         infix_precedence;
5722         parse_expression_infix_function  infix_parser;
5723 };
5724
5725 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5726
5727 /**
5728  * Prints an error message if an expression was expected but not read
5729  */
5730 static expression_t *expected_expression_error(void)
5731 {
5732         /* skip the error message if the error token was read */
5733         if (token.type != T_ERROR) {
5734                 errorf(HERE, "expected expression, got token '%K'", &token);
5735         }
5736         next_token();
5737
5738         return create_invalid_expression();
5739 }
5740
5741 /**
5742  * Parse a string constant.
5743  */
5744 static expression_t *parse_string_const(void)
5745 {
5746         wide_string_t wres;
5747         if (token.type == T_STRING_LITERAL) {
5748                 string_t res = token.v.string;
5749                 next_token();
5750                 while (token.type == T_STRING_LITERAL) {
5751                         res = concat_strings(&res, &token.v.string);
5752                         next_token();
5753                 }
5754                 if (token.type != T_WIDE_STRING_LITERAL) {
5755                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5756                         /* note: that we use type_char_ptr here, which is already the
5757                          * automatic converted type. revert_automatic_type_conversion
5758                          * will construct the array type */
5759                         cnst->base.type    = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5760                         cnst->string.value = res;
5761                         return cnst;
5762                 }
5763
5764                 wres = concat_string_wide_string(&res, &token.v.wide_string);
5765         } else {
5766                 wres = token.v.wide_string;
5767         }
5768         next_token();
5769
5770         for (;;) {
5771                 switch (token.type) {
5772                         case T_WIDE_STRING_LITERAL:
5773                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
5774                                 break;
5775
5776                         case T_STRING_LITERAL:
5777                                 wres = concat_wide_string_string(&wres, &token.v.string);
5778                                 break;
5779
5780                         default: {
5781                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5782                                 cnst->base.type         = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5783                                 cnst->wide_string.value = wres;
5784                                 return cnst;
5785                         }
5786                 }
5787                 next_token();
5788         }
5789 }
5790
5791 /**
5792  * Parse an integer constant.
5793  */
5794 static expression_t *parse_int_const(void)
5795 {
5796         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5797         cnst->base.source_position = *HERE;
5798         cnst->base.type            = token.datatype;
5799         cnst->conste.v.int_value   = token.v.intvalue;
5800
5801         next_token();
5802
5803         return cnst;
5804 }
5805
5806 /**
5807  * Parse a character constant.
5808  */
5809 static expression_t *parse_character_constant(void)
5810 {
5811         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5812
5813         cnst->base.source_position = *HERE;
5814         cnst->base.type            = token.datatype;
5815         cnst->conste.v.character   = token.v.string;
5816
5817         if (cnst->conste.v.character.size != 1) {
5818                 if (warning.multichar && (c_mode & _GNUC)) {
5819                         /* TODO */
5820                         warningf(HERE, "multi-character character constant");
5821                 } else {
5822                         errorf(HERE, "more than 1 characters in character constant");
5823                 }
5824         }
5825         next_token();
5826
5827         return cnst;
5828 }
5829
5830 /**
5831  * Parse a wide character constant.
5832  */
5833 static expression_t *parse_wide_character_constant(void)
5834 {
5835         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5836
5837         cnst->base.source_position    = *HERE;
5838         cnst->base.type               = token.datatype;
5839         cnst->conste.v.wide_character = token.v.wide_string;
5840
5841         if (cnst->conste.v.wide_character.size != 1) {
5842                 if (warning.multichar && (c_mode & _GNUC)) {
5843                         /* TODO */
5844                         warningf(HERE, "multi-character character constant");
5845                 } else {
5846                         errorf(HERE, "more than 1 characters in character constant");
5847                 }
5848         }
5849         next_token();
5850
5851         return cnst;
5852 }
5853
5854 /**
5855  * Parse a float constant.
5856  */
5857 static expression_t *parse_float_const(void)
5858 {
5859         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5860         cnst->base.type            = token.datatype;
5861         cnst->conste.v.float_value = token.v.floatvalue;
5862
5863         next_token();
5864
5865         return cnst;
5866 }
5867
5868 static declaration_t *create_implicit_function(symbol_t *symbol,
5869                 const source_position_t *source_position)
5870 {
5871         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
5872         ntype->function.return_type            = type_int;
5873         ntype->function.unspecified_parameters = true;
5874
5875         type_t *type = typehash_insert(ntype);
5876         if (type != ntype) {
5877                 free_type(ntype);
5878         }
5879
5880         declaration_t *const declaration    = allocate_declaration_zero();
5881         declaration->storage_class          = STORAGE_CLASS_EXTERN;
5882         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5883         declaration->type                   = type;
5884         declaration->symbol                 = symbol;
5885         declaration->source_position        = *source_position;
5886         declaration->implicit               = true;
5887
5888         bool strict_prototypes_old = warning.strict_prototypes;
5889         warning.strict_prototypes  = false;
5890         record_declaration(declaration, false);
5891         warning.strict_prototypes = strict_prototypes_old;
5892
5893         return declaration;
5894 }
5895
5896 /**
5897  * Creates a return_type (func)(argument_type) function type if not
5898  * already exists.
5899  */
5900 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5901                                     type_t *argument_type2)
5902 {
5903         function_parameter_t *parameter2
5904                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5905         memset(parameter2, 0, sizeof(parameter2[0]));
5906         parameter2->type = argument_type2;
5907
5908         function_parameter_t *parameter1
5909                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5910         memset(parameter1, 0, sizeof(parameter1[0]));
5911         parameter1->type = argument_type1;
5912         parameter1->next = parameter2;
5913
5914         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5915         type->function.return_type = return_type;
5916         type->function.parameters  = parameter1;
5917
5918         type_t *result = typehash_insert(type);
5919         if (result != type) {
5920                 free_type(type);
5921         }
5922
5923         return result;
5924 }
5925
5926 /**
5927  * Creates a return_type (func)(argument_type) function type if not
5928  * already exists.
5929  *
5930  * @param return_type    the return type
5931  * @param argument_type  the argument type
5932  */
5933 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5934 {
5935         function_parameter_t *parameter
5936                 = obstack_alloc(type_obst, sizeof(parameter[0]));
5937         memset(parameter, 0, sizeof(parameter[0]));
5938         parameter->type = argument_type;
5939
5940         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5941         type->function.return_type = return_type;
5942         type->function.parameters  = parameter;
5943
5944         type_t *result = typehash_insert(type);
5945         if (result != type) {
5946                 free_type(type);
5947         }
5948
5949         return result;
5950 }
5951
5952 static type_t *make_function_0_type(type_t *return_type)
5953 {
5954         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5955         type->function.return_type = return_type;
5956         type->function.parameters  = NULL;
5957
5958         type_t *result = typehash_insert(type);
5959         if (result != type) {
5960                 free_type(type);
5961         }
5962
5963         return result;
5964 }
5965
5966 /**
5967  * Creates a function type for some function like builtins.
5968  *
5969  * @param symbol   the symbol describing the builtin
5970  */
5971 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5972 {
5973         switch(symbol->ID) {
5974         case T___builtin_alloca:
5975                 return make_function_1_type(type_void_ptr, type_size_t);
5976         case T___builtin_huge_val:
5977                 return make_function_0_type(type_double);
5978         case T___builtin_nan:
5979                 return make_function_1_type(type_double, type_char_ptr);
5980         case T___builtin_nanf:
5981                 return make_function_1_type(type_float, type_char_ptr);
5982         case T___builtin_nand:
5983                 return make_function_1_type(type_long_double, type_char_ptr);
5984         case T___builtin_va_end:
5985                 return make_function_1_type(type_void, type_valist);
5986         case T___builtin_expect:
5987                 return make_function_2_type(type_long, type_long, type_long);
5988         default:
5989                 internal_errorf(HERE, "not implemented builtin symbol found");
5990         }
5991 }
5992
5993 /**
5994  * Performs automatic type cast as described in Â§ 6.3.2.1.
5995  *
5996  * @param orig_type  the original type
5997  */
5998 static type_t *automatic_type_conversion(type_t *orig_type)
5999 {
6000         type_t *type = skip_typeref(orig_type);
6001         if (is_type_array(type)) {
6002                 array_type_t *array_type   = &type->array;
6003                 type_t       *element_type = array_type->element_type;
6004                 unsigned      qualifiers   = array_type->base.qualifiers;
6005
6006                 return make_pointer_type(element_type, qualifiers);
6007         }
6008
6009         if (is_type_function(type)) {
6010                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6011         }
6012
6013         return orig_type;
6014 }
6015
6016 /**
6017  * reverts the automatic casts of array to pointer types and function
6018  * to function-pointer types as defined Â§ 6.3.2.1
6019  */
6020 type_t *revert_automatic_type_conversion(const expression_t *expression)
6021 {
6022         switch (expression->kind) {
6023                 case EXPR_REFERENCE: return expression->reference.declaration->type;
6024
6025                 case EXPR_SELECT:
6026                         return get_qualified_type(expression->select.compound_entry->type,
6027                                                   expression->base.type->base.qualifiers);
6028
6029                 case EXPR_UNARY_DEREFERENCE: {
6030                         const expression_t *const value = expression->unary.value;
6031                         type_t             *const type  = skip_typeref(value->base.type);
6032                         assert(is_type_pointer(type));
6033                         return type->pointer.points_to;
6034                 }
6035
6036                 case EXPR_BUILTIN_SYMBOL:
6037                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6038
6039                 case EXPR_ARRAY_ACCESS: {
6040                         const expression_t *array_ref = expression->array_access.array_ref;
6041                         type_t             *type_left = skip_typeref(array_ref->base.type);
6042                         if (!is_type_valid(type_left))
6043                                 return type_left;
6044                         assert(is_type_pointer(type_left));
6045                         return type_left->pointer.points_to;
6046                 }
6047
6048                 case EXPR_STRING_LITERAL: {
6049                         size_t size = expression->string.value.size;
6050                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6051                 }
6052
6053                 case EXPR_WIDE_STRING_LITERAL: {
6054                         size_t size = expression->wide_string.value.size;
6055                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6056                 }
6057
6058                 case EXPR_COMPOUND_LITERAL:
6059                         return expression->compound_literal.type;
6060
6061                 default: break;
6062         }
6063
6064         return expression->base.type;
6065 }
6066
6067 static expression_t *parse_reference(void)
6068 {
6069         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6070
6071         reference_expression_t *ref = &expression->reference;
6072         symbol_t *const symbol = token.v.symbol;
6073
6074         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6075
6076         if (declaration == NULL) {
6077                 if (!strict_mode && look_ahead(1)->type == '(') {
6078                         /* an implicitly declared function */
6079                         if (warning.implicit_function_declaration) {
6080                                 warningf(HERE, "implicit declaration of function '%Y'",
6081                                         symbol);
6082                         }
6083
6084                         declaration = create_implicit_function(symbol, HERE);
6085                 } else {
6086                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
6087                         declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6088                 }
6089         }
6090
6091         type_t *type = declaration->type;
6092
6093         /* we always do the auto-type conversions; the & and sizeof parser contains
6094          * code to revert this! */
6095         type = automatic_type_conversion(type);
6096
6097         ref->declaration = declaration;
6098         ref->base.type   = type;
6099
6100         /* this declaration is used */
6101         declaration->used = true;
6102
6103         /* check for deprecated functions */
6104         if (warning.deprecated_declarations &&
6105             declaration->modifiers & DM_DEPRECATED) {
6106                 char const *const prefix = is_type_function(declaration->type) ?
6107                         "function" : "variable";
6108
6109                 if (declaration->deprecated_string != NULL) {
6110                         warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6111                                 prefix, declaration->symbol, &declaration->source_position,
6112                                 declaration->deprecated_string);
6113                 } else {
6114                         warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6115                                 declaration->symbol, &declaration->source_position);
6116                 }
6117         }
6118         if (warning.init_self && declaration == current_init_decl) {
6119                 current_init_decl = NULL;
6120                 warningf(HERE, "variable '%#T' is initialized by itself",
6121                         declaration->type, declaration->symbol);
6122         }
6123
6124         next_token();
6125         return expression;
6126 }
6127
6128 static bool semantic_cast(expression_t *cast)
6129 {
6130         expression_t            *expression      = cast->unary.value;
6131         type_t                  *orig_dest_type  = cast->base.type;
6132         type_t                  *orig_type_right = expression->base.type;
6133         type_t            const *dst_type        = skip_typeref(orig_dest_type);
6134         type_t            const *src_type        = skip_typeref(orig_type_right);
6135         source_position_t const *pos             = &cast->base.source_position;
6136
6137         /* Â§6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6138         if (dst_type == type_void)
6139                 return true;
6140
6141         /* only integer and pointer can be casted to pointer */
6142         if (is_type_pointer(dst_type)  &&
6143             !is_type_pointer(src_type) &&
6144             !is_type_integer(src_type) &&
6145             is_type_valid(src_type)) {
6146                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6147                 return false;
6148         }
6149
6150         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6151                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6152                 return false;
6153         }
6154
6155         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6156                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6157                 return false;
6158         }
6159
6160         if (warning.cast_qual &&
6161             is_type_pointer(src_type) &&
6162             is_type_pointer(dst_type)) {
6163                 type_t *src = skip_typeref(src_type->pointer.points_to);
6164                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6165                 unsigned missing_qualifiers =
6166                         src->base.qualifiers & ~dst->base.qualifiers;
6167                 if (missing_qualifiers != 0) {
6168                         warningf(pos,
6169                                  "cast discards qualifiers '%Q' in pointer target type of '%T'",
6170                                  missing_qualifiers, orig_type_right);
6171                 }
6172         }
6173         return true;
6174 }
6175
6176 static expression_t *parse_compound_literal(type_t *type)
6177 {
6178         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6179
6180         parse_initializer_env_t env;
6181         env.type             = type;
6182         env.declaration      = NULL;
6183         env.must_be_constant = false;
6184         initializer_t *initializer = parse_initializer(&env);
6185         type = env.type;
6186
6187         expression->compound_literal.initializer = initializer;
6188         expression->compound_literal.type        = type;
6189         expression->base.type                    = automatic_type_conversion(type);
6190
6191         return expression;
6192 }
6193
6194 /**
6195  * Parse a cast expression.
6196  */
6197 static expression_t *parse_cast(void)
6198 {
6199         add_anchor_token(')');
6200
6201         source_position_t source_position = token.source_position;
6202
6203         type_t *type  = parse_typename();
6204
6205         rem_anchor_token(')');
6206         expect(')');
6207
6208         if (token.type == '{') {
6209                 return parse_compound_literal(type);
6210         }
6211
6212         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6213         cast->base.source_position = source_position;
6214
6215         expression_t *value = parse_sub_expression(20);
6216         cast->base.type   = type;
6217         cast->unary.value = value;
6218
6219         if (! semantic_cast(cast)) {
6220                 /* TODO: record the error in the AST. else it is impossible to detect it */
6221         }
6222
6223         return cast;
6224 end_error:
6225         return create_invalid_expression();
6226 }
6227
6228 /**
6229  * Parse a statement expression.
6230  */
6231 static expression_t *parse_statement_expression(void)
6232 {
6233         add_anchor_token(')');
6234
6235         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6236
6237         statement_t *statement           = parse_compound_statement(true);
6238         expression->statement.statement  = statement;
6239         expression->base.source_position = statement->base.source_position;
6240
6241         /* find last statement and use its type */
6242         type_t *type = type_void;
6243         const statement_t *stmt = statement->compound.statements;
6244         if (stmt != NULL) {
6245                 while (stmt->base.next != NULL)
6246                         stmt = stmt->base.next;
6247
6248                 if (stmt->kind == STATEMENT_EXPRESSION) {
6249                         type = stmt->expression.expression->base.type;
6250                 }
6251         } else {
6252                 warningf(&expression->base.source_position, "empty statement expression ({})");
6253         }
6254         expression->base.type = type;
6255
6256         rem_anchor_token(')');
6257         expect(')');
6258
6259 end_error:
6260         return expression;
6261 }
6262
6263 /**
6264  * Parse a parenthesized expression.
6265  */
6266 static expression_t *parse_parenthesized_expression(void)
6267 {
6268         eat('(');
6269
6270         switch(token.type) {
6271         case '{':
6272                 /* gcc extension: a statement expression */
6273                 return parse_statement_expression();
6274
6275         TYPE_QUALIFIERS
6276         TYPE_SPECIFIERS
6277                 return parse_cast();
6278         case T_IDENTIFIER:
6279                 if (is_typedef_symbol(token.v.symbol)) {
6280                         return parse_cast();
6281                 }
6282         }
6283
6284         add_anchor_token(')');
6285         expression_t *result = parse_expression();
6286         rem_anchor_token(')');
6287         expect(')');
6288
6289 end_error:
6290         return result;
6291 }
6292
6293 static expression_t *parse_function_keyword(void)
6294 {
6295         next_token();
6296         /* TODO */
6297
6298         if (current_function == NULL) {
6299                 errorf(HERE, "'__func__' used outside of a function");
6300         }
6301
6302         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6303         expression->base.type     = type_char_ptr;
6304         expression->funcname.kind = FUNCNAME_FUNCTION;
6305
6306         return expression;
6307 }
6308
6309 static expression_t *parse_pretty_function_keyword(void)
6310 {
6311         eat(T___PRETTY_FUNCTION__);
6312
6313         if (current_function == NULL) {
6314                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6315         }
6316
6317         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6318         expression->base.type     = type_char_ptr;
6319         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6320
6321         return expression;
6322 }
6323
6324 static expression_t *parse_funcsig_keyword(void)
6325 {
6326         eat(T___FUNCSIG__);
6327
6328         if (current_function == NULL) {
6329                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6330         }
6331
6332         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6333         expression->base.type     = type_char_ptr;
6334         expression->funcname.kind = FUNCNAME_FUNCSIG;
6335
6336         return expression;
6337 }
6338
6339 static expression_t *parse_funcdname_keyword(void)
6340 {
6341         eat(T___FUNCDNAME__);
6342
6343         if (current_function == NULL) {
6344                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6345         }
6346
6347         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6348         expression->base.type     = type_char_ptr;
6349         expression->funcname.kind = FUNCNAME_FUNCDNAME;
6350
6351         return expression;
6352 }
6353
6354 static designator_t *parse_designator(void)
6355 {
6356         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
6357         result->source_position = *HERE;
6358
6359         if (token.type != T_IDENTIFIER) {
6360                 parse_error_expected("while parsing member designator",
6361                                      T_IDENTIFIER, NULL);
6362                 return NULL;
6363         }
6364         result->symbol = token.v.symbol;
6365         next_token();
6366
6367         designator_t *last_designator = result;
6368         while(true) {
6369                 if (token.type == '.') {
6370                         next_token();
6371                         if (token.type != T_IDENTIFIER) {
6372                                 parse_error_expected("while parsing member designator",
6373                                                      T_IDENTIFIER, NULL);
6374                                 return NULL;
6375                         }
6376                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6377                         designator->source_position = *HERE;
6378                         designator->symbol          = token.v.symbol;
6379                         next_token();
6380
6381                         last_designator->next = designator;
6382                         last_designator       = designator;
6383                         continue;
6384                 }
6385                 if (token.type == '[') {
6386                         next_token();
6387                         add_anchor_token(']');
6388                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6389                         designator->source_position = *HERE;
6390                         designator->array_index     = parse_expression();
6391                         rem_anchor_token(']');
6392                         expect(']');
6393                         if (designator->array_index == NULL) {
6394                                 return NULL;
6395                         }
6396
6397                         last_designator->next = designator;
6398                         last_designator       = designator;
6399                         continue;
6400                 }
6401                 break;
6402         }
6403
6404         return result;
6405 end_error:
6406         return NULL;
6407 }
6408
6409 /**
6410  * Parse the __builtin_offsetof() expression.
6411  */
6412 static expression_t *parse_offsetof(void)
6413 {
6414         eat(T___builtin_offsetof);
6415
6416         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6417         expression->base.type    = type_size_t;
6418
6419         expect('(');
6420         add_anchor_token(',');
6421         type_t *type = parse_typename();
6422         rem_anchor_token(',');
6423         expect(',');
6424         add_anchor_token(')');
6425         designator_t *designator = parse_designator();
6426         rem_anchor_token(')');
6427         expect(')');
6428
6429         expression->offsetofe.type       = type;
6430         expression->offsetofe.designator = designator;
6431
6432         type_path_t path;
6433         memset(&path, 0, sizeof(path));
6434         path.top_type = type;
6435         path.path     = NEW_ARR_F(type_path_entry_t, 0);
6436
6437         descend_into_subtype(&path);
6438
6439         if (!walk_designator(&path, designator, true)) {
6440                 return create_invalid_expression();
6441         }
6442
6443         DEL_ARR_F(path.path);
6444
6445         return expression;
6446 end_error:
6447         return create_invalid_expression();
6448 }
6449
6450 /**
6451  * Parses a _builtin_va_start() expression.
6452  */
6453 static expression_t *parse_va_start(void)
6454 {
6455         eat(T___builtin_va_start);
6456
6457         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6458
6459         expect('(');
6460         add_anchor_token(',');
6461         expression->va_starte.ap = parse_assignment_expression();
6462         rem_anchor_token(',');
6463         expect(',');
6464         expression_t *const expr = parse_assignment_expression();
6465         if (expr->kind == EXPR_REFERENCE) {
6466                 declaration_t *const decl = expr->reference.declaration;
6467                 if (decl->parent_scope != &current_function->scope || decl->next != NULL) {
6468                         errorf(&expr->base.source_position,
6469                                "second argument of 'va_start' must be last parameter of the current function");
6470                 }
6471                 expression->va_starte.parameter = decl;
6472                 expect(')');
6473                 return expression;
6474         }
6475         expect(')');
6476 end_error:
6477         return create_invalid_expression();
6478 }
6479
6480 /**
6481  * Parses a _builtin_va_arg() expression.
6482  */
6483 static expression_t *parse_va_arg(void)
6484 {
6485         eat(T___builtin_va_arg);
6486
6487         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6488
6489         expect('(');
6490         expression->va_arge.ap = parse_assignment_expression();
6491         expect(',');
6492         expression->base.type = parse_typename();
6493         expect(')');
6494
6495         return expression;
6496 end_error:
6497         return create_invalid_expression();
6498 }
6499
6500 static expression_t *parse_builtin_symbol(void)
6501 {
6502         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6503
6504         symbol_t *symbol = token.v.symbol;
6505
6506         expression->builtin_symbol.symbol = symbol;
6507         next_token();
6508
6509         type_t *type = get_builtin_symbol_type(symbol);
6510         type = automatic_type_conversion(type);
6511
6512         expression->base.type = type;
6513         return expression;
6514 }
6515
6516 /**
6517  * Parses a __builtin_constant() expression.
6518  */
6519 static expression_t *parse_builtin_constant(void)
6520 {
6521         eat(T___builtin_constant_p);
6522
6523         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6524
6525         expect('(');
6526         add_anchor_token(')');
6527         expression->builtin_constant.value = parse_assignment_expression();
6528         rem_anchor_token(')');
6529         expect(')');
6530         expression->base.type = type_int;
6531
6532         return expression;
6533 end_error:
6534         return create_invalid_expression();
6535 }
6536
6537 /**
6538  * Parses a __builtin_prefetch() expression.
6539  */
6540 static expression_t *parse_builtin_prefetch(void)
6541 {
6542         eat(T___builtin_prefetch);
6543
6544         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6545
6546         expect('(');
6547         add_anchor_token(')');
6548         expression->builtin_prefetch.adr = parse_assignment_expression();
6549         if (token.type == ',') {
6550                 next_token();
6551                 expression->builtin_prefetch.rw = parse_assignment_expression();
6552         }
6553         if (token.type == ',') {
6554                 next_token();
6555                 expression->builtin_prefetch.locality = parse_assignment_expression();
6556         }
6557         rem_anchor_token(')');
6558         expect(')');
6559         expression->base.type = type_void;
6560
6561         return expression;
6562 end_error:
6563         return create_invalid_expression();
6564 }
6565
6566 /**
6567  * Parses a __builtin_is_*() compare expression.
6568  */
6569 static expression_t *parse_compare_builtin(void)
6570 {
6571         expression_t *expression;
6572
6573         switch(token.type) {
6574         case T___builtin_isgreater:
6575                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6576                 break;
6577         case T___builtin_isgreaterequal:
6578                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6579                 break;
6580         case T___builtin_isless:
6581                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6582                 break;
6583         case T___builtin_islessequal:
6584                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6585                 break;
6586         case T___builtin_islessgreater:
6587                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6588                 break;
6589         case T___builtin_isunordered:
6590                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6591                 break;
6592         default:
6593                 internal_errorf(HERE, "invalid compare builtin found");
6594                 break;
6595         }
6596         expression->base.source_position = *HERE;
6597         next_token();
6598
6599         expect('(');
6600         expression->binary.left = parse_assignment_expression();
6601         expect(',');
6602         expression->binary.right = parse_assignment_expression();
6603         expect(')');
6604
6605         type_t *const orig_type_left  = expression->binary.left->base.type;
6606         type_t *const orig_type_right = expression->binary.right->base.type;
6607
6608         type_t *const type_left  = skip_typeref(orig_type_left);
6609         type_t *const type_right = skip_typeref(orig_type_right);
6610         if (!is_type_float(type_left) && !is_type_float(type_right)) {
6611                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6612                         type_error_incompatible("invalid operands in comparison",
6613                                 &expression->base.source_position, orig_type_left, orig_type_right);
6614                 }
6615         } else {
6616                 semantic_comparison(&expression->binary);
6617         }
6618
6619         return expression;
6620 end_error:
6621         return create_invalid_expression();
6622 }
6623
6624 #if 0
6625 /**
6626  * Parses a __builtin_expect() expression.
6627  */
6628 static expression_t *parse_builtin_expect(void)
6629 {
6630         eat(T___builtin_expect);
6631
6632         expression_t *expression
6633                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6634
6635         expect('(');
6636         expression->binary.left = parse_assignment_expression();
6637         expect(',');
6638         expression->binary.right = parse_constant_expression();
6639         expect(')');
6640
6641         expression->base.type = expression->binary.left->base.type;
6642
6643         return expression;
6644 end_error:
6645         return create_invalid_expression();
6646 }
6647 #endif
6648
6649 /**
6650  * Parses a MS assume() expression.
6651  */
6652 static expression_t *parse_assume(void)
6653 {
6654         eat(T__assume);
6655
6656         expression_t *expression
6657                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6658
6659         expect('(');
6660         add_anchor_token(')');
6661         expression->unary.value = parse_assignment_expression();
6662         rem_anchor_token(')');
6663         expect(')');
6664
6665         expression->base.type = type_void;
6666         return expression;
6667 end_error:
6668         return create_invalid_expression();
6669 }
6670
6671 /**
6672  * Return the declaration for a given label symbol or create a new one.
6673  *
6674  * @param symbol  the symbol of the label
6675  */
6676 static declaration_t *get_label(symbol_t *symbol)
6677 {
6678         declaration_t *candidate;
6679         assert(current_function != NULL);
6680
6681         candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6682         /* if we found a local label, we already created the declaration */
6683         if (candidate != NULL) {
6684                 assert(candidate->parent_scope == scope);
6685                 return candidate;
6686         }
6687
6688         candidate = get_declaration(symbol, NAMESPACE_LABEL);
6689         /* if we found a label in the same function, then we already created the
6690          * declaration */
6691         if (candidate != NULL
6692                         && candidate->parent_scope == &current_function->scope) {
6693                 return candidate;
6694         }
6695
6696         /* otherwise we need to create a new one */
6697         declaration_t *const declaration = allocate_declaration_zero();
6698         declaration->namespc       = NAMESPACE_LABEL;
6699         declaration->symbol        = symbol;
6700
6701         label_push(declaration);
6702
6703         return declaration;
6704 }
6705
6706 /**
6707  * Parses a GNU && label address expression.
6708  */
6709 static expression_t *parse_label_address(void)
6710 {
6711         source_position_t source_position = token.source_position;
6712         eat(T_ANDAND);
6713         if (token.type != T_IDENTIFIER) {
6714                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6715                 goto end_error;
6716         }
6717         symbol_t *symbol = token.v.symbol;
6718         next_token();
6719
6720         declaration_t *label = get_label(symbol);
6721
6722         label->used          = true;
6723         label->address_taken = true;
6724
6725         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6726         expression->base.source_position = source_position;
6727
6728         /* label address is threaten as a void pointer */
6729         expression->base.type                 = type_void_ptr;
6730         expression->label_address.declaration = label;
6731         return expression;
6732 end_error:
6733         return create_invalid_expression();
6734 }
6735
6736 /**
6737  * Parse a microsoft __noop expression.
6738  */
6739 static expression_t *parse_noop_expression(void)
6740 {
6741         source_position_t source_position = *HERE;
6742         eat(T___noop);
6743
6744         if (token.type == '(') {
6745                 /* parse arguments */
6746                 eat('(');
6747                 add_anchor_token(')');
6748                 add_anchor_token(',');
6749
6750                 if (token.type != ')') {
6751                         while(true) {
6752                                 (void)parse_assignment_expression();
6753                                 if (token.type != ',')
6754                                         break;
6755                                 next_token();
6756                         }
6757                 }
6758         }
6759         rem_anchor_token(',');
6760         rem_anchor_token(')');
6761         expect(')');
6762
6763         /* the result is a (int)0 */
6764         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
6765         cnst->base.source_position = source_position;
6766         cnst->base.type            = type_int;
6767         cnst->conste.v.int_value   = 0;
6768         cnst->conste.is_ms_noop    = true;
6769
6770         return cnst;
6771
6772 end_error:
6773         return create_invalid_expression();
6774 }
6775
6776 /**
6777  * Parses a primary expression.
6778  */
6779 static expression_t *parse_primary_expression(void)
6780 {
6781         switch (token.type) {
6782                 case T_INTEGER:                  return parse_int_const();
6783                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
6784                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
6785                 case T_FLOATINGPOINT:            return parse_float_const();
6786                 case T_STRING_LITERAL:
6787                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
6788                 case T_IDENTIFIER:               return parse_reference();
6789                 case T___FUNCTION__:
6790                 case T___func__:                 return parse_function_keyword();
6791                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
6792                 case T___FUNCSIG__:              return parse_funcsig_keyword();
6793                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
6794                 case T___builtin_offsetof:       return parse_offsetof();
6795                 case T___builtin_va_start:       return parse_va_start();
6796                 case T___builtin_va_arg:         return parse_va_arg();
6797                 case T___builtin_expect:
6798                 case T___builtin_alloca:
6799                 case T___builtin_nan:
6800                 case T___builtin_nand:
6801                 case T___builtin_nanf:
6802                 case T___builtin_huge_val:
6803                 case T___builtin_va_end:         return parse_builtin_symbol();
6804                 case T___builtin_isgreater:
6805                 case T___builtin_isgreaterequal:
6806                 case T___builtin_isless:
6807                 case T___builtin_islessequal:
6808                 case T___builtin_islessgreater:
6809                 case T___builtin_isunordered:    return parse_compare_builtin();
6810                 case T___builtin_constant_p:     return parse_builtin_constant();
6811                 case T___builtin_prefetch:       return parse_builtin_prefetch();
6812                 case T__assume:                  return parse_assume();
6813                 case T_ANDAND:
6814                         if (c_mode & _GNUC)
6815                                 return parse_label_address();
6816                         break;
6817
6818                 case '(':                        return parse_parenthesized_expression();
6819                 case T___noop:                   return parse_noop_expression();
6820         }
6821
6822         errorf(HERE, "unexpected token %K, expected an expression", &token);
6823         return create_invalid_expression();
6824 }
6825
6826 /**
6827  * Check if the expression has the character type and issue a warning then.
6828  */
6829 static void check_for_char_index_type(const expression_t *expression)
6830 {
6831         type_t       *const type      = expression->base.type;
6832         const type_t *const base_type = skip_typeref(type);
6833
6834         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6835                         warning.char_subscripts) {
6836                 warningf(&expression->base.source_position,
6837                          "array subscript has type '%T'", type);
6838         }
6839 }
6840
6841 static expression_t *parse_array_expression(unsigned precedence,
6842                                             expression_t *left)
6843 {
6844         (void) precedence;
6845
6846         eat('[');
6847         add_anchor_token(']');
6848
6849         expression_t *inside = parse_expression();
6850
6851         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6852
6853         array_access_expression_t *array_access = &expression->array_access;
6854
6855         type_t *const orig_type_left   = left->base.type;
6856         type_t *const orig_type_inside = inside->base.type;
6857
6858         type_t *const type_left   = skip_typeref(orig_type_left);
6859         type_t *const type_inside = skip_typeref(orig_type_inside);
6860
6861         type_t *return_type;
6862         if (is_type_pointer(type_left)) {
6863                 return_type             = type_left->pointer.points_to;
6864                 array_access->array_ref = left;
6865                 array_access->index     = inside;
6866                 check_for_char_index_type(inside);
6867         } else if (is_type_pointer(type_inside)) {
6868                 return_type             = type_inside->pointer.points_to;
6869                 array_access->array_ref = inside;
6870                 array_access->index     = left;
6871                 array_access->flipped   = true;
6872                 check_for_char_index_type(left);
6873         } else {
6874                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6875                         errorf(HERE,
6876                                 "array access on object with non-pointer types '%T', '%T'",
6877                                 orig_type_left, orig_type_inside);
6878                 }
6879                 return_type             = type_error_type;
6880                 array_access->array_ref = left;
6881                 array_access->index     = inside;
6882         }
6883
6884         expression->base.type = automatic_type_conversion(return_type);
6885
6886         rem_anchor_token(']');
6887         if (token.type == ']') {
6888                 next_token();
6889         } else {
6890                 parse_error_expected("Problem while parsing array access", ']', NULL);
6891         }
6892         return expression;
6893 }
6894
6895 static expression_t *parse_typeprop(expression_kind_t const kind,
6896                                     source_position_t const pos,
6897                                     unsigned const precedence)
6898 {
6899         expression_t  *tp_expression = allocate_expression_zero(kind);
6900         tp_expression->base.type            = type_size_t;
6901         tp_expression->base.source_position = pos;
6902
6903         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6904
6905         /* we only refer to a type property, not the value, so do not warn
6906          * when using current_init_decl */
6907         declaration_t *old = current_init_decl;
6908         current_init_decl  = NULL;
6909         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6910                 next_token();
6911                 add_anchor_token(')');
6912                 type_t* const orig_type = parse_typename();
6913                 tp_expression->typeprop.type = orig_type;
6914
6915                 type_t const* const type = skip_typeref(orig_type);
6916                 char const* const wrong_type =
6917                         is_type_incomplete(type)    ? "incomplete"          :
6918                         type->kind == TYPE_FUNCTION ? "function designator" :
6919                         type->kind == TYPE_BITFIELD ? "bitfield"            :
6920                         NULL;
6921                 if (wrong_type != NULL) {
6922                         errorf(&pos, "operand of %s expression must not be %s type '%T'",
6923                                what, wrong_type, type);
6924                 }
6925
6926                 rem_anchor_token(')');
6927                 expect(')');
6928         } else {
6929                 expression_t *expression = parse_sub_expression(precedence);
6930
6931                 type_t* const orig_type = revert_automatic_type_conversion(expression);
6932                 expression->base.type = orig_type;
6933
6934                 type_t const* const type = skip_typeref(orig_type);
6935                 char const* const wrong_type =
6936                         is_type_incomplete(type)    ? "incomplete"          :
6937                         type->kind == TYPE_FUNCTION ? "function designator" :
6938                         type->kind == TYPE_BITFIELD ? "bitfield"            :
6939                         NULL;
6940                 if (wrong_type != NULL) {
6941                         errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6942                 }
6943
6944                 tp_expression->typeprop.type          = expression->base.type;
6945                 tp_expression->typeprop.tp_expression = expression;
6946         }
6947
6948 end_error:
6949         current_init_decl  = old;
6950         return tp_expression;
6951 }
6952
6953 static expression_t *parse_sizeof(unsigned precedence)
6954 {
6955         source_position_t pos = *HERE;
6956         eat(T_sizeof);
6957         return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6958 }
6959
6960 static expression_t *parse_alignof(unsigned precedence)
6961 {
6962         source_position_t pos = *HERE;
6963         eat(T___alignof__);
6964         return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6965 }
6966
6967 static expression_t *parse_select_expression(unsigned precedence,
6968                                              expression_t *compound)
6969 {
6970         (void) precedence;
6971         assert(token.type == '.' || token.type == T_MINUSGREATER);
6972
6973         bool is_pointer = (token.type == T_MINUSGREATER);
6974         next_token();
6975
6976         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
6977         select->select.compound = compound;
6978
6979         if (token.type != T_IDENTIFIER) {
6980                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6981                 return select;
6982         }
6983         symbol_t *symbol = token.v.symbol;
6984         next_token();
6985
6986         type_t *const orig_type = compound->base.type;
6987         type_t *const type      = skip_typeref(orig_type);
6988
6989         type_t *type_left;
6990         bool    saw_error = false;
6991         if (is_type_pointer(type)) {
6992                 if (!is_pointer) {
6993                         errorf(HERE,
6994                                "request for member '%Y' in something not a struct or union, but '%T'",
6995                                symbol, orig_type);
6996                         saw_error = true;
6997                 }
6998                 type_left = skip_typeref(type->pointer.points_to);
6999         } else {
7000                 if (is_pointer && is_type_valid(type)) {
7001                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7002                         saw_error = true;
7003                 }
7004                 type_left = type;
7005         }
7006
7007         declaration_t *entry;
7008         if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7009             type_left->kind == TYPE_COMPOUND_UNION) {
7010                 declaration_t *const declaration = type_left->compound.declaration;
7011
7012                 if (!declaration->init.complete) {
7013                         errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7014                                symbol, type_left);
7015                         goto create_error_entry;
7016                 }
7017
7018                 entry = find_compound_entry(declaration, symbol);
7019                 if (entry == NULL) {
7020                         errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7021                         goto create_error_entry;
7022                 }
7023         } else {
7024                 if (is_type_valid(type_left) && !saw_error) {
7025                         errorf(HERE,
7026                                "request for member '%Y' in something not a struct or union, but '%T'",
7027                                symbol, type_left);
7028                 }
7029 create_error_entry:
7030                 entry         = allocate_declaration_zero();
7031                 entry->symbol = symbol;
7032         }
7033
7034         select->select.compound_entry = entry;
7035
7036         type_t *const res_type =
7037                 get_qualified_type(entry->type, type_left->base.qualifiers);
7038
7039         /* we always do the auto-type conversions; the & and sizeof parser contains
7040          * code to revert this! */
7041         select->base.type = automatic_type_conversion(res_type);
7042
7043         type_t *skipped = skip_typeref(res_type);
7044         if (skipped->kind == TYPE_BITFIELD) {
7045                 select->base.type = skipped->bitfield.base_type;
7046         }
7047
7048         return select;
7049 }
7050
7051 static void check_call_argument(const function_parameter_t *parameter,
7052                                 call_argument_t *argument, unsigned pos)
7053 {
7054         type_t         *expected_type      = parameter->type;
7055         type_t         *expected_type_skip = skip_typeref(expected_type);
7056         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7057         expression_t   *arg_expr           = argument->expression;
7058         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7059
7060         /* handle transparent union gnu extension */
7061         if (is_type_union(expected_type_skip)
7062                         && (expected_type_skip->base.modifiers
7063                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7064                 declaration_t  *union_decl = expected_type_skip->compound.declaration;
7065
7066                 declaration_t *declaration = union_decl->scope.declarations;
7067                 type_t        *best_type   = NULL;
7068                 for ( ; declaration != NULL; declaration = declaration->next) {
7069                         type_t *decl_type = declaration->type;
7070                         error = semantic_assign(decl_type, arg_expr);
7071                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7072                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7073                                 continue;
7074
7075                         if (error == ASSIGN_SUCCESS) {
7076                                 best_type = decl_type;
7077                         } else if (best_type == NULL) {
7078                                 best_type = decl_type;
7079                         }
7080                 }
7081
7082                 if (best_type != NULL) {
7083                         expected_type = best_type;
7084                 }
7085         }
7086
7087         error                = semantic_assign(expected_type, arg_expr);
7088         argument->expression = create_implicit_cast(argument->expression,
7089                                                     expected_type);
7090
7091         if (error != ASSIGN_SUCCESS) {
7092                 /* report exact scope in error messages (like "in argument 3") */
7093                 char buf[64];
7094                 snprintf(buf, sizeof(buf), "call argument %u", pos);
7095                 report_assign_error(error, expected_type, arg_expr,     buf,
7096                                                         &arg_expr->base.source_position);
7097         } else if (warning.traditional || warning.conversion) {
7098                 type_t *const promoted_type = get_default_promoted_type(arg_type);
7099                 if (!types_compatible(expected_type_skip, promoted_type) &&
7100                     !types_compatible(expected_type_skip, type_void_ptr) &&
7101                     !types_compatible(type_void_ptr,      promoted_type)) {
7102                         /* Deliberately show the skipped types in this warning */
7103                         warningf(&arg_expr->base.source_position,
7104                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
7105                                 pos, expected_type_skip, promoted_type);
7106                 }
7107         }
7108 }
7109
7110 /**
7111  * Parse a call expression, ie. expression '( ... )'.
7112  *
7113  * @param expression  the function address
7114  */
7115 static expression_t *parse_call_expression(unsigned precedence,
7116                                            expression_t *expression)
7117 {
7118         (void) precedence;
7119         expression_t *result = allocate_expression_zero(EXPR_CALL);
7120         result->base.source_position = expression->base.source_position;
7121
7122         call_expression_t *call = &result->call;
7123         call->function          = expression;
7124
7125         type_t *const orig_type = expression->base.type;
7126         type_t *const type      = skip_typeref(orig_type);
7127
7128         function_type_t *function_type = NULL;
7129         if (is_type_pointer(type)) {
7130                 type_t *const to_type = skip_typeref(type->pointer.points_to);
7131
7132                 if (is_type_function(to_type)) {
7133                         function_type   = &to_type->function;
7134                         call->base.type = function_type->return_type;
7135                 }
7136         }
7137
7138         if (function_type == NULL && is_type_valid(type)) {
7139                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7140         }
7141
7142         /* parse arguments */
7143         eat('(');
7144         add_anchor_token(')');
7145         add_anchor_token(',');
7146
7147         if (token.type != ')') {
7148                 call_argument_t *last_argument = NULL;
7149
7150                 while (true) {
7151                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7152
7153                         argument->expression = parse_assignment_expression();
7154                         if (last_argument == NULL) {
7155                                 call->arguments = argument;
7156                         } else {
7157                                 last_argument->next = argument;
7158                         }
7159                         last_argument = argument;
7160
7161                         if (token.type != ',')
7162                                 break;
7163                         next_token();
7164                 }
7165         }
7166         rem_anchor_token(',');
7167         rem_anchor_token(')');
7168         expect(')');
7169
7170         if (function_type == NULL)
7171                 return result;
7172
7173         function_parameter_t *parameter = function_type->parameters;
7174         call_argument_t      *argument  = call->arguments;
7175         if (!function_type->unspecified_parameters) {
7176                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7177                                 parameter = parameter->next, argument = argument->next) {
7178                         check_call_argument(parameter, argument, ++pos);
7179                 }
7180
7181                 if (parameter != NULL) {
7182                         errorf(HERE, "too few arguments to function '%E'", expression);
7183                 } else if (argument != NULL && !function_type->variadic) {
7184                         errorf(HERE, "too many arguments to function '%E'", expression);
7185                 }
7186         }
7187
7188         /* do default promotion */
7189         for( ; argument != NULL; argument = argument->next) {
7190                 type_t *type = argument->expression->base.type;
7191
7192                 type = get_default_promoted_type(type);
7193
7194                 argument->expression
7195                         = create_implicit_cast(argument->expression, type);
7196         }
7197
7198         check_format(&result->call);
7199
7200         if (warning.aggregate_return &&
7201             is_type_compound(skip_typeref(function_type->return_type))) {
7202                 warningf(&result->base.source_position,
7203                          "function call has aggregate value");
7204         }
7205
7206 end_error:
7207         return result;
7208 }
7209
7210 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7211
7212 static bool same_compound_type(const type_t *type1, const type_t *type2)
7213 {
7214         return
7215                 is_type_compound(type1) &&
7216                 type1->kind == type2->kind &&
7217                 type1->compound.declaration == type2->compound.declaration;
7218 }
7219
7220 /**
7221  * Parse a conditional expression, ie. 'expression ? ... : ...'.
7222  *
7223  * @param expression  the conditional expression
7224  */
7225 static expression_t *parse_conditional_expression(unsigned precedence,
7226                                                   expression_t *expression)
7227 {
7228         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7229
7230         conditional_expression_t *conditional = &result->conditional;
7231         conditional->base.source_position = *HERE;
7232         conditional->condition            = expression;
7233
7234         eat('?');
7235         add_anchor_token(':');
7236
7237         /* 6.5.15.2 */
7238         type_t *const condition_type_orig = expression->base.type;
7239         type_t *const condition_type      = skip_typeref(condition_type_orig);
7240         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7241                 type_error("expected a scalar type in conditional condition",
7242                            &expression->base.source_position, condition_type_orig);
7243         }
7244
7245         expression_t *true_expression = expression;
7246         bool          gnu_cond = false;
7247         if ((c_mode & _GNUC) && token.type == ':') {
7248                 gnu_cond = true;
7249         } else
7250                 true_expression = parse_expression();
7251         rem_anchor_token(':');
7252         expect(':');
7253         expression_t *false_expression = parse_sub_expression(precedence);
7254
7255         type_t *const orig_true_type  = true_expression->base.type;
7256         type_t *const orig_false_type = false_expression->base.type;
7257         type_t *const true_type       = skip_typeref(orig_true_type);
7258         type_t *const false_type      = skip_typeref(orig_false_type);
7259
7260         /* 6.5.15.3 */
7261         type_t *result_type;
7262         if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7263                 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7264                 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7265                     || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7266                         warningf(&conditional->base.source_position,
7267                                         "ISO C forbids conditional expression with only one void side");
7268                 }
7269                 result_type = type_void;
7270         } else if (is_type_arithmetic(true_type)
7271                    && is_type_arithmetic(false_type)) {
7272                 result_type = semantic_arithmetic(true_type, false_type);
7273
7274                 true_expression  = create_implicit_cast(true_expression, result_type);
7275                 false_expression = create_implicit_cast(false_expression, result_type);
7276
7277                 conditional->true_expression  = true_expression;
7278                 conditional->false_expression = false_expression;
7279                 conditional->base.type        = result_type;
7280         } else if (same_compound_type(true_type, false_type)) {
7281                 /* just take 1 of the 2 types */
7282                 result_type = true_type;
7283         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7284                 type_t *pointer_type;
7285                 type_t *other_type;
7286                 expression_t *other_expression;
7287                 if (is_type_pointer(true_type) &&
7288                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7289                         pointer_type     = true_type;
7290                         other_type       = false_type;
7291                         other_expression = false_expression;
7292                 } else {
7293                         pointer_type     = false_type;
7294                         other_type       = true_type;
7295                         other_expression = true_expression;
7296                 }
7297
7298                 if (is_null_pointer_constant(other_expression)) {
7299                         result_type = pointer_type;
7300                 } else if (is_type_pointer(other_type)) {
7301                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7302                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
7303
7304                         type_t *to;
7305                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7306                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7307                                 to = type_void;
7308                         } else if (types_compatible(get_unqualified_type(to1),
7309                                                     get_unqualified_type(to2))) {
7310                                 to = to1;
7311                         } else {
7312                                 warningf(&conditional->base.source_position,
7313                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
7314                                         true_type, false_type);
7315                                 to = type_void;
7316                         }
7317
7318                         type_t *const type =
7319                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7320                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7321                 } else if (is_type_integer(other_type)) {
7322                         warningf(&conditional->base.source_position,
7323                                         "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7324                         result_type = pointer_type;
7325                 } else {
7326                         type_error_incompatible("while parsing conditional",
7327                                         &expression->base.source_position, true_type, false_type);
7328                         result_type = type_error_type;
7329                 }
7330         } else {
7331                 /* TODO: one pointer to void*, other some pointer */
7332
7333                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7334                         type_error_incompatible("while parsing conditional",
7335                                                 &conditional->base.source_position, true_type,
7336                                                 false_type);
7337                 }
7338                 result_type = type_error_type;
7339         }
7340
7341         conditional->true_expression
7342                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7343         conditional->false_expression
7344                 = create_implicit_cast(false_expression, result_type);
7345         conditional->base.type = result_type;
7346         return result;
7347 end_error:
7348         return create_invalid_expression();
7349 }
7350
7351 /**
7352  * Parse an extension expression.
7353  */
7354 static expression_t *parse_extension(unsigned precedence)
7355 {
7356         eat(T___extension__);
7357
7358         /* TODO enable extensions */
7359         expression_t *expression = parse_sub_expression(precedence);
7360         /* TODO disable extensions */
7361         return expression;
7362 }
7363
7364 /**
7365  * Parse a __builtin_classify_type() expression.
7366  */
7367 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7368 {
7369         eat(T___builtin_classify_type);
7370
7371         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7372         result->base.type    = type_int;
7373
7374         expect('(');
7375         add_anchor_token(')');
7376         expression_t *expression = parse_sub_expression(precedence);
7377         rem_anchor_token(')');
7378         expect(')');
7379         result->classify_type.type_expression = expression;
7380
7381         return result;
7382 end_error:
7383         return create_invalid_expression();
7384 }
7385
7386 static bool check_pointer_arithmetic(const source_position_t *source_position,
7387                                      type_t *pointer_type,
7388                                      type_t *orig_pointer_type)
7389 {
7390         type_t *points_to = pointer_type->pointer.points_to;
7391         points_to = skip_typeref(points_to);
7392
7393         if (is_type_incomplete(points_to)) {
7394                 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7395                         errorf(source_position,
7396                                "arithmetic with pointer to incomplete type '%T' not allowed",
7397                                orig_pointer_type);
7398                         return false;
7399                 } else if (warning.pointer_arith) {
7400                         warningf(source_position,
7401                                  "pointer of type '%T' used in arithmetic",
7402                                  orig_pointer_type);
7403                 }
7404         } else if (is_type_function(points_to)) {
7405                 if (!(c_mode && _GNUC)) {
7406                         errorf(source_position,
7407                                "arithmetic with pointer to function type '%T' not allowed",
7408                                orig_pointer_type);
7409                         return false;
7410                 } else if (warning.pointer_arith) {
7411                         warningf(source_position,
7412                                  "pointer to a function '%T' used in arithmetic",
7413                                  orig_pointer_type);
7414                 }
7415         }
7416         return true;
7417 }
7418
7419 static bool is_lvalue(const expression_t *expression)
7420 {
7421         switch (expression->kind) {
7422         case EXPR_REFERENCE:
7423         case EXPR_ARRAY_ACCESS:
7424         case EXPR_SELECT:
7425         case EXPR_UNARY_DEREFERENCE:
7426                 return true;
7427
7428         default:
7429                 return false;
7430         }
7431 }
7432
7433 static void semantic_incdec(unary_expression_t *expression)
7434 {
7435         type_t *const orig_type = expression->value->base.type;
7436         type_t *const type      = skip_typeref(orig_type);
7437         if (is_type_pointer(type)) {
7438                 if (!check_pointer_arithmetic(&expression->base.source_position,
7439                                               type, orig_type)) {
7440                         return;
7441                 }
7442         } else if (!is_type_real(type) && is_type_valid(type)) {
7443                 /* TODO: improve error message */
7444                 errorf(&expression->base.source_position,
7445                        "operation needs an arithmetic or pointer type");
7446                 return;
7447         }
7448         if (!is_lvalue(expression->value)) {
7449                 /* TODO: improve error message */
7450                 errorf(&expression->base.source_position, "lvalue required as operand");
7451         }
7452         expression->base.type = orig_type;
7453 }
7454
7455 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7456 {
7457         type_t *const orig_type = expression->value->base.type;
7458         type_t *const type      = skip_typeref(orig_type);
7459         if (!is_type_arithmetic(type)) {
7460                 if (is_type_valid(type)) {
7461                         /* TODO: improve error message */
7462                         errorf(&expression->base.source_position,
7463                                 "operation needs an arithmetic type");
7464                 }
7465                 return;
7466         }
7467
7468         expression->base.type = orig_type;
7469 }
7470
7471 static void semantic_unexpr_plus(unary_expression_t *expression)
7472 {
7473         semantic_unexpr_arithmetic(expression);
7474         if (warning.traditional)
7475                 warningf(&expression->base.source_position,
7476                         "traditional C rejects the unary plus operator");
7477 }
7478
7479 static void semantic_not(unary_expression_t *expression)
7480 {
7481         type_t *const orig_type = expression->value->base.type;
7482         type_t *const type      = skip_typeref(orig_type);
7483         if (!is_type_scalar(type) && is_type_valid(type)) {
7484                 errorf(&expression->base.source_position,
7485                        "operand of ! must be of scalar type");
7486         }
7487
7488         expression->base.type = type_int;
7489 }
7490
7491 static void semantic_unexpr_integer(unary_expression_t *expression)
7492 {
7493         type_t *const orig_type = expression->value->base.type;
7494         type_t *const type      = skip_typeref(orig_type);
7495         if (!is_type_integer(type)) {
7496                 if (is_type_valid(type)) {
7497                         errorf(&expression->base.source_position,
7498                                "operand of ~ must be of integer type");
7499                 }
7500                 return;
7501         }
7502
7503         expression->base.type = orig_type;
7504 }
7505
7506 static void semantic_dereference(unary_expression_t *expression)
7507 {
7508         type_t *const orig_type = expression->value->base.type;
7509         type_t *const type      = skip_typeref(orig_type);
7510         if (!is_type_pointer(type)) {
7511                 if (is_type_valid(type)) {
7512                         errorf(&expression->base.source_position,
7513                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7514                 }
7515                 return;
7516         }
7517
7518         type_t *result_type   = type->pointer.points_to;
7519         result_type           = automatic_type_conversion(result_type);
7520         expression->base.type = result_type;
7521 }
7522
7523 /**
7524  * Record that an address is taken (expression represents an lvalue).
7525  *
7526  * @param expression       the expression
7527  * @param may_be_register  if true, the expression might be an register
7528  */
7529 static void set_address_taken(expression_t *expression, bool may_be_register)
7530 {
7531         if (expression->kind != EXPR_REFERENCE)
7532                 return;
7533
7534         declaration_t *const declaration = expression->reference.declaration;
7535         /* happens for parse errors */
7536         if (declaration == NULL)
7537                 return;
7538
7539         if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7540                 errorf(&expression->base.source_position,
7541                                 "address of register variable '%Y' requested",
7542                                 declaration->symbol);
7543         } else {
7544                 declaration->address_taken = 1;
7545         }
7546 }
7547
7548 /**
7549  * Check the semantic of the address taken expression.
7550  */
7551 static void semantic_take_addr(unary_expression_t *expression)
7552 {
7553         expression_t *value = expression->value;
7554         value->base.type    = revert_automatic_type_conversion(value);
7555
7556         type_t *orig_type = value->base.type;
7557         if (!is_type_valid(orig_type))
7558                 return;
7559
7560         set_address_taken(value, false);
7561
7562         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7563 }
7564
7565 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
7566 static expression_t *parse_##unexpression_type(unsigned precedence)            \
7567 {                                                                              \
7568         expression_t *unary_expression                                             \
7569                 = allocate_expression_zero(unexpression_type);                         \
7570         unary_expression->base.source_position = *HERE;                            \
7571         eat(token_type);                                                           \
7572         unary_expression->unary.value = parse_sub_expression(precedence);          \
7573                                                                                    \
7574         sfunc(&unary_expression->unary);                                           \
7575                                                                                    \
7576         return unary_expression;                                                   \
7577 }
7578
7579 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7580                                semantic_unexpr_arithmetic)
7581 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7582                                semantic_unexpr_plus)
7583 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7584                                semantic_not)
7585 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7586                                semantic_dereference)
7587 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7588                                semantic_take_addr)
7589 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7590                                semantic_unexpr_integer)
7591 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
7592                                semantic_incdec)
7593 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7594                                semantic_incdec)
7595
7596 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7597                                                sfunc)                         \
7598 static expression_t *parse_##unexpression_type(unsigned precedence,           \
7599                                                expression_t *left)            \
7600 {                                                                             \
7601         (void) precedence;                                                        \
7602                                                                               \
7603         expression_t *unary_expression                                            \
7604                 = allocate_expression_zero(unexpression_type);                        \
7605         unary_expression->base.source_position = *HERE;                           \
7606         eat(token_type);                                                          \
7607         unary_expression->unary.value          = left;                            \
7608                                                                                   \
7609         sfunc(&unary_expression->unary);                                          \
7610                                                                               \
7611         return unary_expression;                                                  \
7612 }
7613
7614 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7615                                        EXPR_UNARY_POSTFIX_INCREMENT,
7616                                        semantic_incdec)
7617 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7618                                        EXPR_UNARY_POSTFIX_DECREMENT,
7619                                        semantic_incdec)
7620
7621 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7622 {
7623         /* TODO: handle complex + imaginary types */
7624
7625         type_left  = get_unqualified_type(type_left);
7626         type_right = get_unqualified_type(type_right);
7627
7628         /* Â§ 6.3.1.8 Usual arithmetic conversions */
7629         if (type_left == type_long_double || type_right == type_long_double) {
7630                 return type_long_double;
7631         } else if (type_left == type_double || type_right == type_double) {
7632                 return type_double;
7633         } else if (type_left == type_float || type_right == type_float) {
7634                 return type_float;
7635         }
7636
7637         type_left  = promote_integer(type_left);
7638         type_right = promote_integer(type_right);
7639
7640         if (type_left == type_right)
7641                 return type_left;
7642
7643         bool const signed_left  = is_type_signed(type_left);
7644         bool const signed_right = is_type_signed(type_right);
7645         int const  rank_left    = get_rank(type_left);
7646         int const  rank_right   = get_rank(type_right);
7647
7648         if (signed_left == signed_right)
7649                 return rank_left >= rank_right ? type_left : type_right;
7650
7651         int     s_rank;
7652         int     u_rank;
7653         type_t *s_type;
7654         type_t *u_type;
7655         if (signed_left) {
7656                 s_rank = rank_left;
7657                 s_type = type_left;
7658                 u_rank = rank_right;
7659                 u_type = type_right;
7660         } else {
7661                 s_rank = rank_right;
7662                 s_type = type_right;
7663                 u_rank = rank_left;
7664                 u_type = type_left;
7665         }
7666
7667         if (u_rank >= s_rank)
7668                 return u_type;
7669
7670         /* casting rank to atomic_type_kind is a bit hacky, but makes things
7671          * easier here... */
7672         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7673                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
7674                 return s_type;
7675
7676         switch (s_rank) {
7677                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
7678                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
7679                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7680
7681                 default: panic("invalid atomic type");
7682         }
7683 }
7684
7685 /**
7686  * Check the semantic restrictions for a binary expression.
7687  */
7688 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7689 {
7690         expression_t *const left            = expression->left;
7691         expression_t *const right           = expression->right;
7692         type_t       *const orig_type_left  = left->base.type;
7693         type_t       *const orig_type_right = right->base.type;
7694         type_t       *const type_left       = skip_typeref(orig_type_left);
7695         type_t       *const type_right      = skip_typeref(orig_type_right);
7696
7697         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7698                 /* TODO: improve error message */
7699                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7700                         errorf(&expression->base.source_position,
7701                                "operation needs arithmetic types");
7702                 }
7703                 return;
7704         }
7705
7706         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7707         expression->left      = create_implicit_cast(left, arithmetic_type);
7708         expression->right     = create_implicit_cast(right, arithmetic_type);
7709         expression->base.type = arithmetic_type;
7710 }
7711
7712 static void warn_div_by_zero(binary_expression_t const *const expression)
7713 {
7714         if (!warning.div_by_zero ||
7715             !is_type_integer(expression->base.type))
7716                 return;
7717
7718         expression_t const *const right = expression->right;
7719         /* The type of the right operand can be different for /= */
7720         if (is_type_integer(right->base.type) &&
7721             is_constant_expression(right)     &&
7722             fold_constant(right) == 0) {
7723                 warningf(&expression->base.source_position, "division by zero");
7724         }
7725 }
7726
7727 /**
7728  * Check the semantic restrictions for a div/mod expression.
7729  */
7730 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7731         semantic_binexpr_arithmetic(expression);
7732         warn_div_by_zero(expression);
7733 }
7734
7735 static void semantic_shift_op(binary_expression_t *expression)
7736 {
7737         expression_t *const left            = expression->left;
7738         expression_t *const right           = expression->right;
7739         type_t       *const orig_type_left  = left->base.type;
7740         type_t       *const orig_type_right = right->base.type;
7741         type_t       *      type_left       = skip_typeref(orig_type_left);
7742         type_t       *      type_right      = skip_typeref(orig_type_right);
7743
7744         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7745                 /* TODO: improve error message */
7746                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7747                         errorf(&expression->base.source_position,
7748                                "operands of shift operation must have integer types");
7749                 }
7750                 return;
7751         }
7752
7753         type_left  = promote_integer(type_left);
7754         type_right = promote_integer(type_right);
7755
7756         expression->left      = create_implicit_cast(left, type_left);
7757         expression->right     = create_implicit_cast(right, type_right);
7758         expression->base.type = type_left;
7759 }
7760
7761 static void semantic_add(binary_expression_t *expression)
7762 {
7763         expression_t *const left            = expression->left;
7764         expression_t *const right           = expression->right;
7765         type_t       *const orig_type_left  = left->base.type;
7766         type_t       *const orig_type_right = right->base.type;
7767         type_t       *const type_left       = skip_typeref(orig_type_left);
7768         type_t       *const type_right      = skip_typeref(orig_type_right);
7769
7770         /* Â§ 6.5.6 */
7771         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7772                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7773                 expression->left  = create_implicit_cast(left, arithmetic_type);
7774                 expression->right = create_implicit_cast(right, arithmetic_type);
7775                 expression->base.type = arithmetic_type;
7776                 return;
7777         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7778                 check_pointer_arithmetic(&expression->base.source_position,
7779                                          type_left, orig_type_left);
7780                 expression->base.type = type_left;
7781         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7782                 check_pointer_arithmetic(&expression->base.source_position,
7783                                          type_right, orig_type_right);
7784                 expression->base.type = type_right;
7785         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7786                 errorf(&expression->base.source_position,
7787                        "invalid operands to binary + ('%T', '%T')",
7788                        orig_type_left, orig_type_right);
7789         }
7790 }
7791
7792 static void semantic_sub(binary_expression_t *expression)
7793 {
7794         expression_t            *const left            = expression->left;
7795         expression_t            *const right           = expression->right;
7796         type_t                  *const orig_type_left  = left->base.type;
7797         type_t                  *const orig_type_right = right->base.type;
7798         type_t                  *const type_left       = skip_typeref(orig_type_left);
7799         type_t                  *const type_right      = skip_typeref(orig_type_right);
7800         source_position_t const *const pos             = &expression->base.source_position;
7801
7802         /* Â§ 5.6.5 */
7803         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7804                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7805                 expression->left        = create_implicit_cast(left, arithmetic_type);
7806                 expression->right       = create_implicit_cast(right, arithmetic_type);
7807                 expression->base.type =  arithmetic_type;
7808                 return;
7809         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7810                 check_pointer_arithmetic(&expression->base.source_position,
7811                                          type_left, orig_type_left);
7812                 expression->base.type = type_left;
7813         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7814                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7815                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7816                 if (!types_compatible(unqual_left, unqual_right)) {
7817                         errorf(pos,
7818                                "subtracting pointers to incompatible types '%T' and '%T'",
7819                                orig_type_left, orig_type_right);
7820                 } else if (!is_type_object(unqual_left)) {
7821                         if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7822                                 warningf(pos, "subtracting pointers to void");
7823                         } else {
7824                                 errorf(pos, "subtracting pointers to non-object types '%T'",
7825                                        orig_type_left);
7826                         }
7827                 }
7828                 expression->base.type = type_ptrdiff_t;
7829         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7830                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7831                        orig_type_left, orig_type_right);
7832         }
7833 }
7834
7835 /**
7836  * Check the semantics of comparison expressions.
7837  *
7838  * @param expression   The expression to check.
7839  */
7840 static void semantic_comparison(binary_expression_t *expression)
7841 {
7842         expression_t *left            = expression->left;
7843         expression_t *right           = expression->right;
7844         type_t       *orig_type_left  = left->base.type;
7845         type_t       *orig_type_right = right->base.type;
7846
7847         type_t *type_left  = skip_typeref(orig_type_left);
7848         type_t *type_right = skip_typeref(orig_type_right);
7849
7850         /* TODO non-arithmetic types */
7851         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7852                 /* test for signed vs unsigned compares */
7853                 if (warning.sign_compare &&
7854                     (expression->base.kind != EXPR_BINARY_EQUAL &&
7855                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7856                     (is_type_signed(type_left) != is_type_signed(type_right))) {
7857
7858                         /* check if 1 of the operands is a constant, in this case we just
7859                          * check wether we can safely represent the resulting constant in
7860                          * the type of the other operand. */
7861                         expression_t *const_expr = NULL;
7862                         expression_t *other_expr = NULL;
7863
7864                         if (is_constant_expression(left)) {
7865                                 const_expr = left;
7866                                 other_expr = right;
7867                         } else if (is_constant_expression(right)) {
7868                                 const_expr = right;
7869                                 other_expr = left;
7870                         }
7871
7872                         if (const_expr != NULL) {
7873                                 type_t *other_type = skip_typeref(other_expr->base.type);
7874                                 long    val        = fold_constant(const_expr);
7875                                 /* TODO: check if val can be represented by other_type */
7876                                 (void) other_type;
7877                                 (void) val;
7878                         }
7879                         warningf(&expression->base.source_position,
7880                                  "comparison between signed and unsigned");
7881                 }
7882                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7883                 expression->left        = create_implicit_cast(left, arithmetic_type);
7884                 expression->right       = create_implicit_cast(right, arithmetic_type);
7885                 expression->base.type   = arithmetic_type;
7886                 if (warning.float_equal &&
7887                     (expression->base.kind == EXPR_BINARY_EQUAL ||
7888                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7889                     is_type_float(arithmetic_type)) {
7890                         warningf(&expression->base.source_position,
7891                                  "comparing floating point with == or != is unsafe");
7892                 }
7893         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7894                 /* TODO check compatibility */
7895         } else if (is_type_pointer(type_left)) {
7896                 expression->right = create_implicit_cast(right, type_left);
7897         } else if (is_type_pointer(type_right)) {
7898                 expression->left = create_implicit_cast(left, type_right);
7899         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7900                 type_error_incompatible("invalid operands in comparison",
7901                                         &expression->base.source_position,
7902                                         type_left, type_right);
7903         }
7904         expression->base.type = type_int;
7905 }
7906
7907 /**
7908  * Checks if a compound type has constant fields.
7909  */
7910 static bool has_const_fields(const compound_type_t *type)
7911 {
7912         const scope_t       *scope       = &type->declaration->scope;
7913         const declaration_t *declaration = scope->declarations;
7914
7915         for (; declaration != NULL; declaration = declaration->next) {
7916                 if (declaration->namespc != NAMESPACE_NORMAL)
7917                         continue;
7918
7919                 const type_t *decl_type = skip_typeref(declaration->type);
7920                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7921                         return true;
7922         }
7923         /* TODO */
7924         return false;
7925 }
7926
7927 static bool is_valid_assignment_lhs(expression_t const* const left)
7928 {
7929         type_t *const orig_type_left = revert_automatic_type_conversion(left);
7930         type_t *const type_left      = skip_typeref(orig_type_left);
7931
7932         if (!is_lvalue(left)) {
7933                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7934                        left);
7935                 return false;
7936         }
7937
7938         if (is_type_array(type_left)) {
7939                 errorf(HERE, "cannot assign to arrays ('%E')", left);
7940                 return false;
7941         }
7942         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7943                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7944                        orig_type_left);
7945                 return false;
7946         }
7947         if (is_type_incomplete(type_left)) {
7948                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7949                        left, orig_type_left);
7950                 return false;
7951         }
7952         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7953                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7954                        left, orig_type_left);
7955                 return false;
7956         }
7957
7958         return true;
7959 }
7960
7961 static void semantic_arithmetic_assign(binary_expression_t *expression)
7962 {
7963         expression_t *left            = expression->left;
7964         expression_t *right           = expression->right;
7965         type_t       *orig_type_left  = left->base.type;
7966         type_t       *orig_type_right = right->base.type;
7967
7968         if (!is_valid_assignment_lhs(left))
7969                 return;
7970
7971         type_t *type_left  = skip_typeref(orig_type_left);
7972         type_t *type_right = skip_typeref(orig_type_right);
7973
7974         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7975                 /* TODO: improve error message */
7976                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7977                         errorf(&expression->base.source_position,
7978                                "operation needs arithmetic types");
7979                 }
7980                 return;
7981         }
7982
7983         /* combined instructions are tricky. We can't create an implicit cast on
7984          * the left side, because we need the uncasted form for the store.
7985          * The ast2firm pass has to know that left_type must be right_type
7986          * for the arithmetic operation and create a cast by itself */
7987         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7988         expression->right       = create_implicit_cast(right, arithmetic_type);
7989         expression->base.type   = type_left;
7990 }
7991
7992 static void semantic_divmod_assign(binary_expression_t *expression)
7993 {
7994         semantic_arithmetic_assign(expression);
7995         warn_div_by_zero(expression);
7996 }
7997
7998 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7999 {
8000         expression_t *const left            = expression->left;
8001         expression_t *const right           = expression->right;
8002         type_t       *const orig_type_left  = left->base.type;
8003         type_t       *const orig_type_right = right->base.type;
8004         type_t       *const type_left       = skip_typeref(orig_type_left);
8005         type_t       *const type_right      = skip_typeref(orig_type_right);
8006
8007         if (!is_valid_assignment_lhs(left))
8008                 return;
8009
8010         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8011                 /* combined instructions are tricky. We can't create an implicit cast on
8012                  * the left side, because we need the uncasted form for the store.
8013                  * The ast2firm pass has to know that left_type must be right_type
8014                  * for the arithmetic operation and create a cast by itself */
8015                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8016                 expression->right     = create_implicit_cast(right, arithmetic_type);
8017                 expression->base.type = type_left;
8018         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8019                 check_pointer_arithmetic(&expression->base.source_position,
8020                                          type_left, orig_type_left);
8021                 expression->base.type = type_left;
8022         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8023                 errorf(&expression->base.source_position,
8024                        "incompatible types '%T' and '%T' in assignment",
8025                        orig_type_left, orig_type_right);
8026         }
8027 }
8028
8029 /**
8030  * Check the semantic restrictions of a logical expression.
8031  */
8032 static void semantic_logical_op(binary_expression_t *expression)
8033 {
8034         expression_t *const left            = expression->left;
8035         expression_t *const right           = expression->right;
8036         type_t       *const orig_type_left  = left->base.type;
8037         type_t       *const orig_type_right = right->base.type;
8038         type_t       *const type_left       = skip_typeref(orig_type_left);
8039         type_t       *const type_right      = skip_typeref(orig_type_right);
8040
8041         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8042                 /* TODO: improve error message */
8043                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8044                         errorf(&expression->base.source_position,
8045                                "operation needs scalar types");
8046                 }
8047                 return;
8048         }
8049
8050         expression->base.type = type_int;
8051 }
8052
8053 /**
8054  * Check the semantic restrictions of a binary assign expression.
8055  */
8056 static void semantic_binexpr_assign(binary_expression_t *expression)
8057 {
8058         expression_t *left           = expression->left;
8059         type_t       *orig_type_left = left->base.type;
8060
8061         if (!is_valid_assignment_lhs(left))
8062                 return;
8063
8064         assign_error_t error = semantic_assign(orig_type_left, expression->right);
8065         report_assign_error(error, orig_type_left, expression->right,
8066                         "assignment", &left->base.source_position);
8067         expression->right = create_implicit_cast(expression->right, orig_type_left);
8068         expression->base.type = orig_type_left;
8069 }
8070
8071 /**
8072  * Determine if the outermost operation (or parts thereof) of the given
8073  * expression has no effect in order to generate a warning about this fact.
8074  * Therefore in some cases this only examines some of the operands of the
8075  * expression (see comments in the function and examples below).
8076  * Examples:
8077  *   f() + 23;    // warning, because + has no effect
8078  *   x || f();    // no warning, because x controls execution of f()
8079  *   x ? y : f(); // warning, because y has no effect
8080  *   (void)x;     // no warning to be able to suppress the warning
8081  * This function can NOT be used for an "expression has definitely no effect"-
8082  * analysis. */
8083 static bool expression_has_effect(const expression_t *const expr)
8084 {
8085         switch (expr->kind) {
8086                 case EXPR_UNKNOWN:                   break;
8087                 case EXPR_INVALID:                   return true; /* do NOT warn */
8088                 case EXPR_REFERENCE:                 return false;
8089                 /* suppress the warning for microsoft __noop operations */
8090                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
8091                 case EXPR_CHARACTER_CONSTANT:        return false;
8092                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
8093                 case EXPR_STRING_LITERAL:            return false;
8094                 case EXPR_WIDE_STRING_LITERAL:       return false;
8095                 case EXPR_LABEL_ADDRESS:             return false;
8096
8097                 case EXPR_CALL: {
8098                         const call_expression_t *const call = &expr->call;
8099                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8100                                 return true;
8101
8102                         switch (call->function->builtin_symbol.symbol->ID) {
8103                                 case T___builtin_va_end: return true;
8104                                 default:                 return false;
8105                         }
8106                 }
8107
8108                 /* Generate the warning if either the left or right hand side of a
8109                  * conditional expression has no effect */
8110                 case EXPR_CONDITIONAL: {
8111                         const conditional_expression_t *const cond = &expr->conditional;
8112                         return
8113                                 expression_has_effect(cond->true_expression) &&
8114                                 expression_has_effect(cond->false_expression);
8115                 }
8116
8117                 case EXPR_SELECT:                    return false;
8118                 case EXPR_ARRAY_ACCESS:              return false;
8119                 case EXPR_SIZEOF:                    return false;
8120                 case EXPR_CLASSIFY_TYPE:             return false;
8121                 case EXPR_ALIGNOF:                   return false;
8122
8123                 case EXPR_FUNCNAME:                  return false;
8124                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
8125                 case EXPR_BUILTIN_CONSTANT_P:        return false;
8126                 case EXPR_BUILTIN_PREFETCH:          return true;
8127                 case EXPR_OFFSETOF:                  return false;
8128                 case EXPR_VA_START:                  return true;
8129                 case EXPR_VA_ARG:                    return true;
8130                 case EXPR_STATEMENT:                 return true; // TODO
8131                 case EXPR_COMPOUND_LITERAL:          return false;
8132
8133                 case EXPR_UNARY_NEGATE:              return false;
8134                 case EXPR_UNARY_PLUS:                return false;
8135                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
8136                 case EXPR_UNARY_NOT:                 return false;
8137                 case EXPR_UNARY_DEREFERENCE:         return false;
8138                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
8139                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
8140                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
8141                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
8142                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
8143
8144                 /* Treat void casts as if they have an effect in order to being able to
8145                  * suppress the warning */
8146                 case EXPR_UNARY_CAST: {
8147                         type_t *const type = skip_typeref(expr->base.type);
8148                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
8149                 }
8150
8151                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
8152                 case EXPR_UNARY_ASSUME:              return true;
8153
8154                 case EXPR_BINARY_ADD:                return false;
8155                 case EXPR_BINARY_SUB:                return false;
8156                 case EXPR_BINARY_MUL:                return false;
8157                 case EXPR_BINARY_DIV:                return false;
8158                 case EXPR_BINARY_MOD:                return false;
8159                 case EXPR_BINARY_EQUAL:              return false;
8160                 case EXPR_BINARY_NOTEQUAL:           return false;
8161                 case EXPR_BINARY_LESS:               return false;
8162                 case EXPR_BINARY_LESSEQUAL:          return false;
8163                 case EXPR_BINARY_GREATER:            return false;
8164                 case EXPR_BINARY_GREATEREQUAL:       return false;
8165                 case EXPR_BINARY_BITWISE_AND:        return false;
8166                 case EXPR_BINARY_BITWISE_OR:         return false;
8167                 case EXPR_BINARY_BITWISE_XOR:        return false;
8168                 case EXPR_BINARY_SHIFTLEFT:          return false;
8169                 case EXPR_BINARY_SHIFTRIGHT:         return false;
8170                 case EXPR_BINARY_ASSIGN:             return true;
8171                 case EXPR_BINARY_MUL_ASSIGN:         return true;
8172                 case EXPR_BINARY_DIV_ASSIGN:         return true;
8173                 case EXPR_BINARY_MOD_ASSIGN:         return true;
8174                 case EXPR_BINARY_ADD_ASSIGN:         return true;
8175                 case EXPR_BINARY_SUB_ASSIGN:         return true;
8176                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
8177                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
8178                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8179                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8180                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
8181
8182                 /* Only examine the right hand side of && and ||, because the left hand
8183                  * side already has the effect of controlling the execution of the right
8184                  * hand side */
8185                 case EXPR_BINARY_LOGICAL_AND:
8186                 case EXPR_BINARY_LOGICAL_OR:
8187                 /* Only examine the right hand side of a comma expression, because the left
8188                  * hand side has a separate warning */
8189                 case EXPR_BINARY_COMMA:
8190                         return expression_has_effect(expr->binary.right);
8191
8192                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
8193                 case EXPR_BINARY_ISGREATER:          return false;
8194                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
8195                 case EXPR_BINARY_ISLESS:             return false;
8196                 case EXPR_BINARY_ISLESSEQUAL:        return false;
8197                 case EXPR_BINARY_ISLESSGREATER:      return false;
8198                 case EXPR_BINARY_ISUNORDERED:        return false;
8199         }
8200
8201         internal_errorf(HERE, "unexpected expression");
8202 }
8203
8204 static void semantic_comma(binary_expression_t *expression)
8205 {
8206         if (warning.unused_value) {
8207                 const expression_t *const left = expression->left;
8208                 if (!expression_has_effect(left)) {
8209                         warningf(&left->base.source_position,
8210                                  "left-hand operand of comma expression has no effect");
8211                 }
8212         }
8213         expression->base.type = expression->right->base.type;
8214 }
8215
8216 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
8217 static expression_t *parse_##binexpression_type(unsigned precedence,      \
8218                                                 expression_t *left)       \
8219 {                                                                         \
8220         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8221         binexpr->base.source_position = *HERE;                                \
8222         binexpr->binary.left          = left;                                 \
8223         eat(token_type);                                                      \
8224                                                                           \
8225         expression_t *right = parse_sub_expression(precedence + lr);          \
8226                                                                           \
8227         binexpr->binary.right = right;                                        \
8228         sfunc(&binexpr->binary);                                              \
8229                                                                           \
8230         return binexpr;                                                       \
8231 }
8232
8233 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
8234 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
8235 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_divmod_arithmetic, 1)
8236 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_divmod_arithmetic, 1)
8237 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
8238 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
8239 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
8240 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
8241 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
8242
8243 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
8244                       semantic_comparison, 1)
8245 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8246                       semantic_comparison, 1)
8247 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
8248                       semantic_comparison, 1)
8249 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
8250                       semantic_comparison, 1)
8251
8252 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8253                       semantic_binexpr_arithmetic, 1)
8254 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8255                       semantic_binexpr_arithmetic, 1)
8256 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8257                       semantic_binexpr_arithmetic, 1)
8258 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8259                       semantic_logical_op, 1)
8260 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8261                       semantic_logical_op, 1)
8262 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8263                       semantic_shift_op, 1)
8264 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8265                       semantic_shift_op, 1)
8266 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8267                       semantic_arithmetic_addsubb_assign, 0)
8268 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8269                       semantic_arithmetic_addsubb_assign, 0)
8270 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8271                       semantic_arithmetic_assign, 0)
8272 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8273                       semantic_divmod_assign, 0)
8274 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8275                       semantic_divmod_assign, 0)
8276 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8277                       semantic_arithmetic_assign, 0)
8278 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8279                       semantic_arithmetic_assign, 0)
8280 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8281                       semantic_arithmetic_assign, 0)
8282 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8283                       semantic_arithmetic_assign, 0)
8284 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8285                       semantic_arithmetic_assign, 0)
8286
8287 static expression_t *parse_sub_expression(unsigned precedence)
8288 {
8289         if (token.type < 0) {
8290                 return expected_expression_error();
8291         }
8292
8293         expression_parser_function_t *parser
8294                 = &expression_parsers[token.type];
8295         source_position_t             source_position = token.source_position;
8296         expression_t                 *left;
8297
8298         if (parser->parser != NULL) {
8299                 left = parser->parser(parser->precedence);
8300         } else {
8301                 left = parse_primary_expression();
8302         }
8303         assert(left != NULL);
8304         left->base.source_position = source_position;
8305
8306         while(true) {
8307                 if (token.type < 0) {
8308                         return expected_expression_error();
8309                 }
8310
8311                 parser = &expression_parsers[token.type];
8312                 if (parser->infix_parser == NULL)
8313                         break;
8314                 if (parser->infix_precedence < precedence)
8315                         break;
8316
8317                 left = parser->infix_parser(parser->infix_precedence, left);
8318
8319                 assert(left != NULL);
8320                 assert(left->kind != EXPR_UNKNOWN);
8321                 left->base.source_position = source_position;
8322         }
8323
8324         return left;
8325 }
8326
8327 /**
8328  * Parse an expression.
8329  */
8330 static expression_t *parse_expression(void)
8331 {
8332         return parse_sub_expression(1);
8333 }
8334
8335 /**
8336  * Register a parser for a prefix-like operator with given precedence.
8337  *
8338  * @param parser      the parser function
8339  * @param token_type  the token type of the prefix token
8340  * @param precedence  the precedence of the operator
8341  */
8342 static void register_expression_parser(parse_expression_function parser,
8343                                        int token_type, unsigned precedence)
8344 {
8345         expression_parser_function_t *entry = &expression_parsers[token_type];
8346
8347         if (entry->parser != NULL) {
8348                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8349                 panic("trying to register multiple expression parsers for a token");
8350         }
8351         entry->parser     = parser;
8352         entry->precedence = precedence;
8353 }
8354
8355 /**
8356  * Register a parser for an infix operator with given precedence.
8357  *
8358  * @param parser      the parser function
8359  * @param token_type  the token type of the infix operator
8360  * @param precedence  the precedence of the operator
8361  */
8362 static void register_infix_parser(parse_expression_infix_function parser,
8363                 int token_type, unsigned precedence)
8364 {
8365         expression_parser_function_t *entry = &expression_parsers[token_type];
8366
8367         if (entry->infix_parser != NULL) {
8368                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8369                 panic("trying to register multiple infix expression parsers for a "
8370                       "token");
8371         }
8372         entry->infix_parser     = parser;
8373         entry->infix_precedence = precedence;
8374 }
8375
8376 /**
8377  * Initialize the expression parsers.
8378  */
8379 static void init_expression_parsers(void)
8380 {
8381         memset(&expression_parsers, 0, sizeof(expression_parsers));
8382
8383         register_infix_parser(parse_array_expression,         '[',              30);
8384         register_infix_parser(parse_call_expression,          '(',              30);
8385         register_infix_parser(parse_select_expression,        '.',              30);
8386         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
8387         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8388                                                               T_PLUSPLUS,       30);
8389         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8390                                                               T_MINUSMINUS,     30);
8391
8392         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              17);
8393         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              17);
8394         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              17);
8395         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              16);
8396         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              16);
8397         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       15);
8398         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 15);
8399         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
8400         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
8401         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
8402         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
8403         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
8404         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8405                                                     T_EXCLAMATIONMARKEQUAL, 13);
8406         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
8407         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
8408         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
8409         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
8410         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
8411         register_infix_parser(parse_conditional_expression,   '?',               7);
8412         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
8413         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
8414         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
8415         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
8416         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
8417         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
8418         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8419                                                                 T_LESSLESSEQUAL, 2);
8420         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8421                                                           T_GREATERGREATEREQUAL, 2);
8422         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8423                                                                      T_ANDEQUAL, 2);
8424         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8425                                                                     T_PIPEEQUAL, 2);
8426         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8427                                                                    T_CARETEQUAL, 2);
8428
8429         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
8430
8431         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
8432         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
8433         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
8434         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
8435         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
8436         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
8437         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8438                                                                   T_PLUSPLUS,   25);
8439         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8440                                                                   T_MINUSMINUS, 25);
8441         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
8442         register_expression_parser(parse_alignof,                T___alignof__, 25);
8443         register_expression_parser(parse_extension,            T___extension__, 25);
8444         register_expression_parser(parse_builtin_classify_type,
8445                                                      T___builtin_classify_type, 25);
8446 }
8447
8448 /**
8449  * Parse a asm statement arguments specification.
8450  */
8451 static asm_argument_t *parse_asm_arguments(bool is_out)
8452 {
8453         asm_argument_t *result = NULL;
8454         asm_argument_t *last   = NULL;
8455
8456         while (token.type == T_STRING_LITERAL || token.type == '[') {
8457                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8458                 memset(argument, 0, sizeof(argument[0]));
8459
8460                 if (token.type == '[') {
8461                         eat('[');
8462                         if (token.type != T_IDENTIFIER) {
8463                                 parse_error_expected("while parsing asm argument",
8464                                                      T_IDENTIFIER, NULL);
8465                                 return NULL;
8466                         }
8467                         argument->symbol = token.v.symbol;
8468
8469                         expect(']');
8470                 }
8471
8472                 argument->constraints = parse_string_literals();
8473                 expect('(');
8474                 add_anchor_token(')');
8475                 expression_t *expression = parse_expression();
8476                 rem_anchor_token(')');
8477                 if (is_out) {
8478                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
8479                          * change size or type representation (e.g. int -> long is ok, but
8480                          * int -> float is not) */
8481                         if (expression->kind == EXPR_UNARY_CAST) {
8482                                 type_t      *const type = expression->base.type;
8483                                 type_kind_t  const kind = type->kind;
8484                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8485                                         unsigned flags;
8486                                         unsigned size;
8487                                         if (kind == TYPE_ATOMIC) {
8488                                                 atomic_type_kind_t const akind = type->atomic.akind;
8489                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8490                                                 size  = get_atomic_type_size(akind);
8491                                         } else {
8492                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8493                                                 size  = get_atomic_type_size(get_intptr_kind());
8494                                         }
8495
8496                                         do {
8497                                                 expression_t *const value      = expression->unary.value;
8498                                                 type_t       *const value_type = value->base.type;
8499                                                 type_kind_t   const value_kind = value_type->kind;
8500
8501                                                 unsigned value_flags;
8502                                                 unsigned value_size;
8503                                                 if (value_kind == TYPE_ATOMIC) {
8504                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
8505                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8506                                                         value_size  = get_atomic_type_size(value_akind);
8507                                                 } else if (value_kind == TYPE_POINTER) {
8508                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8509                                                         value_size  = get_atomic_type_size(get_intptr_kind());
8510                                                 } else {
8511                                                         break;
8512                                                 }
8513
8514                                                 if (value_flags != flags || value_size != size)
8515                                                         break;
8516
8517                                                 expression = value;
8518                                         } while (expression->kind == EXPR_UNARY_CAST);
8519                                 }
8520                         }
8521
8522                         if (!is_lvalue(expression)) {
8523                                 errorf(&expression->base.source_position,
8524                                        "asm output argument is not an lvalue");
8525                         }
8526                 }
8527                 argument->expression = expression;
8528                 expect(')');
8529
8530                 set_address_taken(expression, true);
8531
8532                 if (last != NULL) {
8533                         last->next = argument;
8534                 } else {
8535                         result = argument;
8536                 }
8537                 last = argument;
8538
8539                 if (token.type != ',')
8540                         break;
8541                 eat(',');
8542         }
8543
8544         return result;
8545 end_error:
8546         return NULL;
8547 }
8548
8549 /**
8550  * Parse a asm statement clobber specification.
8551  */
8552 static asm_clobber_t *parse_asm_clobbers(void)
8553 {
8554         asm_clobber_t *result = NULL;
8555         asm_clobber_t *last   = NULL;
8556
8557         while(token.type == T_STRING_LITERAL) {
8558                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8559                 clobber->clobber       = parse_string_literals();
8560
8561                 if (last != NULL) {
8562                         last->next = clobber;
8563                 } else {
8564                         result = clobber;
8565                 }
8566                 last = clobber;
8567
8568                 if (token.type != ',')
8569                         break;
8570                 eat(',');
8571         }
8572
8573         return result;
8574 }
8575
8576 /**
8577  * Parse an asm statement.
8578  */
8579 static statement_t *parse_asm_statement(void)
8580 {
8581         eat(T_asm);
8582
8583         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
8584         statement->base.source_position = token.source_position;
8585
8586         asm_statement_t *asm_statement = &statement->asms;
8587
8588         if (token.type == T_volatile) {
8589                 next_token();
8590                 asm_statement->is_volatile = true;
8591         }
8592
8593         expect('(');
8594         add_anchor_token(')');
8595         add_anchor_token(':');
8596         asm_statement->asm_text = parse_string_literals();
8597
8598         if (token.type != ':') {
8599                 rem_anchor_token(':');
8600                 goto end_of_asm;
8601         }
8602         eat(':');
8603
8604         asm_statement->outputs = parse_asm_arguments(true);
8605         if (token.type != ':') {
8606                 rem_anchor_token(':');
8607                 goto end_of_asm;
8608         }
8609         eat(':');
8610
8611         asm_statement->inputs = parse_asm_arguments(false);
8612         if (token.type != ':') {
8613                 rem_anchor_token(':');
8614                 goto end_of_asm;
8615         }
8616         rem_anchor_token(':');
8617         eat(':');
8618
8619         asm_statement->clobbers = parse_asm_clobbers();
8620
8621 end_of_asm:
8622         rem_anchor_token(')');
8623         expect(')');
8624         expect(';');
8625
8626         if (asm_statement->outputs == NULL) {
8627                 /* GCC: An 'asm' instruction without any output operands will be treated
8628                  * identically to a volatile 'asm' instruction. */
8629                 asm_statement->is_volatile = true;
8630         }
8631
8632         return statement;
8633 end_error:
8634         return create_invalid_statement();
8635 }
8636
8637 /**
8638  * Parse a case statement.
8639  */
8640 static statement_t *parse_case_statement(void)
8641 {
8642         eat(T_case);
8643
8644         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8645         source_position_t *const pos       = &statement->base.source_position;
8646
8647         *pos                             = token.source_position;
8648         expression_t *const expression   = parse_expression();
8649         statement->case_label.expression = expression;
8650         if (!is_constant_expression(expression)) {
8651                 /* This check does not prevent the error message in all cases of an
8652                  * prior error while parsing the expression.  At least it catches the
8653                  * common case of a mistyped enum entry. */
8654                 if (is_type_valid(expression->base.type)) {
8655                         errorf(pos, "case label does not reduce to an integer constant");
8656                 }
8657                 statement->case_label.is_bad = true;
8658         } else {
8659                 long const val = fold_constant(expression);
8660                 statement->case_label.first_case = val;
8661                 statement->case_label.last_case  = val;
8662         }
8663
8664         if (c_mode & _GNUC) {
8665                 if (token.type == T_DOTDOTDOT) {
8666                         next_token();
8667                         expression_t *const end_range   = parse_expression();
8668                         statement->case_label.end_range = end_range;
8669                         if (!is_constant_expression(end_range)) {
8670                                 /* This check does not prevent the error message in all cases of an
8671                                  * prior error while parsing the expression.  At least it catches the
8672                                  * common case of a mistyped enum entry. */
8673                                 if (is_type_valid(end_range->base.type)) {
8674                                         errorf(pos, "case range does not reduce to an integer constant");
8675                                 }
8676                                 statement->case_label.is_bad = true;
8677                         } else {
8678                                 long const val = fold_constant(end_range);
8679                                 statement->case_label.last_case = val;
8680
8681                                 if (val < statement->case_label.first_case) {
8682                                         statement->case_label.is_empty_range = true;
8683                                         warningf(pos, "empty range specified");
8684                                 }
8685                         }
8686                 }
8687         }
8688
8689         PUSH_PARENT(statement);
8690
8691         expect(':');
8692
8693         if (current_switch != NULL) {
8694                 if (! statement->case_label.is_bad) {
8695                         /* Check for duplicate case values */
8696                         case_label_statement_t *c = &statement->case_label;
8697                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8698                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8699                                         continue;
8700
8701                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
8702                                         continue;
8703
8704                                 errorf(pos, "duplicate case value (previously used %P)",
8705                                        &l->base.source_position);
8706                                 break;
8707                         }
8708                 }
8709                 /* link all cases into the switch statement */
8710                 if (current_switch->last_case == NULL) {
8711                         current_switch->first_case      = &statement->case_label;
8712                 } else {
8713                         current_switch->last_case->next = &statement->case_label;
8714                 }
8715                 current_switch->last_case = &statement->case_label;
8716         } else {
8717                 errorf(pos, "case label not within a switch statement");
8718         }
8719
8720         statement_t *const inner_stmt = parse_statement();
8721         statement->case_label.statement = inner_stmt;
8722         if (inner_stmt->kind == STATEMENT_DECLARATION) {
8723                 errorf(&inner_stmt->base.source_position, "declaration after case label");
8724         }
8725
8726         POP_PARENT;
8727         return statement;
8728 end_error:
8729         POP_PARENT;
8730         return create_invalid_statement();
8731 }
8732
8733 /**
8734  * Parse a default statement.
8735  */
8736 static statement_t *parse_default_statement(void)
8737 {
8738         eat(T_default);
8739
8740         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8741         statement->base.source_position = token.source_position;
8742
8743         PUSH_PARENT(statement);
8744
8745         expect(':');
8746         if (current_switch != NULL) {
8747                 const case_label_statement_t *def_label = current_switch->default_label;
8748                 if (def_label != NULL) {
8749                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8750                                &def_label->base.source_position);
8751                 } else {
8752                         current_switch->default_label = &statement->case_label;
8753
8754                         /* link all cases into the switch statement */
8755                         if (current_switch->last_case == NULL) {
8756                                 current_switch->first_case      = &statement->case_label;
8757                         } else {
8758                                 current_switch->last_case->next = &statement->case_label;
8759                         }
8760                         current_switch->last_case = &statement->case_label;
8761                 }
8762         } else {
8763                 errorf(&statement->base.source_position,
8764                         "'default' label not within a switch statement");
8765         }
8766
8767         statement_t *const inner_stmt = parse_statement();
8768         statement->case_label.statement = inner_stmt;
8769         if (inner_stmt->kind == STATEMENT_DECLARATION) {
8770                 errorf(&inner_stmt->base.source_position, "declaration after default label");
8771         }
8772
8773         POP_PARENT;
8774         return statement;
8775 end_error:
8776         POP_PARENT;
8777         return create_invalid_statement();
8778 }
8779
8780 /**
8781  * Parse a label statement.
8782  */
8783 static statement_t *parse_label_statement(void)
8784 {
8785         assert(token.type == T_IDENTIFIER);
8786         symbol_t *symbol = token.v.symbol;
8787         next_token();
8788
8789         declaration_t *label = get_label(symbol);
8790
8791         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8792         statement->base.source_position = token.source_position;
8793         statement->label.label          = label;
8794
8795         PUSH_PARENT(statement);
8796
8797         /* if statement is already set then the label is defined twice,
8798          * otherwise it was just mentioned in a goto/local label declaration so far */
8799         if (label->init.statement != NULL) {
8800                 errorf(HERE, "duplicate label '%Y' (declared %P)",
8801                        symbol, &label->source_position);
8802         } else {
8803                 label->source_position = token.source_position;
8804                 label->init.statement  = statement;
8805         }
8806
8807         eat(':');
8808
8809         if (token.type == '}') {
8810                 /* TODO only warn? */
8811                 if (false) {
8812                         warningf(HERE, "label at end of compound statement");
8813                         statement->label.statement = create_empty_statement();
8814                 } else {
8815                         errorf(HERE, "label at end of compound statement");
8816                         statement->label.statement = create_invalid_statement();
8817                 }
8818         } else if (token.type == ';') {
8819                 /* Eat an empty statement here, to avoid the warning about an empty
8820                  * statement after a label.  label:; is commonly used to have a label
8821                  * before a closing brace. */
8822                 statement->label.statement = create_empty_statement();
8823                 next_token();
8824         } else {
8825                 statement_t *const inner_stmt = parse_statement();
8826                 statement->label.statement = inner_stmt;
8827                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8828                         errorf(&inner_stmt->base.source_position, "declaration after label");
8829                 }
8830         }
8831
8832         /* remember the labels in a list for later checking */
8833         if (label_last == NULL) {
8834                 label_first = &statement->label;
8835         } else {
8836                 label_last->next = &statement->label;
8837         }
8838         label_last = &statement->label;
8839
8840         POP_PARENT;
8841         return statement;
8842 }
8843
8844 /**
8845  * Parse an if statement.
8846  */
8847 static statement_t *parse_if(void)
8848 {
8849         eat(T_if);
8850
8851         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
8852         statement->base.source_position = token.source_position;
8853
8854         PUSH_PARENT(statement);
8855
8856         expect('(');
8857         add_anchor_token(')');
8858         statement->ifs.condition = parse_expression();
8859         rem_anchor_token(')');
8860         expect(')');
8861
8862         add_anchor_token(T_else);
8863         statement->ifs.true_statement = parse_statement();
8864         rem_anchor_token(T_else);
8865
8866         if (token.type == T_else) {
8867                 next_token();
8868                 statement->ifs.false_statement = parse_statement();
8869         }
8870
8871         POP_PARENT;
8872         return statement;
8873 end_error:
8874         POP_PARENT;
8875         return create_invalid_statement();
8876 }
8877
8878 /**
8879  * Check that all enums are handled in a switch.
8880  *
8881  * @param statement  the switch statement to check
8882  */
8883 static void check_enum_cases(const switch_statement_t *statement) {
8884         const type_t *type = skip_typeref(statement->expression->base.type);
8885         if (! is_type_enum(type))
8886                 return;
8887         const enum_type_t *enumt = &type->enumt;
8888
8889         /* if we have a default, no warnings */
8890         if (statement->default_label != NULL)
8891                 return;
8892
8893         /* FIXME: calculation of value should be done while parsing */
8894         const declaration_t *declaration;
8895         long last_value = -1;
8896         for (declaration = enumt->declaration->next;
8897              declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8898                  declaration = declaration->next) {
8899                 const expression_t *expression = declaration->init.enum_value;
8900                 long                value      = expression != NULL ? fold_constant(expression) : last_value + 1;
8901                 bool                found      = false;
8902                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8903                         if (l->expression == NULL)
8904                                 continue;
8905                         if (l->first_case <= value && value <= l->last_case) {
8906                                 found = true;
8907                                 break;
8908                         }
8909                 }
8910                 if (! found) {
8911                         warningf(&statement->base.source_position,
8912                                 "enumeration value '%Y' not handled in switch", declaration->symbol);
8913                 }
8914                 last_value = value;
8915         }
8916 }
8917
8918 /**
8919  * Parse a switch statement.
8920  */
8921 static statement_t *parse_switch(void)
8922 {
8923         eat(T_switch);
8924
8925         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
8926         statement->base.source_position = token.source_position;
8927
8928         PUSH_PARENT(statement);
8929
8930         expect('(');
8931         add_anchor_token(')');
8932         expression_t *const expr = parse_expression();
8933         type_t       *      type = skip_typeref(expr->base.type);
8934         if (is_type_integer(type)) {
8935                 type = promote_integer(type);
8936                 if (warning.traditional) {
8937                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8938                                 warningf(&expr->base.source_position,
8939                                         "'%T' switch expression not converted to '%T' in ISO C",
8940                                         type, type_int);
8941                         }
8942                 }
8943         } else if (is_type_valid(type)) {
8944                 errorf(&expr->base.source_position,
8945                        "switch quantity is not an integer, but '%T'", type);
8946                 type = type_error_type;
8947         }
8948         statement->switchs.expression = create_implicit_cast(expr, type);
8949         expect(')');
8950         rem_anchor_token(')');
8951
8952         switch_statement_t *rem = current_switch;
8953         current_switch          = &statement->switchs;
8954         statement->switchs.body = parse_statement();
8955         current_switch          = rem;
8956
8957         if (warning.switch_default &&
8958             statement->switchs.default_label == NULL) {
8959                 warningf(&statement->base.source_position, "switch has no default case");
8960         }
8961         if (warning.switch_enum)
8962                 check_enum_cases(&statement->switchs);
8963
8964         POP_PARENT;
8965         return statement;
8966 end_error:
8967         POP_PARENT;
8968         return create_invalid_statement();
8969 }
8970
8971 static statement_t *parse_loop_body(statement_t *const loop)
8972 {
8973         statement_t *const rem = current_loop;
8974         current_loop = loop;
8975
8976         statement_t *const body = parse_statement();
8977
8978         current_loop = rem;
8979         return body;
8980 }
8981
8982 /**
8983  * Parse a while statement.
8984  */
8985 static statement_t *parse_while(void)
8986 {
8987         eat(T_while);
8988
8989         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
8990         statement->base.source_position = token.source_position;
8991
8992         PUSH_PARENT(statement);
8993
8994         expect('(');
8995         add_anchor_token(')');
8996         statement->whiles.condition = parse_expression();
8997         rem_anchor_token(')');
8998         expect(')');
8999
9000         statement->whiles.body = parse_loop_body(statement);
9001
9002         POP_PARENT;
9003         return statement;
9004 end_error:
9005         POP_PARENT;
9006         return create_invalid_statement();
9007 }
9008
9009 /**
9010  * Parse a do statement.
9011  */
9012 static statement_t *parse_do(void)
9013 {
9014         eat(T_do);
9015
9016         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9017         statement->base.source_position = token.source_position;
9018
9019         PUSH_PARENT(statement)
9020
9021         add_anchor_token(T_while);
9022         statement->do_while.body = parse_loop_body(statement);
9023         rem_anchor_token(T_while);
9024
9025         expect(T_while);
9026         expect('(');
9027         add_anchor_token(')');
9028         statement->do_while.condition = parse_expression();
9029         rem_anchor_token(')');
9030         expect(')');
9031         expect(';');
9032
9033         POP_PARENT;
9034         return statement;
9035 end_error:
9036         POP_PARENT;
9037         return create_invalid_statement();
9038 }
9039
9040 /**
9041  * Parse a for statement.
9042  */
9043 static statement_t *parse_for(void)
9044 {
9045         eat(T_for);
9046
9047         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
9048         statement->base.source_position = token.source_position;
9049
9050         PUSH_PARENT(statement);
9051
9052         int      top        = environment_top();
9053         scope_t *last_scope = scope;
9054         set_scope(&statement->fors.scope);
9055
9056         expect('(');
9057         add_anchor_token(')');
9058
9059         if (token.type != ';') {
9060                 if (is_declaration_specifier(&token, false)) {
9061                         parse_declaration(record_declaration);
9062                 } else {
9063                         add_anchor_token(';');
9064                         expression_t *const init = parse_expression();
9065                         statement->fors.initialisation = init;
9066                         if (warning.unused_value && !expression_has_effect(init)) {
9067                                 warningf(&init->base.source_position,
9068                                          "initialisation of 'for'-statement has no effect");
9069                         }
9070                         rem_anchor_token(';');
9071                         expect(';');
9072                 }
9073         } else {
9074                 expect(';');
9075         }
9076
9077         if (token.type != ';') {
9078                 add_anchor_token(';');
9079                 statement->fors.condition = parse_expression();
9080                 rem_anchor_token(';');
9081         }
9082         expect(';');
9083         if (token.type != ')') {
9084                 expression_t *const step = parse_expression();
9085                 statement->fors.step = step;
9086                 if (warning.unused_value && !expression_has_effect(step)) {
9087                         warningf(&step->base.source_position,
9088                                  "step of 'for'-statement has no effect");
9089                 }
9090         }
9091         rem_anchor_token(')');
9092         expect(')');
9093         statement->fors.body = parse_loop_body(statement);
9094
9095         assert(scope == &statement->fors.scope);
9096         set_scope(last_scope);
9097         environment_pop_to(top);
9098
9099         POP_PARENT;
9100         return statement;
9101
9102 end_error:
9103         POP_PARENT;
9104         rem_anchor_token(')');
9105         assert(scope == &statement->fors.scope);
9106         set_scope(last_scope);
9107         environment_pop_to(top);
9108
9109         return create_invalid_statement();
9110 }
9111
9112 /**
9113  * Parse a goto statement.
9114  */
9115 static statement_t *parse_goto(void)
9116 {
9117         source_position_t source_position = token.source_position;
9118         eat(T_goto);
9119
9120         statement_t *statement;
9121         if (c_mode & _GNUC && token.type == '*') {
9122                 next_token();
9123                 expression_t *expression = parse_expression();
9124
9125                 /* Argh: although documentation say the expression must be of type void *,
9126                  * gcc excepts anything that can be casted into void * without error */
9127                 type_t *type = expression->base.type;
9128
9129                 if (type != type_error_type) {
9130                         if (!is_type_pointer(type) && !is_type_integer(type)) {
9131                                 errorf(&source_position, "cannot convert to a pointer type");
9132                         } else if (type != type_void_ptr) {
9133                                 warningf(&source_position,
9134                                         "type of computed goto expression should be 'void*' not '%T'", type);
9135                         }
9136                         expression = create_implicit_cast(expression, type_void_ptr);
9137                 }
9138
9139                 statement                       = allocate_statement_zero(STATEMENT_GOTO);
9140                 statement->base.source_position = source_position;
9141                 statement->gotos.expression     = expression;
9142         } else {
9143                 if (token.type != T_IDENTIFIER) {
9144                         if (c_mode & _GNUC)
9145                                 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9146                         else
9147                                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9148                         eat_until_anchor();
9149                         goto end_error;
9150                 }
9151                 symbol_t *symbol = token.v.symbol;
9152                 next_token();
9153
9154                 statement                       = allocate_statement_zero(STATEMENT_GOTO);
9155                 statement->base.source_position = source_position;
9156                 statement->gotos.label          = get_label(symbol);
9157         }
9158
9159         /* remember the goto's in a list for later checking */
9160         if (goto_last == NULL) {
9161                 goto_first = &statement->gotos;
9162         } else {
9163                 goto_last->next = &statement->gotos;
9164         }
9165         goto_last = &statement->gotos;
9166
9167         expect(';');
9168
9169         return statement;
9170 end_error:
9171         return create_invalid_statement();
9172 }
9173
9174 /**
9175  * Parse a continue statement.
9176  */
9177 static statement_t *parse_continue(void)
9178 {
9179         if (current_loop == NULL) {
9180                 errorf(HERE, "continue statement not within loop");
9181         }
9182
9183         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9184         statement->base.source_position = token.source_position;
9185
9186         eat(T_continue);
9187         expect(';');
9188
9189 end_error:
9190         return statement;
9191 }
9192
9193 /**
9194  * Parse a break statement.
9195  */
9196 static statement_t *parse_break(void)
9197 {
9198         if (current_switch == NULL && current_loop == NULL) {
9199                 errorf(HERE, "break statement not within loop or switch");
9200         }
9201
9202         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9203         statement->base.source_position = token.source_position;
9204
9205         eat(T_break);
9206         expect(';');
9207
9208 end_error:
9209         return statement;
9210 }
9211
9212 /**
9213  * Parse a __leave statement.
9214  */
9215 static statement_t *parse_leave_statement(void)
9216 {
9217         if (current_try == NULL) {
9218                 errorf(HERE, "__leave statement not within __try");
9219         }
9220
9221         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9222         statement->base.source_position = token.source_position;
9223
9224         eat(T___leave);
9225         expect(';');
9226
9227 end_error:
9228         return statement;
9229 }
9230
9231 /**
9232  * Check if a given declaration represents a local variable.
9233  */
9234 static bool is_local_var_declaration(const declaration_t *declaration)
9235 {
9236         switch ((storage_class_tag_t) declaration->storage_class) {
9237         case STORAGE_CLASS_AUTO:
9238         case STORAGE_CLASS_REGISTER: {
9239                 const type_t *type = skip_typeref(declaration->type);
9240                 if (is_type_function(type)) {
9241                         return false;
9242                 } else {
9243                         return true;
9244                 }
9245         }
9246         default:
9247                 return false;
9248         }
9249 }
9250
9251 /**
9252  * Check if a given declaration represents a variable.
9253  */
9254 static bool is_var_declaration(const declaration_t *declaration)
9255 {
9256         if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9257                 return false;
9258
9259         const type_t *type = skip_typeref(declaration->type);
9260         return !is_type_function(type);
9261 }
9262
9263 /**
9264  * Check if a given expression represents a local variable.
9265  */
9266 static bool is_local_variable(const expression_t *expression)
9267 {
9268         if (expression->base.kind != EXPR_REFERENCE) {
9269                 return false;
9270         }
9271         const declaration_t *declaration = expression->reference.declaration;
9272         return is_local_var_declaration(declaration);
9273 }
9274
9275 /**
9276  * Check if a given expression represents a local variable and
9277  * return its declaration then, else return NULL.
9278  */
9279 declaration_t *expr_is_variable(const expression_t *expression)
9280 {
9281         if (expression->base.kind != EXPR_REFERENCE) {
9282                 return NULL;
9283         }
9284         declaration_t *declaration = expression->reference.declaration;
9285         if (is_var_declaration(declaration))
9286                 return declaration;
9287         return NULL;
9288 }
9289
9290 /**
9291  * Parse a return statement.
9292  */
9293 static statement_t *parse_return(void)
9294 {
9295         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
9296         statement->base.source_position = token.source_position;
9297
9298         eat(T_return);
9299
9300         expression_t *return_value = NULL;
9301         if (token.type != ';') {
9302                 return_value = parse_expression();
9303         }
9304
9305         const type_t *const func_type = current_function->type;
9306         assert(is_type_function(func_type));
9307         type_t *const return_type = skip_typeref(func_type->function.return_type);
9308
9309         if (return_value != NULL) {
9310                 type_t *return_value_type = skip_typeref(return_value->base.type);
9311
9312                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9313                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9314                         warningf(&statement->base.source_position,
9315                                  "'return' with a value, in function returning void");
9316                         return_value = NULL;
9317                 } else {
9318                         assign_error_t error = semantic_assign(return_type, return_value);
9319                         report_assign_error(error, return_type, return_value, "'return'",
9320                                             &statement->base.source_position);
9321                         return_value = create_implicit_cast(return_value, return_type);
9322                 }
9323                 /* check for returning address of a local var */
9324                 if (return_value != NULL &&
9325                                 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9326                         const expression_t *expression = return_value->unary.value;
9327                         if (is_local_variable(expression)) {
9328                                 warningf(&statement->base.source_position,
9329                                          "function returns address of local variable");
9330                         }
9331                 }
9332         } else {
9333                 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9334                         warningf(&statement->base.source_position,
9335                                  "'return' without value, in function returning non-void");
9336                 }
9337         }
9338         statement->returns.value = return_value;
9339
9340         expect(';');
9341
9342 end_error:
9343         return statement;
9344 }
9345
9346 /**
9347  * Parse a declaration statement.
9348  */
9349 static statement_t *parse_declaration_statement(void)
9350 {
9351         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9352
9353         statement->base.source_position = token.source_position;
9354
9355         declaration_t *before = last_declaration;
9356         parse_declaration(record_declaration);
9357
9358         if (before == NULL) {
9359                 statement->declaration.declarations_begin = scope->declarations;
9360         } else {
9361                 statement->declaration.declarations_begin = before->next;
9362         }
9363         statement->declaration.declarations_end = last_declaration;
9364
9365         return statement;
9366 }
9367
9368 /**
9369  * Parse an expression statement, ie. expr ';'.
9370  */
9371 static statement_t *parse_expression_statement(void)
9372 {
9373         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9374
9375         statement->base.source_position  = token.source_position;
9376         expression_t *const expr         = parse_expression();
9377         statement->expression.expression = expr;
9378
9379         expect(';');
9380
9381 end_error:
9382         return statement;
9383 }
9384
9385 /**
9386  * Parse a microsoft __try { } __finally { } or
9387  * __try{ } __except() { }
9388  */
9389 static statement_t *parse_ms_try_statment(void)
9390 {
9391         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9392         statement->base.source_position  = token.source_position;
9393         eat(T___try);
9394
9395         PUSH_PARENT(statement);
9396
9397         ms_try_statement_t *rem = current_try;
9398         current_try = &statement->ms_try;
9399         statement->ms_try.try_statement = parse_compound_statement(false);
9400         current_try = rem;
9401
9402         POP_PARENT;
9403
9404         if (token.type == T___except) {
9405                 eat(T___except);
9406                 expect('(');
9407                 add_anchor_token(')');
9408                 expression_t *const expr = parse_expression();
9409                 type_t       *      type = skip_typeref(expr->base.type);
9410                 if (is_type_integer(type)) {
9411                         type = promote_integer(type);
9412                 } else if (is_type_valid(type)) {
9413                         errorf(&expr->base.source_position,
9414                                "__expect expression is not an integer, but '%T'", type);
9415                         type = type_error_type;
9416                 }
9417                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9418                 rem_anchor_token(')');
9419                 expect(')');
9420                 statement->ms_try.final_statement = parse_compound_statement(false);
9421         } else if (token.type == T__finally) {
9422                 eat(T___finally);
9423                 statement->ms_try.final_statement = parse_compound_statement(false);
9424         } else {
9425                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9426                 return create_invalid_statement();
9427         }
9428         return statement;
9429 end_error:
9430         return create_invalid_statement();
9431 }
9432
9433 static statement_t *parse_empty_statement(void)
9434 {
9435         if (warning.empty_statement) {
9436                 warningf(HERE, "statement is empty");
9437         }
9438         statement_t *const statement = create_empty_statement();
9439         eat(';');
9440         return statement;
9441 }
9442
9443 static statement_t *parse_local_label_declaration(void) {
9444         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9445         statement->base.source_position = token.source_position;
9446
9447         eat(T___label__);
9448
9449         declaration_t *begin = NULL, *end = NULL;
9450
9451         while (true) {
9452                 if (token.type != T_IDENTIFIER) {
9453                         parse_error_expected("while parsing local label declaration",
9454                                 T_IDENTIFIER, NULL);
9455                         goto end_error;
9456                 }
9457                 symbol_t      *symbol      = token.v.symbol;
9458                 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9459                 if (declaration != NULL) {
9460                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9461                                 symbol, &declaration->source_position);
9462                 } else {
9463                         declaration = allocate_declaration_zero();
9464                         declaration->namespc         = NAMESPACE_LOCAL_LABEL;
9465                         declaration->source_position = token.source_position;
9466                         declaration->symbol          = symbol;
9467                         declaration->parent_scope    = scope;
9468                         declaration->init.statement  = NULL;
9469
9470                         if (end != NULL)
9471                                 end->next = declaration;
9472                         end = declaration;
9473                         if (begin == NULL)
9474                                 begin = declaration;
9475
9476                         local_label_push(declaration);
9477                 }
9478                 next_token();
9479
9480                 if (token.type != ',')
9481                         break;
9482                 next_token();
9483         }
9484         eat(';');
9485 end_error:
9486         statement->declaration.declarations_begin = begin;
9487         statement->declaration.declarations_end   = end;
9488         return statement;
9489 }
9490
9491 /**
9492  * Parse a statement.
9493  * There's also parse_statement() which additionally checks for
9494  * "statement has no effect" warnings
9495  */
9496 static statement_t *intern_parse_statement(void)
9497 {
9498         statement_t *statement = NULL;
9499
9500         /* declaration or statement */
9501         add_anchor_token(';');
9502         switch (token.type) {
9503         case T_IDENTIFIER: {
9504                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9505                 if (la1_type == ':') {
9506                         statement = parse_label_statement();
9507                 } else if (is_typedef_symbol(token.v.symbol)) {
9508                         statement = parse_declaration_statement();
9509                 } else switch (la1_type) {
9510                         case '*':
9511                                 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9512                                         goto expression_statment;
9513                                 /* FALLTHROUGH */
9514
9515                         DECLARATION_START
9516                         case T_IDENTIFIER:
9517                                 statement = parse_declaration_statement();
9518                                 break;
9519
9520                         default:
9521 expression_statment:
9522                                 statement = parse_expression_statement();
9523                                 break;
9524                 }
9525                 break;
9526         }
9527
9528         case T___extension__:
9529                 /* This can be a prefix to a declaration or an expression statement.
9530                  * We simply eat it now and parse the rest with tail recursion. */
9531                 do {
9532                         next_token();
9533                 } while (token.type == T___extension__);
9534                 statement = parse_statement();
9535                 break;
9536
9537         DECLARATION_START
9538                 statement = parse_declaration_statement();
9539                 break;
9540
9541         case T___label__:
9542                 statement = parse_local_label_declaration();
9543                 break;
9544
9545         case ';':        statement = parse_empty_statement();         break;
9546         case '{':        statement = parse_compound_statement(false); break;
9547         case T___leave:  statement = parse_leave_statement();         break;
9548         case T___try:    statement = parse_ms_try_statment();         break;
9549         case T_asm:      statement = parse_asm_statement();           break;
9550         case T_break:    statement = parse_break();                   break;
9551         case T_case:     statement = parse_case_statement();          break;
9552         case T_continue: statement = parse_continue();                break;
9553         case T_default:  statement = parse_default_statement();       break;
9554         case T_do:       statement = parse_do();                      break;
9555         case T_for:      statement = parse_for();                     break;
9556         case T_goto:     statement = parse_goto();                    break;
9557         case T_if:       statement = parse_if ();                     break;
9558         case T_return:   statement = parse_return();                  break;
9559         case T_switch:   statement = parse_switch();                  break;
9560         case T_while:    statement = parse_while();                   break;
9561
9562         case '!':
9563         case '&':
9564         case '(':
9565         case '*':
9566         case '+':
9567         case '-':
9568         case '~':
9569         case T_ANDAND:
9570         case T_CHARACTER_CONSTANT:
9571         case T_FLOATINGPOINT:
9572         case T_INTEGER:
9573         case T_MINUSMINUS:
9574         case T_PLUSPLUS:
9575         case T_STRING_LITERAL:
9576         case T_WIDE_CHARACTER_CONSTANT:
9577         case T_WIDE_STRING_LITERAL:
9578         case T___FUNCDNAME__:
9579         case T___FUNCSIG__:
9580         case T___FUNCTION__:
9581         case T___PRETTY_FUNCTION__:
9582         case T___builtin_alloca:
9583         case T___builtin_classify_type:
9584         case T___builtin_constant_p:
9585         case T___builtin_expect:
9586         case T___builtin_huge_val:
9587         case T___builtin_isgreater:
9588         case T___builtin_isgreaterequal:
9589         case T___builtin_isless:
9590         case T___builtin_islessequal:
9591         case T___builtin_islessgreater:
9592         case T___builtin_isunordered:
9593         case T___builtin_nan:
9594         case T___builtin_nand:
9595         case T___builtin_nanf:
9596         case T___builtin_offsetof:
9597         case T___builtin_prefetch:
9598         case T___builtin_va_arg:
9599         case T___builtin_va_end:
9600         case T___builtin_va_start:
9601         case T___func__:
9602         case T___noop:
9603         case T__assume:
9604                 statement = parse_expression_statement();
9605                 break;
9606
9607         default:
9608                 errorf(HERE, "unexpected token %K while parsing statement", &token);
9609                 statement = create_invalid_statement();
9610                 if (!at_anchor())
9611                         next_token();
9612                 break;
9613         }
9614         rem_anchor_token(';');
9615
9616         assert(statement != NULL
9617                         && statement->base.source_position.input_name != NULL);
9618
9619         return statement;
9620 }
9621
9622 /**
9623  * parse a statement and emits "statement has no effect" warning if needed
9624  * (This is really a wrapper around intern_parse_statement with check for 1
9625  *  single warning. It is needed, because for statement expressions we have
9626  *  to avoid the warning on the last statement)
9627  */
9628 static statement_t *parse_statement(void)
9629 {
9630         statement_t *statement = intern_parse_statement();
9631
9632         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9633                 expression_t *expression = statement->expression.expression;
9634                 if (!expression_has_effect(expression)) {
9635                         warningf(&expression->base.source_position,
9636                                         "statement has no effect");
9637                 }
9638         }
9639
9640         return statement;
9641 }
9642
9643 /**
9644  * Parse a compound statement.
9645  */
9646 static statement_t *parse_compound_statement(bool inside_expression_statement)
9647 {
9648         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9649         statement->base.source_position = token.source_position;
9650
9651         PUSH_PARENT(statement);
9652
9653         eat('{');
9654         add_anchor_token('}');
9655
9656         int      top        = environment_top();
9657         int      top_local  = local_label_top();
9658         scope_t *last_scope = scope;
9659         set_scope(&statement->compound.scope);
9660
9661         statement_t **anchor            = &statement->compound.statements;
9662         bool          only_decls_so_far = true;
9663         while (token.type != '}' && token.type != T_EOF) {
9664                 statement_t *sub_statement = intern_parse_statement();
9665                 if (is_invalid_statement(sub_statement)) {
9666                         /* an error occurred. if we are at an anchor, return */
9667                         if (at_anchor())
9668                                 goto end_error;
9669                         continue;
9670                 }
9671
9672                 if (warning.declaration_after_statement) {
9673                         if (sub_statement->kind != STATEMENT_DECLARATION) {
9674                                 only_decls_so_far = false;
9675                         } else if (!only_decls_so_far) {
9676                                 warningf(&sub_statement->base.source_position,
9677                                          "ISO C90 forbids mixed declarations and code");
9678                         }
9679                 }
9680
9681                 *anchor = sub_statement;
9682
9683                 while (sub_statement->base.next != NULL)
9684                         sub_statement = sub_statement->base.next;
9685
9686                 anchor = &sub_statement->base.next;
9687         }
9688
9689         if (token.type == '}') {
9690                 next_token();
9691         } else {
9692                 errorf(&statement->base.source_position,
9693                        "end of file while looking for closing '}'");
9694         }
9695
9696         /* look over all statements again to produce no effect warnings */
9697         if (warning.unused_value) {
9698                 statement_t *sub_statement = statement->compound.statements;
9699                 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9700                         if (sub_statement->kind != STATEMENT_EXPRESSION)
9701                                 continue;
9702                         /* don't emit a warning for the last expression in an expression
9703                          * statement as it has always an effect */
9704                         if (inside_expression_statement && sub_statement->base.next == NULL)
9705                                 continue;
9706
9707                         expression_t *expression = sub_statement->expression.expression;
9708                         if (!expression_has_effect(expression)) {
9709                                 warningf(&expression->base.source_position,
9710                                          "statement has no effect");
9711                         }
9712                 }
9713         }
9714
9715 end_error:
9716         rem_anchor_token('}');
9717         assert(scope == &statement->compound.scope);
9718         set_scope(last_scope);
9719         environment_pop_to(top);
9720         local_label_pop_to(top_local);
9721
9722         POP_PARENT;
9723         return statement;
9724 }
9725
9726 /**
9727  * Initialize builtin types.
9728  */
9729 static void initialize_builtin_types(void)
9730 {
9731         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
9732         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
9733         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
9734         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
9735         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
9736         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9737         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    opt_short_wchar_t ? type_unsigned_short : type_int);
9738         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
9739
9740         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
9741         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9742         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
9743         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
9744
9745         /* const version of wchar_t */
9746         type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9747         type_const_wchar_t->typedeft.declaration  = type_wchar_t->typedeft.declaration;
9748         type_const_wchar_t->base.qualifiers      |= TYPE_QUALIFIER_CONST;
9749
9750         type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9751 }
9752
9753 /**
9754  * Check for unused global static functions and variables
9755  */
9756 static void check_unused_globals(void)
9757 {
9758         if (!warning.unused_function && !warning.unused_variable)
9759                 return;
9760
9761         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9762                 if (decl->used                  ||
9763                     decl->modifiers & DM_UNUSED ||
9764                     decl->modifiers & DM_USED   ||
9765                     decl->storage_class != STORAGE_CLASS_STATIC)
9766                         continue;
9767
9768                 type_t *const type = decl->type;
9769                 const char *s;
9770                 if (is_type_function(skip_typeref(type))) {
9771                         if (!warning.unused_function || decl->is_inline)
9772                                 continue;
9773
9774                         s = (decl->init.statement != NULL ? "defined" : "declared");
9775                 } else {
9776                         if (!warning.unused_variable)
9777                                 continue;
9778
9779                         s = "defined";
9780                 }
9781
9782                 warningf(&decl->source_position, "'%#T' %s but not used",
9783                         type, decl->symbol, s);
9784         }
9785 }
9786
9787 static void parse_global_asm(void)
9788 {
9789         eat(T_asm);
9790         expect('(');
9791
9792         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
9793         statement->base.source_position = token.source_position;
9794         statement->asms.asm_text        = parse_string_literals();
9795         statement->base.next            = unit->global_asm;
9796         unit->global_asm                = statement;
9797
9798         expect(')');
9799         expect(';');
9800
9801 end_error:;
9802 }
9803
9804 /**
9805  * Parse a translation unit.
9806  */
9807 static void parse_translation_unit(void)
9808 {
9809         for (;;) {
9810 #ifndef NDEBUG
9811                 bool anchor_leak = false;
9812                 for (token_type_t i = 0; i != T_LAST_TOKEN; ++i) {
9813                         unsigned char count = token_anchor_set[i];
9814                         if (count != 0) {
9815                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9816                                 anchor_leak = true;
9817                         }
9818                 }
9819                 if (anchor_leak)
9820                         abort();
9821 #endif
9822
9823                 switch (token.type) {
9824                         DECLARATION_START
9825                         case T_IDENTIFIER:
9826                         case T___extension__:
9827                                 parse_external_declaration();
9828                                 break;
9829
9830                         case T_asm:
9831                                 parse_global_asm();
9832                                 break;
9833
9834                         case T_EOF:
9835                                 return;
9836
9837                         case ';':
9838                                 /* TODO error in strict mode */
9839                                 warningf(HERE, "stray ';' outside of function");
9840                                 next_token();
9841                                 break;
9842
9843                         default:
9844                                 errorf(HERE, "stray %K outside of function", &token);
9845                                 if (token.type == '(' || token.type == '{' || token.type == '[')
9846                                         eat_until_matching_token(token.type);
9847                                 next_token();
9848                                 break;
9849                 }
9850         }
9851 }
9852
9853 /**
9854  * Parse the input.
9855  *
9856  * @return  the translation unit or NULL if errors occurred.
9857  */
9858 void start_parsing(void)
9859 {
9860         environment_stack = NEW_ARR_F(stack_entry_t, 0);
9861         label_stack       = NEW_ARR_F(stack_entry_t, 0);
9862         local_label_stack = NEW_ARR_F(stack_entry_t, 0);
9863         diagnostic_count  = 0;
9864         error_count       = 0;
9865         warning_count     = 0;
9866
9867         type_set_output(stderr);
9868         ast_set_output(stderr);
9869
9870         assert(unit == NULL);
9871         unit = allocate_ast_zero(sizeof(unit[0]));
9872
9873         assert(global_scope == NULL);
9874         global_scope = &unit->scope;
9875
9876         assert(scope == NULL);
9877         set_scope(&unit->scope);
9878
9879         initialize_builtin_types();
9880 }
9881
9882 translation_unit_t *finish_parsing(void)
9883 {
9884         assert(scope == &unit->scope);
9885         scope          = NULL;
9886         last_declaration = NULL;
9887
9888         assert(global_scope == &unit->scope);
9889         check_unused_globals();
9890         global_scope = NULL;
9891
9892         DEL_ARR_F(environment_stack);
9893         DEL_ARR_F(label_stack);
9894         DEL_ARR_F(local_label_stack);
9895
9896         translation_unit_t *result = unit;
9897         unit = NULL;
9898         return result;
9899 }
9900
9901 void parse(void)
9902 {
9903         lookahead_bufpos = 0;
9904         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9905                 next_token();
9906         }
9907         parse_translation_unit();
9908 }
9909
9910 /**
9911  * Initialize the parser.
9912  */
9913 void init_parser(void)
9914 {
9915         sym_anonymous = symbol_table_insert("<anonymous>");
9916
9917         if (c_mode & _MS) {
9918                 /* add predefined symbols for extended-decl-modifier */
9919                 sym_align      = symbol_table_insert("align");
9920                 sym_allocate   = symbol_table_insert("allocate");
9921                 sym_dllimport  = symbol_table_insert("dllimport");
9922                 sym_dllexport  = symbol_table_insert("dllexport");
9923                 sym_naked      = symbol_table_insert("naked");
9924                 sym_noinline   = symbol_table_insert("noinline");
9925                 sym_noreturn   = symbol_table_insert("noreturn");
9926                 sym_nothrow    = symbol_table_insert("nothrow");
9927                 sym_novtable   = symbol_table_insert("novtable");
9928                 sym_property   = symbol_table_insert("property");
9929                 sym_get        = symbol_table_insert("get");
9930                 sym_put        = symbol_table_insert("put");
9931                 sym_selectany  = symbol_table_insert("selectany");
9932                 sym_thread     = symbol_table_insert("thread");
9933                 sym_uuid       = symbol_table_insert("uuid");
9934                 sym_deprecated = symbol_table_insert("deprecated");
9935                 sym_restrict   = symbol_table_insert("restrict");
9936                 sym_noalias    = symbol_table_insert("noalias");
9937         }
9938         memset(token_anchor_set, 0, sizeof(token_anchor_set));
9939
9940         init_expression_parsers();
9941         obstack_init(&temp_obst);
9942
9943         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9944         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9945 }
9946
9947 /**
9948  * Terminate the parser.
9949  */
9950 void exit_parser(void)
9951 {
9952         obstack_free(&temp_obst, NULL);
9953 }