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