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