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