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