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