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