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