Avoid unnecessary casts.
[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         entity_t    *entity     = 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 = get_tag(symbol, kind);
2433                 if (entity != NULL) {
2434                         if (entity->base.parent_scope != current_scope &&
2435                             (token.type == '{' || token.type == ';')) {
2436                                 /* we're in an inner scope and have a definition. Shadow
2437                                  * existing definition in outer scope */
2438                                 entity = NULL;
2439                         } else if (entity->compound.complete && token.type == '{') {
2440                                 assert(symbol != NULL);
2441                                 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2442                                        is_struct ? "struct" : "union", symbol,
2443                                        &entity->base.source_position);
2444                                 /* clear members in the hope to avoid further errors */
2445                                 entity->compound.members.entities = NULL;
2446                         }
2447                 }
2448         } else if (token.type != '{') {
2449                 if (is_struct) {
2450                         parse_error_expected("while parsing struct type specifier",
2451                                              T_IDENTIFIER, '{', NULL);
2452                 } else {
2453                         parse_error_expected("while parsing union type specifier",
2454                                              T_IDENTIFIER, '{', NULL);
2455                 }
2456
2457                 return NULL;
2458         }
2459
2460         if (entity == NULL) {
2461                 entity = allocate_entity_zero(kind);
2462
2463                 entity->compound.alignment   = 1;
2464                 entity->base.namespc         = NAMESPACE_TAG;
2465                 entity->base.source_position = token.source_position;
2466                 entity->base.symbol          = symbol;
2467                 entity->base.parent_scope    = current_scope;
2468                 if (symbol != NULL) {
2469                         environment_push(entity);
2470                 }
2471                 append_entity(current_scope, entity);
2472         }
2473
2474         if (token.type == '{') {
2475                 parse_compound_type_entries(&entity->compound);
2476
2477                 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2478                 if (symbol == NULL) {
2479                         assert(anonymous_entity == NULL);
2480                         anonymous_entity = entity;
2481                 }
2482         }
2483
2484         if (attributes != NULL) {
2485                 handle_entity_attributes(attributes, entity);
2486         }
2487
2488         return &entity->compound;
2489 }
2490
2491 static void parse_enum_entries(type_t *const enum_type)
2492 {
2493         eat('{');
2494
2495         if (token.type == '}') {
2496                 errorf(HERE, "empty enum not allowed");
2497                 next_token();
2498                 return;
2499         }
2500
2501         add_anchor_token('}');
2502         do {
2503                 if (token.type != T_IDENTIFIER) {
2504                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2505                         eat_block();
2506                         rem_anchor_token('}');
2507                         return;
2508                 }
2509
2510                 entity_t *entity             = allocate_entity_zero(ENTITY_ENUM_VALUE);
2511                 entity->enum_value.enum_type = enum_type;
2512                 entity->base.namespc         = NAMESPACE_NORMAL;
2513                 entity->base.symbol          = token.symbol;
2514                 entity->base.source_position = token.source_position;
2515                 next_token();
2516
2517                 if (next_if('=')) {
2518                         expression_t *value = parse_constant_expression();
2519
2520                         value = create_implicit_cast(value, enum_type);
2521                         entity->enum_value.value = value;
2522
2523                         /* TODO semantic */
2524                 }
2525
2526                 record_entity(entity, false);
2527         } while (next_if(',') && token.type != '}');
2528         rem_anchor_token('}');
2529
2530         expect('}', end_error);
2531
2532 end_error:
2533         ;
2534 }
2535
2536 static type_t *parse_enum_specifier(void)
2537 {
2538         entity_t *entity;
2539         symbol_t *symbol;
2540
2541         eat(T_enum);
2542         switch (token.type) {
2543                 case T_IDENTIFIER:
2544                         symbol = token.symbol;
2545                         next_token();
2546
2547                         entity = get_tag(symbol, ENTITY_ENUM);
2548                         if (entity != NULL) {
2549                                 if (entity->base.parent_scope != current_scope &&
2550                                                 (token.type == '{' || token.type == ';')) {
2551                                         /* we're in an inner scope and have a definition. Shadow
2552                                          * existing definition in outer scope */
2553                                         entity = NULL;
2554                                 } else if (entity->enume.complete && token.type == '{') {
2555                                         errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2556                                                         symbol, &entity->base.source_position);
2557                                 }
2558                         }
2559                         break;
2560
2561                 case '{':
2562                         entity = NULL;
2563                         symbol = NULL;
2564                         break;
2565
2566                 default:
2567                         parse_error_expected("while parsing enum type specifier",
2568                                         T_IDENTIFIER, '{', NULL);
2569                         return NULL;
2570         }
2571
2572         if (entity == NULL) {
2573                 entity                       = allocate_entity_zero(ENTITY_ENUM);
2574                 entity->base.namespc         = NAMESPACE_TAG;
2575                 entity->base.source_position = token.source_position;
2576                 entity->base.symbol          = symbol;
2577                 entity->base.parent_scope    = current_scope;
2578         }
2579
2580         type_t *const type = allocate_type_zero(TYPE_ENUM);
2581         type->enumt.enume  = &entity->enume;
2582         type->enumt.akind  = ATOMIC_TYPE_INT;
2583
2584         if (token.type == '{') {
2585                 if (symbol != NULL) {
2586                         environment_push(entity);
2587                 }
2588                 append_entity(current_scope, entity);
2589                 entity->enume.complete = true;
2590
2591                 parse_enum_entries(type);
2592                 parse_attributes(NULL);
2593
2594                 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2595                 if (symbol == NULL) {
2596                         assert(anonymous_entity == NULL);
2597                         anonymous_entity = entity;
2598                 }
2599         } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2600                 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2601                        symbol);
2602         }
2603
2604         return type;
2605 }
2606
2607 /**
2608  * if a symbol is a typedef to another type, return true
2609  */
2610 static bool is_typedef_symbol(symbol_t *symbol)
2611 {
2612         const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2613         return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2614 }
2615
2616 static type_t *parse_typeof(void)
2617 {
2618         eat(T___typeof__);
2619
2620         type_t *type;
2621
2622         expect('(', end_error);
2623         add_anchor_token(')');
2624
2625         expression_t *expression  = NULL;
2626
2627         bool old_type_prop     = in_type_prop;
2628         bool old_gcc_extension = in_gcc_extension;
2629         in_type_prop           = true;
2630
2631         while (next_if(T___extension__)) {
2632                 /* This can be a prefix to a typename or an expression. */
2633                 in_gcc_extension = true;
2634         }
2635         switch (token.type) {
2636         case T_IDENTIFIER:
2637                 if (is_typedef_symbol(token.symbol)) {
2638         TYPENAME_START
2639                         type = parse_typename();
2640                 } else {
2641         default:
2642                         expression = parse_expression();
2643                         type       = revert_automatic_type_conversion(expression);
2644                 }
2645                 break;
2646         }
2647         in_type_prop     = old_type_prop;
2648         in_gcc_extension = old_gcc_extension;
2649
2650         rem_anchor_token(')');
2651         expect(')', end_error);
2652
2653         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF);
2654         typeof_type->typeoft.expression  = expression;
2655         typeof_type->typeoft.typeof_type = type;
2656
2657         return typeof_type;
2658 end_error:
2659         return NULL;
2660 }
2661
2662 typedef enum specifiers_t {
2663         SPECIFIER_SIGNED    = 1 << 0,
2664         SPECIFIER_UNSIGNED  = 1 << 1,
2665         SPECIFIER_LONG      = 1 << 2,
2666         SPECIFIER_INT       = 1 << 3,
2667         SPECIFIER_DOUBLE    = 1 << 4,
2668         SPECIFIER_CHAR      = 1 << 5,
2669         SPECIFIER_WCHAR_T   = 1 << 6,
2670         SPECIFIER_SHORT     = 1 << 7,
2671         SPECIFIER_LONG_LONG = 1 << 8,
2672         SPECIFIER_FLOAT     = 1 << 9,
2673         SPECIFIER_BOOL      = 1 << 10,
2674         SPECIFIER_VOID      = 1 << 11,
2675         SPECIFIER_INT8      = 1 << 12,
2676         SPECIFIER_INT16     = 1 << 13,
2677         SPECIFIER_INT32     = 1 << 14,
2678         SPECIFIER_INT64     = 1 << 15,
2679         SPECIFIER_INT128    = 1 << 16,
2680         SPECIFIER_COMPLEX   = 1 << 17,
2681         SPECIFIER_IMAGINARY = 1 << 18,
2682 } specifiers_t;
2683
2684 static type_t *create_builtin_type(symbol_t *const symbol,
2685                                    type_t *const real_type)
2686 {
2687         type_t *type            = allocate_type_zero(TYPE_BUILTIN);
2688         type->builtin.symbol    = symbol;
2689         type->builtin.real_type = real_type;
2690         return identify_new_type(type);
2691 }
2692
2693 static type_t *get_typedef_type(symbol_t *symbol)
2694 {
2695         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2696         if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2697                 return NULL;
2698
2699         type_t *type            = allocate_type_zero(TYPE_TYPEDEF);
2700         type->typedeft.typedefe = &entity->typedefe;
2701
2702         return type;
2703 }
2704
2705 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2706 {
2707         expect('(', end_error);
2708
2709         attribute_property_argument_t *property
2710                 = allocate_ast_zero(sizeof(*property));
2711
2712         do {
2713                 if (token.type != T_IDENTIFIER) {
2714                         parse_error_expected("while parsing property declspec",
2715                                              T_IDENTIFIER, NULL);
2716                         goto end_error;
2717                 }
2718
2719                 bool is_put;
2720                 symbol_t *symbol = token.symbol;
2721                 next_token();
2722                 if (strcmp(symbol->string, "put") == 0) {
2723                         is_put = true;
2724                 } else if (strcmp(symbol->string, "get") == 0) {
2725                         is_put = false;
2726                 } else {
2727                         errorf(HERE, "expected put or get in property declspec");
2728                         goto end_error;
2729                 }
2730                 expect('=', end_error);
2731                 if (token.type != T_IDENTIFIER) {
2732                         parse_error_expected("while parsing property declspec",
2733                                              T_IDENTIFIER, NULL);
2734                         goto end_error;
2735                 }
2736                 if (is_put) {
2737                         property->put_symbol = token.symbol;
2738                 } else {
2739                         property->get_symbol = token.symbol;
2740                 }
2741                 next_token();
2742         } while (next_if(','));
2743
2744         attribute->a.property = property;
2745
2746         expect(')', end_error);
2747
2748 end_error:
2749         return attribute;
2750 }
2751
2752 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2753 {
2754         attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2755         if (next_if(T_restrict)) {
2756                 kind = ATTRIBUTE_MS_RESTRICT;
2757         } else if (token.type == T_IDENTIFIER) {
2758                 const char *name = token.symbol->string;
2759                 next_token();
2760                 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2761                      ++k) {
2762                         const char *attribute_name = get_attribute_name(k);
2763                         if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2764                                 kind = k;
2765                                 break;
2766                         }
2767                 }
2768
2769                 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2770                         warningf(HERE, "unknown __declspec '%s' ignored", name);
2771                 }
2772         } else {
2773                 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2774                 return NULL;
2775         }
2776
2777         attribute_t *attribute = allocate_attribute_zero(kind);
2778
2779         if (kind == ATTRIBUTE_MS_PROPERTY) {
2780                 return parse_attribute_ms_property(attribute);
2781         }
2782
2783         /* parse arguments */
2784         if (next_if('('))
2785                 attribute->a.arguments = parse_attribute_arguments();
2786
2787         return attribute;
2788 }
2789
2790 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2791 {
2792         eat(T__declspec);
2793
2794         expect('(', end_error);
2795
2796         if (next_if(')'))
2797                 return NULL;
2798
2799         add_anchor_token(')');
2800
2801         attribute_t **anchor = &first;
2802         do {
2803                 while (*anchor != NULL)
2804                         anchor = &(*anchor)->next;
2805
2806                 attribute_t *attribute
2807                         = parse_microsoft_extended_decl_modifier_single();
2808                 if (attribute == NULL)
2809                         goto end_error;
2810
2811                 *anchor = attribute;
2812                 anchor  = &attribute->next;
2813         } while (next_if(','));
2814
2815         rem_anchor_token(')');
2816         expect(')', end_error);
2817         return first;
2818
2819 end_error:
2820         rem_anchor_token(')');
2821         return first;
2822 }
2823
2824 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2825 {
2826         entity_t *entity             = allocate_entity_zero(kind);
2827         entity->base.namespc         = NAMESPACE_NORMAL;
2828         entity->base.source_position = *HERE;
2829         entity->base.symbol          = symbol;
2830         if (is_declaration(entity)) {
2831                 entity->declaration.type     = type_error_type;
2832                 entity->declaration.implicit = true;
2833         } else if (kind == ENTITY_TYPEDEF) {
2834                 entity->typedefe.type    = type_error_type;
2835                 entity->typedefe.builtin = true;
2836         }
2837         if (kind != ENTITY_COMPOUND_MEMBER)
2838                 record_entity(entity, false);
2839         return entity;
2840 }
2841
2842 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2843 {
2844         type_t            *type              = NULL;
2845         type_qualifiers_t  qualifiers        = TYPE_QUALIFIER_NONE;
2846         unsigned           type_specifiers   = 0;
2847         bool               newtype           = false;
2848         bool               saw_error         = false;
2849         bool               old_gcc_extension = in_gcc_extension;
2850
2851         specifiers->source_position = token.source_position;
2852
2853         while (true) {
2854                 specifiers->attributes = parse_attributes(specifiers->attributes);
2855
2856                 switch (token.type) {
2857                 /* storage class */
2858 #define MATCH_STORAGE_CLASS(token, class)                                  \
2859                 case token:                                                        \
2860                         if (specifiers->storage_class != STORAGE_CLASS_NONE) {         \
2861                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2862                         }                                                              \
2863                         specifiers->storage_class = class;                             \
2864                         if (specifiers->thread_local)                                  \
2865                                 goto check_thread_storage_class;                           \
2866                         next_token();                                                  \
2867                         break;
2868
2869                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
2870                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
2871                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
2872                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
2873                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2874
2875                 case T__declspec:
2876                         specifiers->attributes
2877                                 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2878                         break;
2879
2880                 case T___thread:
2881                         if (specifiers->thread_local) {
2882                                 errorf(HERE, "duplicate '__thread'");
2883                         } else {
2884                                 specifiers->thread_local = true;
2885 check_thread_storage_class:
2886                                 switch (specifiers->storage_class) {
2887                                         case STORAGE_CLASS_EXTERN:
2888                                         case STORAGE_CLASS_NONE:
2889                                         case STORAGE_CLASS_STATIC:
2890                                                 break;
2891
2892                                                 char const* wrong;
2893                                         case STORAGE_CLASS_AUTO:     wrong = "auto";     goto wrong_thread_storage_class;
2894                                         case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2895                                         case STORAGE_CLASS_TYPEDEF:  wrong = "typedef";  goto wrong_thread_storage_class;
2896 wrong_thread_storage_class:
2897                                                 errorf(HERE, "'__thread' used with '%s'", wrong);
2898                                                 break;
2899                                 }
2900                         }
2901                         next_token();
2902                         break;
2903
2904                 /* type qualifiers */
2905 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
2906                 case token:                                                     \
2907                         qualifiers |= qualifier;                                    \
2908                         next_token();                                               \
2909                         break
2910
2911                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2912                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2913                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2914                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
2915                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
2916                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
2917                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
2918                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
2919
2920                 case T___extension__:
2921                         next_token();
2922                         in_gcc_extension = true;
2923                         break;
2924
2925                 /* type specifiers */
2926 #define MATCH_SPECIFIER(token, specifier, name)                         \
2927                 case token:                                                     \
2928                         if (type_specifiers & specifier) {                           \
2929                                 errorf(HERE, "multiple " name " type specifiers given"); \
2930                         } else {                                                    \
2931                                 type_specifiers |= specifier;                           \
2932                         }                                                           \
2933                         next_token();                                               \
2934                         break
2935
2936                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool");
2937                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex");
2938                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2939                 MATCH_SPECIFIER(T__int128,    SPECIFIER_INT128,    "_int128");
2940                 MATCH_SPECIFIER(T__int16,     SPECIFIER_INT16,     "_int16");
2941                 MATCH_SPECIFIER(T__int32,     SPECIFIER_INT32,     "_int32");
2942                 MATCH_SPECIFIER(T__int64,     SPECIFIER_INT64,     "_int64");
2943                 MATCH_SPECIFIER(T__int8,      SPECIFIER_INT8,      "_int8");
2944                 MATCH_SPECIFIER(T_bool,       SPECIFIER_BOOL,      "bool");
2945                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char");
2946                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double");
2947                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float");
2948                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int");
2949                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short");
2950                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed");
2951                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned");
2952                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void");
2953                 MATCH_SPECIFIER(T_wchar_t,    SPECIFIER_WCHAR_T,   "wchar_t");
2954
2955                 case T_inline:
2956                         next_token();
2957                         specifiers->is_inline = true;
2958                         break;
2959
2960 #if 0
2961                 case T__forceinline:
2962                         next_token();
2963                         specifiers->modifiers |= DM_FORCEINLINE;
2964                         break;
2965 #endif
2966
2967                 case T_long:
2968                         if (type_specifiers & SPECIFIER_LONG_LONG) {
2969                                 errorf(HERE, "multiple type specifiers given");
2970                         } else if (type_specifiers & SPECIFIER_LONG) {
2971                                 type_specifiers |= SPECIFIER_LONG_LONG;
2972                         } else {
2973                                 type_specifiers |= SPECIFIER_LONG;
2974                         }
2975                         next_token();
2976                         break;
2977
2978 #define CHECK_DOUBLE_TYPE()        \
2979                         if ( type != NULL)     \
2980                                 errorf(HERE, "multiple data types in declaration specifiers");
2981
2982                 case T_struct:
2983                         CHECK_DOUBLE_TYPE();
2984                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2985
2986                         type->compound.compound = parse_compound_type_specifier(true);
2987                         break;
2988                 case T_union:
2989                         CHECK_DOUBLE_TYPE();
2990                         type = allocate_type_zero(TYPE_COMPOUND_UNION);
2991                         type->compound.compound = parse_compound_type_specifier(false);
2992                         break;
2993                 case T_enum:
2994                         CHECK_DOUBLE_TYPE();
2995                         type = parse_enum_specifier();
2996                         break;
2997                 case T___typeof__:
2998                         CHECK_DOUBLE_TYPE();
2999                         type = parse_typeof();
3000                         break;
3001                 case T___builtin_va_list:
3002                         CHECK_DOUBLE_TYPE();
3003                         type = duplicate_type(type_valist);
3004                         next_token();
3005                         break;
3006
3007                 case T_IDENTIFIER: {
3008                         /* only parse identifier if we haven't found a type yet */
3009                         if (type != NULL || type_specifiers != 0) {
3010                                 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3011                                  * declaration, so it doesn't generate errors about expecting '(' or
3012                                  * '{' later on. */
3013                                 switch (look_ahead(1)->type) {
3014                                         STORAGE_CLASSES
3015                                         TYPE_SPECIFIERS
3016                                         case T_const:
3017                                         case T_restrict:
3018                                         case T_volatile:
3019                                         case T_inline:
3020                                         case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3021                                         case T_IDENTIFIER:
3022                                         case '&':
3023                                         case '*':
3024                                                 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3025                                                 next_token();
3026                                                 continue;
3027
3028                                         default:
3029                                                 goto finish_specifiers;
3030                                 }
3031                         }
3032
3033                         type_t *const typedef_type = get_typedef_type(token.symbol);
3034                         if (typedef_type == NULL) {
3035                                 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3036                                  * declaration, so it doesn't generate 'implicit int' followed by more
3037                                  * errors later on. */
3038                                 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3039                                 switch (la1_type) {
3040                                         DECLARATION_START
3041                                         case T_IDENTIFIER:
3042                                         case '&':
3043                                         case '*': {
3044                                                 errorf(HERE, "%K does not name a type", &token);
3045
3046                                                 entity_t *entity =
3047                                                         create_error_entity(token.symbol, ENTITY_TYPEDEF);
3048
3049                                                 type = allocate_type_zero(TYPE_TYPEDEF);
3050                                                 type->typedeft.typedefe = &entity->typedefe;
3051
3052                                                 next_token();
3053                                                 saw_error = true;
3054                                                 if (la1_type == '&' || la1_type == '*')
3055                                                         goto finish_specifiers;
3056                                                 continue;
3057                                         }
3058
3059                                         default:
3060                                                 goto finish_specifiers;
3061                                 }
3062                         }
3063
3064                         next_token();
3065                         type = typedef_type;
3066                         break;
3067                 }
3068
3069                 /* function specifier */
3070                 default:
3071                         goto finish_specifiers;
3072                 }
3073         }
3074
3075 finish_specifiers:
3076         specifiers->attributes = parse_attributes(specifiers->attributes);
3077
3078         in_gcc_extension = old_gcc_extension;
3079
3080         if (type == NULL || (saw_error && type_specifiers != 0)) {
3081                 atomic_type_kind_t atomic_type;
3082
3083                 /* match valid basic types */
3084                 switch (type_specifiers) {
3085                 case SPECIFIER_VOID:
3086                         atomic_type = ATOMIC_TYPE_VOID;
3087                         break;
3088                 case SPECIFIER_WCHAR_T:
3089                         atomic_type = ATOMIC_TYPE_WCHAR_T;
3090                         break;
3091                 case SPECIFIER_CHAR:
3092                         atomic_type = ATOMIC_TYPE_CHAR;
3093                         break;
3094                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3095                         atomic_type = ATOMIC_TYPE_SCHAR;
3096                         break;
3097                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3098                         atomic_type = ATOMIC_TYPE_UCHAR;
3099                         break;
3100                 case SPECIFIER_SHORT:
3101                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3102                 case SPECIFIER_SHORT | SPECIFIER_INT:
3103                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3104                         atomic_type = ATOMIC_TYPE_SHORT;
3105                         break;
3106                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3107                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3108                         atomic_type = ATOMIC_TYPE_USHORT;
3109                         break;
3110                 case SPECIFIER_INT:
3111                 case SPECIFIER_SIGNED:
3112                 case SPECIFIER_SIGNED | SPECIFIER_INT:
3113                         atomic_type = ATOMIC_TYPE_INT;
3114                         break;
3115                 case SPECIFIER_UNSIGNED:
3116                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3117                         atomic_type = ATOMIC_TYPE_UINT;
3118                         break;
3119                 case SPECIFIER_LONG:
3120                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3121                 case SPECIFIER_LONG | SPECIFIER_INT:
3122                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3123                         atomic_type = ATOMIC_TYPE_LONG;
3124                         break;
3125                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3126                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3127                         atomic_type = ATOMIC_TYPE_ULONG;
3128                         break;
3129
3130                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3131                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3132                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3133                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3134                         | SPECIFIER_INT:
3135                         atomic_type = ATOMIC_TYPE_LONGLONG;
3136                         goto warn_about_long_long;
3137
3138                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3139                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3140                         | SPECIFIER_INT:
3141                         atomic_type = ATOMIC_TYPE_ULONGLONG;
3142 warn_about_long_long:
3143                         if (warning.long_long) {
3144                                 warningf(&specifiers->source_position,
3145                                          "ISO C90 does not support 'long long'");
3146                         }
3147                         break;
3148
3149                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3150                         atomic_type = unsigned_int8_type_kind;
3151                         break;
3152
3153                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3154                         atomic_type = unsigned_int16_type_kind;
3155                         break;
3156
3157                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3158                         atomic_type = unsigned_int32_type_kind;
3159                         break;
3160
3161                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3162                         atomic_type = unsigned_int64_type_kind;
3163                         break;
3164
3165                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3166                         atomic_type = unsigned_int128_type_kind;
3167                         break;
3168
3169                 case SPECIFIER_INT8:
3170                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3171                         atomic_type = int8_type_kind;
3172                         break;
3173
3174                 case SPECIFIER_INT16:
3175                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3176                         atomic_type = int16_type_kind;
3177                         break;
3178
3179                 case SPECIFIER_INT32:
3180                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3181                         atomic_type = int32_type_kind;
3182                         break;
3183
3184                 case SPECIFIER_INT64:
3185                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3186                         atomic_type = int64_type_kind;
3187                         break;
3188
3189                 case SPECIFIER_INT128:
3190                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3191                         atomic_type = int128_type_kind;
3192                         break;
3193
3194                 case SPECIFIER_FLOAT:
3195                         atomic_type = ATOMIC_TYPE_FLOAT;
3196                         break;
3197                 case SPECIFIER_DOUBLE:
3198                         atomic_type = ATOMIC_TYPE_DOUBLE;
3199                         break;
3200                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3201                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3202                         break;
3203                 case SPECIFIER_BOOL:
3204                         atomic_type = ATOMIC_TYPE_BOOL;
3205                         break;
3206                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3207                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3208                         atomic_type = ATOMIC_TYPE_FLOAT;
3209                         break;
3210                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3211                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3212                         atomic_type = ATOMIC_TYPE_DOUBLE;
3213                         break;
3214                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3215                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3216                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3217                         break;
3218                 default:
3219                         /* invalid specifier combination, give an error message */
3220                         if (type_specifiers == 0) {
3221                                 if (saw_error)
3222                                         goto end_error;
3223
3224                                 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3225                                 if (!(c_mode & _CXX) && !strict_mode) {
3226                                         if (warning.implicit_int) {
3227                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
3228                                         }
3229                                         atomic_type = ATOMIC_TYPE_INT;
3230                                         break;
3231                                 } else {
3232                                         errorf(HERE, "no type specifiers given in declaration");
3233                                 }
3234                         } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3235                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
3236                                 errorf(HERE, "signed and unsigned specifiers given");
3237                         } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3238                                 errorf(HERE, "only integer types can be signed or unsigned");
3239                         } else {
3240                                 errorf(HERE, "multiple datatypes in declaration");
3241                         }
3242                         goto end_error;
3243                 }
3244
3245                 if (type_specifiers & SPECIFIER_COMPLEX) {
3246                         type                = allocate_type_zero(TYPE_COMPLEX);
3247                         type->complex.akind = atomic_type;
3248                 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3249                         type                  = allocate_type_zero(TYPE_IMAGINARY);
3250                         type->imaginary.akind = atomic_type;
3251                 } else {
3252                         type                 = allocate_type_zero(TYPE_ATOMIC);
3253                         type->atomic.akind   = atomic_type;
3254                 }
3255                 newtype = true;
3256         } else if (type_specifiers != 0) {
3257                 errorf(HERE, "multiple datatypes in declaration");
3258         }
3259
3260         /* FIXME: check type qualifiers here */
3261         type->base.qualifiers = qualifiers;
3262
3263         if (newtype) {
3264                 type = identify_new_type(type);
3265         } else {
3266                 type = typehash_insert(type);
3267         }
3268
3269         if (specifiers->attributes != NULL)
3270                 type = handle_type_attributes(specifiers->attributes, type);
3271         specifiers->type = type;
3272         return;
3273
3274 end_error:
3275         specifiers->type = type_error_type;
3276 }
3277
3278 static type_qualifiers_t parse_type_qualifiers(void)
3279 {
3280         type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3281
3282         while (true) {
3283                 switch (token.type) {
3284                 /* type qualifiers */
3285                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3286                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3287                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3288                 /* microsoft extended type modifiers */
3289                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3290                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3291                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3292                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3293                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3294
3295                 default:
3296                         return qualifiers;
3297                 }
3298         }
3299 }
3300
3301 /**
3302  * Parses an K&R identifier list
3303  */
3304 static void parse_identifier_list(scope_t *scope)
3305 {
3306         do {
3307                 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3308                 entity->base.source_position = token.source_position;
3309                 entity->base.namespc         = NAMESPACE_NORMAL;
3310                 entity->base.symbol          = token.symbol;
3311                 /* a K&R parameter has no type, yet */
3312                 next_token();
3313
3314                 if (scope != NULL)
3315                         append_entity(scope, entity);
3316         } while (next_if(',') && token.type == T_IDENTIFIER);
3317 }
3318
3319 static entity_t *parse_parameter(void)
3320 {
3321         declaration_specifiers_t specifiers;
3322         memset(&specifiers, 0, sizeof(specifiers));
3323
3324         parse_declaration_specifiers(&specifiers);
3325
3326         entity_t *entity = parse_declarator(&specifiers,
3327                         DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3328         anonymous_entity = NULL;
3329         return entity;
3330 }
3331
3332 static void semantic_parameter_incomplete(const entity_t *entity)
3333 {
3334         assert(entity->kind == ENTITY_PARAMETER);
3335
3336         /* §6.7.5.3:4  After adjustment, the parameters in a parameter type
3337          *             list in a function declarator that is part of a
3338          *             definition of that function shall not have
3339          *             incomplete type. */
3340         type_t *type = skip_typeref(entity->declaration.type);
3341         if (is_type_incomplete(type)) {
3342                 errorf(&entity->base.source_position,
3343                                 "parameter '%#T' has incomplete type",
3344                                 entity->declaration.type, entity->base.symbol);
3345         }
3346 }
3347
3348 static bool has_parameters(void)
3349 {
3350         /* func(void) is not a parameter */
3351         if (token.type == T_IDENTIFIER) {
3352                 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3353                 if (entity == NULL)
3354                         return true;
3355                 if (entity->kind != ENTITY_TYPEDEF)
3356                         return true;
3357                 if (skip_typeref(entity->typedefe.type) != type_void)
3358                         return true;
3359         } else if (token.type != T_void) {
3360                 return true;
3361         }
3362         if (look_ahead(1)->type != ')')
3363                 return true;
3364         next_token();
3365         return false;
3366 }
3367
3368 /**
3369  * Parses function type parameters (and optionally creates variable_t entities
3370  * for them in a scope)
3371  */
3372 static void parse_parameters(function_type_t *type, scope_t *scope)
3373 {
3374         eat('(');
3375         add_anchor_token(')');
3376         int saved_comma_state = save_and_reset_anchor_state(',');
3377
3378         if (token.type == T_IDENTIFIER &&
3379             !is_typedef_symbol(token.symbol)) {
3380                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3381                 if (la1_type == ',' || la1_type == ')') {
3382                         type->kr_style_parameters = true;
3383                         parse_identifier_list(scope);
3384                         goto parameters_finished;
3385                 }
3386         }
3387
3388         if (token.type == ')') {
3389                 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3390                 if (!(c_mode & _CXX))
3391                         type->unspecified_parameters = true;
3392                 goto parameters_finished;
3393         }
3394
3395         if (has_parameters()) {
3396                 function_parameter_t **anchor = &type->parameters;
3397                 do {
3398                         switch (token.type) {
3399                         case T_DOTDOTDOT:
3400                                 next_token();
3401                                 type->variadic = true;
3402                                 goto parameters_finished;
3403
3404                         case T_IDENTIFIER:
3405                         case T___extension__:
3406                         DECLARATION_START
3407                         {
3408                                 entity_t *entity = parse_parameter();
3409                                 if (entity->kind == ENTITY_TYPEDEF) {
3410                                         errorf(&entity->base.source_position,
3411                                                         "typedef not allowed as function parameter");
3412                                         break;
3413                                 }
3414                                 assert(is_declaration(entity));
3415
3416                                 semantic_parameter_incomplete(entity);
3417
3418                                 function_parameter_t *const parameter =
3419                                         allocate_parameter(entity->declaration.type);
3420
3421                                 if (scope != NULL) {
3422                                         append_entity(scope, entity);
3423                                 }
3424
3425                                 *anchor = parameter;
3426                                 anchor  = &parameter->next;
3427                                 break;
3428                         }
3429
3430                         default:
3431                                 goto parameters_finished;
3432                         }
3433                 } while (next_if(','));
3434         }
3435
3436
3437 parameters_finished:
3438         rem_anchor_token(')');
3439         expect(')', end_error);
3440
3441 end_error:
3442         restore_anchor_state(',', saved_comma_state);
3443 }
3444
3445 typedef enum construct_type_kind_t {
3446         CONSTRUCT_INVALID,
3447         CONSTRUCT_POINTER,
3448         CONSTRUCT_REFERENCE,
3449         CONSTRUCT_FUNCTION,
3450         CONSTRUCT_ARRAY
3451 } construct_type_kind_t;
3452
3453 typedef union construct_type_t construct_type_t;
3454
3455 typedef struct construct_type_base_t {
3456         construct_type_kind_t  kind;
3457         source_position_t      pos;
3458         construct_type_t      *next;
3459 } construct_type_base_t;
3460
3461 typedef struct parsed_pointer_t {
3462         construct_type_base_t  base;
3463         type_qualifiers_t      type_qualifiers;
3464         variable_t            *base_variable;  /**< MS __based extension. */
3465 } parsed_pointer_t;
3466
3467 typedef struct parsed_reference_t {
3468         construct_type_base_t base;
3469 } parsed_reference_t;
3470
3471 typedef struct construct_function_type_t {
3472         construct_type_base_t  base;
3473         type_t                *function_type;
3474 } construct_function_type_t;
3475
3476 typedef struct parsed_array_t {
3477         construct_type_base_t  base;
3478         type_qualifiers_t      type_qualifiers;
3479         bool                   is_static;
3480         bool                   is_variable;
3481         expression_t          *size;
3482 } parsed_array_t;
3483
3484 union construct_type_t {
3485         construct_type_kind_t     kind;
3486         construct_type_base_t     base;
3487         parsed_pointer_t          pointer;
3488         parsed_reference_t        reference;
3489         construct_function_type_t function;
3490         parsed_array_t            array;
3491 };
3492
3493 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3494 {
3495         construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3496         memset(cons, 0, size);
3497         cons->kind     = kind;
3498         cons->base.pos = *HERE;
3499         return cons;
3500 }
3501
3502 /* §6.7.5.1 */
3503 static construct_type_t *parse_pointer_declarator(void)
3504 {
3505         construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3506         eat('*');
3507         cons->pointer.type_qualifiers = parse_type_qualifiers();
3508         //cons->pointer.base_variable   = base_variable;
3509
3510         return cons;
3511 }
3512
3513 /* ISO/IEC 14882:1998(E) §8.3.2 */
3514 static construct_type_t *parse_reference_declarator(void)
3515 {
3516         if (!(c_mode & _CXX))
3517                 errorf(HERE, "references are only available for C++");
3518
3519         construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3520         eat('&');
3521
3522         return cons;
3523 }
3524
3525 /* §6.7.5.2 */
3526 static construct_type_t *parse_array_declarator(void)
3527 {
3528         construct_type_t *const cons  = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3529         parsed_array_t   *const array = &cons->array;
3530
3531         eat('[');
3532         add_anchor_token(']');
3533
3534         bool is_static = next_if(T_static);
3535
3536         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3537
3538         if (!is_static)
3539                 is_static = next_if(T_static);
3540
3541         array->type_qualifiers = type_qualifiers;
3542         array->is_static       = is_static;
3543
3544         expression_t *size = NULL;
3545         if (token.type == '*' && look_ahead(1)->type == ']') {
3546                 array->is_variable = true;
3547                 next_token();
3548         } else if (token.type != ']') {
3549                 size = parse_assignment_expression();
3550
3551                 /* §6.7.5.2:1  Array size must have integer type */
3552                 type_t *const orig_type = size->base.type;
3553                 type_t *const type      = skip_typeref(orig_type);
3554                 if (!is_type_integer(type) && is_type_valid(type)) {
3555                         errorf(&size->base.source_position,
3556                                "array size '%E' must have integer type but has type '%T'",
3557                                size, orig_type);
3558                 }
3559
3560                 array->size = size;
3561                 mark_vars_read(size, NULL);
3562         }
3563
3564         if (is_static && size == NULL)
3565                 errorf(HERE, "static array parameters require a size");
3566
3567         rem_anchor_token(']');
3568         expect(']', end_error);
3569
3570 end_error:
3571         return cons;
3572 }
3573
3574 /* §6.7.5.3 */
3575 static construct_type_t *parse_function_declarator(scope_t *scope)
3576 {
3577         construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3578
3579         type_t          *type  = allocate_type_zero(TYPE_FUNCTION);
3580         function_type_t *ftype = &type->function;
3581
3582         ftype->linkage            = current_linkage;
3583         ftype->calling_convention = CC_DEFAULT;
3584
3585         parse_parameters(ftype, scope);
3586
3587         cons->function.function_type = type;
3588
3589         return cons;
3590 }
3591
3592 typedef struct parse_declarator_env_t {
3593         bool               may_be_abstract : 1;
3594         bool               must_be_abstract : 1;
3595         decl_modifiers_t   modifiers;
3596         symbol_t          *symbol;
3597         source_position_t  source_position;
3598         scope_t            parameters;
3599         attribute_t       *attributes;
3600 } parse_declarator_env_t;
3601
3602 /* §6.7.5 */
3603 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3604 {
3605         /* construct a single linked list of construct_type_t's which describe
3606          * how to construct the final declarator type */
3607         construct_type_t  *first      = NULL;
3608         construct_type_t **anchor     = &first;
3609
3610         env->attributes = parse_attributes(env->attributes);
3611
3612         for (;;) {
3613                 construct_type_t *type;
3614                 //variable_t       *based = NULL; /* MS __based extension */
3615                 switch (token.type) {
3616                         case '&':
3617                                 type = parse_reference_declarator();
3618                                 break;
3619
3620                         case T__based: {
3621                                 panic("based not supported anymore");
3622                                 /* FALLTHROUGH */
3623                         }
3624
3625                         case '*':
3626                                 type = parse_pointer_declarator();
3627                                 break;
3628
3629                         default:
3630                                 goto ptr_operator_end;
3631                 }
3632
3633                 *anchor = type;
3634                 anchor  = &type->base.next;
3635
3636                 /* TODO: find out if this is correct */
3637                 env->attributes = parse_attributes(env->attributes);
3638         }
3639
3640 ptr_operator_end: ;
3641         construct_type_t *inner_types = NULL;
3642
3643         switch (token.type) {
3644         case T_IDENTIFIER:
3645                 if (env->must_be_abstract) {
3646                         errorf(HERE, "no identifier expected in typename");
3647                 } else {
3648                         env->symbol          = token.symbol;
3649                         env->source_position = token.source_position;
3650                 }
3651                 next_token();
3652                 break;
3653         case '(':
3654                 /* §6.7.6:2 footnote 126:  Empty parentheses in a type name are
3655                  * interpreted as ``function with no parameter specification'', rather
3656                  * than redundant parentheses around the omitted identifier. */
3657                 if (look_ahead(1)->type != ')') {
3658                         next_token();
3659                         add_anchor_token(')');
3660                         inner_types = parse_inner_declarator(env);
3661                         if (inner_types != NULL) {
3662                                 /* All later declarators only modify the return type */
3663                                 env->must_be_abstract = true;
3664                         }
3665                         rem_anchor_token(')');
3666                         expect(')', end_error);
3667                 } else if (!env->may_be_abstract) {
3668                         errorf(HERE, "declarator must have a name");
3669                         goto error_out;
3670                 }
3671                 break;
3672         default:
3673                 if (env->may_be_abstract)
3674                         break;
3675                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3676 error_out:
3677                 eat_until_anchor();
3678                 return NULL;
3679         }
3680
3681         construct_type_t **const p = anchor;
3682
3683         for (;;) {
3684                 construct_type_t *type;
3685                 switch (token.type) {
3686                 case '(': {
3687                         scope_t *scope = NULL;
3688                         if (!env->must_be_abstract) {
3689                                 scope = &env->parameters;
3690                         }
3691
3692                         type = parse_function_declarator(scope);
3693                         break;
3694                 }
3695                 case '[':
3696                         type = parse_array_declarator();
3697                         break;
3698                 default:
3699                         goto declarator_finished;
3700                 }
3701
3702                 /* insert in the middle of the list (at p) */
3703                 type->base.next = *p;
3704                 *p              = type;
3705                 if (anchor == p)
3706                         anchor = &type->base.next;
3707         }
3708
3709 declarator_finished:
3710         /* append inner_types at the end of the list, we don't to set anchor anymore
3711          * as it's not needed anymore */
3712         *anchor = inner_types;
3713
3714         return first;
3715 end_error:
3716         return NULL;
3717 }
3718
3719 static type_t *construct_declarator_type(construct_type_t *construct_list,
3720                                          type_t *type)
3721 {
3722         construct_type_t *iter = construct_list;
3723         for (; iter != NULL; iter = iter->base.next) {
3724                 source_position_t const* const pos = &iter->base.pos;
3725                 switch (iter->kind) {
3726                 case CONSTRUCT_INVALID:
3727                         break;
3728                 case CONSTRUCT_FUNCTION: {
3729                         construct_function_type_t *function      = &iter->function;
3730                         type_t                    *function_type = function->function_type;
3731
3732                         function_type->function.return_type = type;
3733
3734                         type_t *skipped_return_type = skip_typeref(type);
3735                         /* §6.7.5.3:1 */
3736                         if (is_type_function(skipped_return_type)) {
3737                                 errorf(pos, "function returning function is not allowed");
3738                         } else if (is_type_array(skipped_return_type)) {
3739                                 errorf(pos, "function returning array is not allowed");
3740                         } else {
3741                                 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3742                                         warningf(pos, "type qualifiers in return type of function type are meaningless");
3743                                 }
3744                         }
3745
3746                         /* The function type was constructed earlier.  Freeing it here will
3747                          * destroy other types. */
3748                         type = typehash_insert(function_type);
3749                         continue;
3750                 }
3751
3752                 case CONSTRUCT_POINTER: {
3753                         if (is_type_reference(skip_typeref(type)))
3754                                 errorf(pos, "cannot declare a pointer to reference");
3755
3756                         parsed_pointer_t *pointer = &iter->pointer;
3757                         type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3758                         continue;
3759                 }
3760
3761                 case CONSTRUCT_REFERENCE:
3762                         if (is_type_reference(skip_typeref(type)))
3763                                 errorf(pos, "cannot declare a reference to reference");
3764
3765                         type = make_reference_type(type);
3766                         continue;
3767
3768                 case CONSTRUCT_ARRAY: {
3769                         if (is_type_reference(skip_typeref(type)))
3770                                 errorf(pos, "cannot declare an array of references");
3771
3772                         parsed_array_t *array      = &iter->array;
3773                         type_t         *array_type = allocate_type_zero(TYPE_ARRAY);
3774
3775                         expression_t *size_expression = array->size;
3776                         if (size_expression != NULL) {
3777                                 size_expression
3778                                         = create_implicit_cast(size_expression, type_size_t);
3779                         }
3780
3781                         array_type->base.qualifiers       = array->type_qualifiers;
3782                         array_type->array.element_type    = type;
3783                         array_type->array.is_static       = array->is_static;
3784                         array_type->array.is_variable     = array->is_variable;
3785                         array_type->array.size_expression = size_expression;
3786
3787                         if (size_expression != NULL) {
3788                                 switch (is_constant_expression(size_expression)) {
3789                                         case EXPR_CLASS_CONSTANT: {
3790                                                 long const size = fold_constant_to_int(size_expression);
3791                                                 array_type->array.size          = size;
3792                                                 array_type->array.size_constant = true;
3793                                                 /* §6.7.5.2:1  If the expression is a constant expression, it shall
3794                                                  * have a value greater than zero. */
3795                                                 if (size <= 0) {
3796                                                         if (size < 0 || !GNU_MODE) {
3797                                                                 errorf(&size_expression->base.source_position,
3798                                                                                 "size of array must be greater than zero");
3799                                                         } else if (warning.other) {
3800                                                                 warningf(&size_expression->base.source_position,
3801                                                                                 "zero length arrays are a GCC extension");
3802                                                         }
3803                                                 }
3804                                                 break;
3805                                         }
3806
3807                                         case EXPR_CLASS_VARIABLE:
3808                                                 array_type->array.is_vla = true;
3809                                                 break;
3810
3811                                         case EXPR_CLASS_ERROR:
3812                                                 break;
3813                                 }
3814                         }
3815
3816                         type_t *skipped_type = skip_typeref(type);
3817                         /* §6.7.5.2:1 */
3818                         if (is_type_incomplete(skipped_type)) {
3819                                 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3820                         } else if (is_type_function(skipped_type)) {
3821                                 errorf(pos, "array of functions is not allowed");
3822                         }
3823                         type = identify_new_type(array_type);
3824                         continue;
3825                 }
3826                 }
3827                 internal_errorf(pos, "invalid type construction found");
3828         }
3829
3830         return type;
3831 }
3832
3833 static type_t *automatic_type_conversion(type_t *orig_type);
3834
3835 static type_t *semantic_parameter(const source_position_t *pos,
3836                                   type_t *type,
3837                                   const declaration_specifiers_t *specifiers,
3838                                   symbol_t *symbol)
3839 {
3840         /* §6.7.5.3:7  A declaration of a parameter as ``array of type''
3841          *             shall be adjusted to ``qualified pointer to type'',
3842          *             [...]
3843          * §6.7.5.3:8  A declaration of a parameter as ``function returning
3844          *             type'' shall be adjusted to ``pointer to function
3845          *             returning type'', as in 6.3.2.1. */
3846         type = automatic_type_conversion(type);
3847
3848         if (specifiers->is_inline && is_type_valid(type)) {
3849                 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3850         }
3851
3852         /* §6.9.1:6  The declarations in the declaration list shall contain
3853          *           no storage-class specifier other than register and no
3854          *           initializations. */
3855         if (specifiers->thread_local || (
3856                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3857                         specifiers->storage_class != STORAGE_CLASS_REGISTER)
3858            ) {
3859                 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3860         }
3861
3862         /* delay test for incomplete type, because we might have (void)
3863          * which is legal but incomplete... */
3864
3865         return type;
3866 }
3867
3868 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3869                                   declarator_flags_t flags)
3870 {
3871         parse_declarator_env_t env;
3872         memset(&env, 0, sizeof(env));
3873         env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3874
3875         construct_type_t *construct_type = parse_inner_declarator(&env);
3876         type_t           *orig_type      =
3877                 construct_declarator_type(construct_type, specifiers->type);
3878         type_t           *type           = skip_typeref(orig_type);
3879
3880         if (construct_type != NULL) {
3881                 obstack_free(&temp_obst, construct_type);
3882         }
3883
3884         attribute_t *attributes = parse_attributes(env.attributes);
3885         /* append (shared) specifier attribute behind attributes of this
3886          * declarator */
3887         attribute_t **anchor = &attributes;
3888         while (*anchor != NULL)
3889                 anchor = &(*anchor)->next;
3890         *anchor = specifiers->attributes;
3891
3892         entity_t *entity;
3893         if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3894                 entity                       = allocate_entity_zero(ENTITY_TYPEDEF);
3895                 entity->base.namespc         = NAMESPACE_NORMAL;
3896                 entity->base.symbol          = env.symbol;
3897                 entity->base.source_position = env.source_position;
3898                 entity->typedefe.type        = orig_type;
3899
3900                 if (anonymous_entity != NULL) {
3901                         if (is_type_compound(type)) {
3902                                 assert(anonymous_entity->compound.alias == NULL);
3903                                 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3904                                        anonymous_entity->kind == ENTITY_UNION);
3905                                 anonymous_entity->compound.alias = entity;
3906                                 anonymous_entity = NULL;
3907                         } else if (is_type_enum(type)) {
3908                                 assert(anonymous_entity->enume.alias == NULL);
3909                                 assert(anonymous_entity->kind == ENTITY_ENUM);
3910                                 anonymous_entity->enume.alias = entity;
3911                                 anonymous_entity = NULL;
3912                         }
3913                 }
3914         } else {
3915                 /* create a declaration type entity */
3916                 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3917                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3918
3919                         if (env.symbol != NULL) {
3920                                 if (specifiers->is_inline && is_type_valid(type)) {
3921                                         errorf(&env.source_position,
3922                                                         "compound member '%Y' declared 'inline'", env.symbol);
3923                                 }
3924
3925                                 if (specifiers->thread_local ||
3926                                                 specifiers->storage_class != STORAGE_CLASS_NONE) {
3927                                         errorf(&env.source_position,
3928                                                         "compound member '%Y' must have no storage class",
3929                                                         env.symbol);
3930                                 }
3931                         }
3932                 } else if (flags & DECL_IS_PARAMETER) {
3933                         orig_type = semantic_parameter(&env.source_position, orig_type,
3934                                                        specifiers, env.symbol);
3935
3936                         entity = allocate_entity_zero(ENTITY_PARAMETER);
3937                 } else if (is_type_function(type)) {
3938                         entity = allocate_entity_zero(ENTITY_FUNCTION);
3939
3940                         entity->function.is_inline  = specifiers->is_inline;
3941                         entity->function.parameters = env.parameters;
3942
3943                         if (env.symbol != NULL) {
3944                                 /* this needs fixes for C++ */
3945                                 bool in_function_scope = current_function != NULL;
3946
3947                                 if (specifiers->thread_local || (
3948                                                         specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3949                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3950                                                         (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3951                                                 )) {
3952                                         errorf(&env.source_position,
3953                                                         "invalid storage class for function '%Y'", env.symbol);
3954                                 }
3955                         }
3956                 } else {
3957                         entity = allocate_entity_zero(ENTITY_VARIABLE);
3958
3959                         entity->variable.thread_local = specifiers->thread_local;
3960
3961                         if (env.symbol != NULL) {
3962                                 if (specifiers->is_inline && is_type_valid(type)) {
3963                                         errorf(&env.source_position,
3964                                                         "variable '%Y' declared 'inline'", env.symbol);
3965                                 }
3966
3967                                 bool invalid_storage_class = false;
3968                                 if (current_scope == file_scope) {
3969                                         if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3970                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3971                                                         specifiers->storage_class != STORAGE_CLASS_STATIC) {
3972                                                 invalid_storage_class = true;
3973                                         }
3974                                 } else {
3975                                         if (specifiers->thread_local &&
3976                                                         specifiers->storage_class == STORAGE_CLASS_NONE) {
3977                                                 invalid_storage_class = true;
3978                                         }
3979                                 }
3980                                 if (invalid_storage_class) {
3981                                         errorf(&env.source_position,
3982                                                         "invalid storage class for variable '%Y'", env.symbol);
3983                                 }
3984                         }
3985                 }
3986
3987                 if (env.symbol != NULL) {
3988                         entity->base.symbol          = env.symbol;
3989                         entity->base.source_position = env.source_position;
3990                 } else {
3991                         entity->base.source_position = specifiers->source_position;
3992                 }
3993                 entity->base.namespc           = NAMESPACE_NORMAL;
3994                 entity->declaration.type       = orig_type;
3995                 entity->declaration.alignment  = get_type_alignment(orig_type);
3996                 entity->declaration.modifiers  = env.modifiers;
3997                 entity->declaration.attributes = attributes;
3998
3999                 storage_class_t storage_class = specifiers->storage_class;
4000                 entity->declaration.declared_storage_class = storage_class;
4001
4002                 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4003                         storage_class = STORAGE_CLASS_AUTO;
4004                 entity->declaration.storage_class = storage_class;
4005         }
4006
4007         if (attributes != NULL) {
4008                 handle_entity_attributes(attributes, entity);
4009         }
4010
4011         return entity;
4012 }
4013
4014 static type_t *parse_abstract_declarator(type_t *base_type)
4015 {
4016         parse_declarator_env_t env;
4017         memset(&env, 0, sizeof(env));
4018         env.may_be_abstract = true;
4019         env.must_be_abstract = true;
4020
4021         construct_type_t *construct_type = parse_inner_declarator(&env);
4022
4023         type_t *result = construct_declarator_type(construct_type, base_type);
4024         if (construct_type != NULL) {
4025                 obstack_free(&temp_obst, construct_type);
4026         }
4027         result = handle_type_attributes(env.attributes, result);
4028
4029         return result;
4030 }
4031
4032 /**
4033  * Check if the declaration of main is suspicious.  main should be a
4034  * function with external linkage, returning int, taking either zero
4035  * arguments, two, or three arguments of appropriate types, ie.
4036  *
4037  * int main([ int argc, char **argv [, char **env ] ]).
4038  *
4039  * @param decl    the declaration to check
4040  * @param type    the function type of the declaration
4041  */
4042 static void check_main(const entity_t *entity)
4043 {
4044         const source_position_t *pos = &entity->base.source_position;
4045         if (entity->kind != ENTITY_FUNCTION) {
4046                 warningf(pos, "'main' is not a function");
4047                 return;
4048         }
4049
4050         if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4051                 warningf(pos, "'main' is normally a non-static function");
4052         }
4053
4054         type_t *type = skip_typeref(entity->declaration.type);
4055         assert(is_type_function(type));
4056
4057         function_type_t *func_type = &type->function;
4058         if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4059                 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4060                          func_type->return_type);
4061         }
4062         const function_parameter_t *parm = func_type->parameters;
4063         if (parm != NULL) {
4064                 type_t *const first_type = parm->type;
4065                 if (!types_compatible(skip_typeref(first_type), type_int)) {
4066                         warningf(pos,
4067                                  "first argument of 'main' should be 'int', but is '%T'",
4068                                  first_type);
4069                 }
4070                 parm = parm->next;
4071                 if (parm != NULL) {
4072                         type_t *const second_type = parm->type;
4073                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4074                                 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4075                         }
4076                         parm = parm->next;
4077                         if (parm != NULL) {
4078                                 type_t *const third_type = parm->type;
4079                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4080                                         warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4081                                 }
4082                                 parm = parm->next;
4083                                 if (parm != NULL)
4084                                         goto warn_arg_count;
4085                         }
4086                 } else {
4087 warn_arg_count:
4088                         warningf(pos, "'main' takes only zero, two or three arguments");
4089                 }
4090         }
4091 }
4092
4093 /**
4094  * Check if a symbol is the equal to "main".
4095  */
4096 static bool is_sym_main(const symbol_t *const sym)
4097 {
4098         return strcmp(sym->string, "main") == 0;
4099 }
4100
4101 static void error_redefined_as_different_kind(const source_position_t *pos,
4102                 const entity_t *old, entity_kind_t new_kind)
4103 {
4104         errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4105                get_entity_kind_name(old->kind), old->base.symbol,
4106                get_entity_kind_name(new_kind), &old->base.source_position);
4107 }
4108
4109 static bool is_entity_valid(entity_t *const ent)
4110 {
4111         if (is_declaration(ent)) {
4112                 return is_type_valid(skip_typeref(ent->declaration.type));
4113         } else if (ent->kind == ENTITY_TYPEDEF) {
4114                 return is_type_valid(skip_typeref(ent->typedefe.type));
4115         }
4116         return true;
4117 }
4118
4119 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4120 {
4121         for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4122                 if (attributes_equal(tattr, attr))
4123                         return true;
4124         }
4125         return false;
4126 }
4127
4128 /**
4129  * test wether new_list contains any attributes not included in old_list
4130  */
4131 static bool has_new_attributes(const attribute_t *old_list,
4132                                const attribute_t *new_list)
4133 {
4134         for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4135                 if (!contains_attribute(old_list, attr))
4136                         return true;
4137         }
4138         return false;
4139 }
4140
4141 /**
4142  * Merge in attributes from an attribute list (probably from a previous
4143  * declaration with the same name). Warning: destroys the old structure
4144  * of the attribute list - don't reuse attributes after this call.
4145  */
4146 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4147 {
4148         attribute_t *next;
4149         for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4150                 next = attr->next;
4151                 if (contains_attribute(decl->attributes, attr))
4152                         continue;
4153
4154                 /* move attribute to new declarations attributes list */
4155                 attr->next       = decl->attributes;
4156                 decl->attributes = attr;
4157         }
4158 }
4159
4160 /**
4161  * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4162  * for various problems that occur for multiple definitions
4163  */
4164 entity_t *record_entity(entity_t *entity, const bool is_definition)
4165 {
4166         const symbol_t *const    symbol  = entity->base.symbol;
4167         const namespace_tag_t    namespc = (namespace_tag_t)entity->base.namespc;
4168         const source_position_t *pos     = &entity->base.source_position;
4169
4170         /* can happen in error cases */
4171         if (symbol == NULL)
4172                 return entity;
4173
4174         entity_t *const previous_entity = get_entity(symbol, namespc);
4175         /* pushing the same entity twice will break the stack structure */
4176         assert(previous_entity != entity);
4177
4178         if (entity->kind == ENTITY_FUNCTION) {
4179                 type_t *const orig_type = entity->declaration.type;
4180                 type_t *const type      = skip_typeref(orig_type);
4181
4182                 assert(is_type_function(type));
4183                 if (type->function.unspecified_parameters &&
4184                                 warning.strict_prototypes &&
4185                                 previous_entity == NULL) {
4186                         warningf(pos, "function declaration '%#T' is not a prototype",
4187                                          orig_type, symbol);
4188                 }
4189
4190                 if (warning.main && current_scope == file_scope
4191                                 && is_sym_main(symbol)) {
4192                         check_main(entity);
4193                 }
4194         }
4195
4196         if (is_declaration(entity) &&
4197                         warning.nested_externs &&
4198                         entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4199                         current_scope != file_scope) {
4200                 warningf(pos, "nested extern declaration of '%#T'",
4201                          entity->declaration.type, symbol);
4202         }
4203
4204         if (previous_entity != NULL) {
4205                 if (previous_entity->base.parent_scope == &current_function->parameters &&
4206                                 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4207                         assert(previous_entity->kind == ENTITY_PARAMETER);
4208                         errorf(pos,
4209                                         "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4210                                         entity->declaration.type, symbol,
4211                                         previous_entity->declaration.type, symbol,
4212                                         &previous_entity->base.source_position);
4213                         goto finish;
4214                 }
4215
4216                 if (previous_entity->base.parent_scope == current_scope) {
4217                         if (previous_entity->kind != entity->kind) {
4218                                 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4219                                         error_redefined_as_different_kind(pos, previous_entity,
4220                                                         entity->kind);
4221                                 }
4222                                 goto finish;
4223                         }
4224                         if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4225                                 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4226                                                 symbol, &previous_entity->base.source_position);
4227                                 goto finish;
4228                         }
4229                         if (previous_entity->kind == ENTITY_TYPEDEF) {
4230                                 /* TODO: C++ allows this for exactly the same type */
4231                                 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4232                                                 symbol, &previous_entity->base.source_position);
4233                                 goto finish;
4234                         }
4235
4236                         /* at this point we should have only VARIABLES or FUNCTIONS */
4237                         assert(is_declaration(previous_entity) && is_declaration(entity));
4238
4239                         declaration_t *const prev_decl = &previous_entity->declaration;
4240                         declaration_t *const decl      = &entity->declaration;
4241
4242                         /* can happen for K&R style declarations */
4243                         if (prev_decl->type       == NULL             &&
4244                                         previous_entity->kind == ENTITY_PARAMETER &&
4245                                         entity->kind          == ENTITY_PARAMETER) {
4246                                 prev_decl->type                   = decl->type;
4247                                 prev_decl->storage_class          = decl->storage_class;
4248                                 prev_decl->declared_storage_class = decl->declared_storage_class;
4249                                 prev_decl->modifiers              = decl->modifiers;
4250                                 return previous_entity;
4251                         }
4252
4253                         type_t *const orig_type = decl->type;
4254                         assert(orig_type != NULL);
4255                         type_t *const type      = skip_typeref(orig_type);
4256                         type_t *const prev_type = skip_typeref(prev_decl->type);
4257
4258                         if (!types_compatible(type, prev_type)) {
4259                                 errorf(pos,
4260                                                 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4261                                                 orig_type, symbol, prev_decl->type, symbol,
4262                                                 &previous_entity->base.source_position);
4263                         } else {
4264                                 unsigned old_storage_class = prev_decl->storage_class;
4265
4266                                 if (warning.redundant_decls               &&
4267                                                 is_definition                     &&
4268                                                 !prev_decl->used                  &&
4269                                                 !(prev_decl->modifiers & DM_USED) &&
4270                                                 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4271                                         warningf(&previous_entity->base.source_position,
4272                                                         "unnecessary static forward declaration for '%#T'",
4273                                                         prev_decl->type, symbol);
4274                                 }
4275
4276                                 storage_class_t new_storage_class = decl->storage_class;
4277
4278                                 /* pretend no storage class means extern for function
4279                                  * declarations (except if the previous declaration is neither
4280                                  * none nor extern) */
4281                                 if (entity->kind == ENTITY_FUNCTION) {
4282                                         /* the previous declaration could have unspecified parameters or
4283                                          * be a typedef, so use the new type */
4284                                         if (prev_type->function.unspecified_parameters || is_definition)
4285                                                 prev_decl->type = type;
4286
4287                                         switch (old_storage_class) {
4288                                                 case STORAGE_CLASS_NONE:
4289                                                         old_storage_class = STORAGE_CLASS_EXTERN;
4290                                                         /* FALLTHROUGH */
4291
4292                                                 case STORAGE_CLASS_EXTERN:
4293                                                         if (is_definition) {
4294                                                                 if (warning.missing_prototypes &&
4295                                                                                 prev_type->function.unspecified_parameters &&
4296                                                                                 !is_sym_main(symbol)) {
4297                                                                         warningf(pos, "no previous prototype for '%#T'",
4298                                                                                         orig_type, symbol);
4299                                                                 }
4300                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
4301                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
4302                                                         }
4303                                                         break;
4304
4305                                                 default:
4306                                                         break;
4307                                         }
4308                                 } else if (is_type_incomplete(prev_type)) {
4309                                         prev_decl->type = type;
4310                                 }
4311
4312                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4313                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
4314
4315 warn_redundant_declaration: ;
4316                                         bool has_new_attrs
4317                                                 = has_new_attributes(prev_decl->attributes,
4318                                                                      decl->attributes);
4319                                         if (has_new_attrs) {
4320                                                 merge_in_attributes(decl, prev_decl->attributes);
4321                                         } else if (!is_definition        &&
4322                                                         warning.redundant_decls  &&
4323                                                         is_type_valid(prev_type) &&
4324                                                         strcmp(previous_entity->base.source_position.input_name,
4325                                                                 "<builtin>") != 0) {
4326                                                 warningf(pos,
4327                                                          "redundant declaration for '%Y' (declared %P)",
4328                                                          symbol, &previous_entity->base.source_position);
4329                                         }
4330                                 } else if (current_function == NULL) {
4331                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
4332                                                         new_storage_class == STORAGE_CLASS_STATIC) {
4333                                                 errorf(pos,
4334                                                        "static declaration of '%Y' follows non-static declaration (declared %P)",
4335                                                        symbol, &previous_entity->base.source_position);
4336                                         } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4337                                                 prev_decl->storage_class          = STORAGE_CLASS_NONE;
4338                                                 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4339                                         } else {
4340                                                 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4341                                                 if (c_mode & _CXX)
4342                                                         goto error_redeclaration;
4343                                                 goto warn_redundant_declaration;
4344                                         }
4345                                 } else if (is_type_valid(prev_type)) {
4346                                         if (old_storage_class == new_storage_class) {
4347 error_redeclaration:
4348                                                 errorf(pos, "redeclaration of '%Y' (declared %P)",
4349                                                                 symbol, &previous_entity->base.source_position);
4350                                         } else {
4351                                                 errorf(pos,
4352                                                                 "redeclaration of '%Y' with different linkage (declared %P)",
4353                                                                 symbol, &previous_entity->base.source_position);
4354                                         }
4355                                 }
4356                         }
4357
4358                         prev_decl->modifiers |= decl->modifiers;
4359                         if (entity->kind == ENTITY_FUNCTION) {
4360                                 previous_entity->function.is_inline |= entity->function.is_inline;
4361                         }
4362                         return previous_entity;
4363                 }
4364
4365                 if (warning.shadow) {
4366                         warningf(pos, "%s '%Y' shadows %s (declared %P)",
4367                                         get_entity_kind_name(entity->kind), symbol,
4368                                         get_entity_kind_name(previous_entity->kind),
4369                                         &previous_entity->base.source_position);
4370                 }
4371         }
4372
4373         if (entity->kind == ENTITY_FUNCTION) {
4374                 if (is_definition &&
4375                                 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4376                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
4377                                 warningf(pos, "no previous prototype for '%#T'",
4378                                          entity->declaration.type, symbol);
4379                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4380                                 warningf(pos, "no previous declaration for '%#T'",
4381                                          entity->declaration.type, symbol);
4382                         }
4383                 }
4384         } else if (warning.missing_declarations &&
4385                         entity->kind == ENTITY_VARIABLE &&
4386                         current_scope == file_scope) {
4387                 declaration_t *declaration = &entity->declaration;
4388                 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4389                         warningf(pos, "no previous declaration for '%#T'",
4390                                  declaration->type, symbol);
4391                 }
4392         }
4393
4394 finish:
4395         assert(entity->base.parent_scope == NULL);
4396         assert(current_scope != NULL);
4397
4398         entity->base.parent_scope = current_scope;
4399         entity->base.namespc      = NAMESPACE_NORMAL;
4400         environment_push(entity);
4401         append_entity(current_scope, entity);
4402
4403         return entity;
4404 }
4405
4406 static void parser_error_multiple_definition(entity_t *entity,
4407                 const source_position_t *source_position)
4408 {
4409         errorf(source_position, "multiple definition of '%Y' (declared %P)",
4410                entity->base.symbol, &entity->base.source_position);
4411 }
4412
4413 static bool is_declaration_specifier(const token_t *token,
4414                                      bool only_specifiers_qualifiers)
4415 {
4416         switch (token->type) {
4417                 TYPE_SPECIFIERS
4418                 TYPE_QUALIFIERS
4419                         return true;
4420                 case T_IDENTIFIER:
4421                         return is_typedef_symbol(token->symbol);
4422
4423                 case T___extension__:
4424                 STORAGE_CLASSES
4425                         return !only_specifiers_qualifiers;
4426
4427                 default:
4428                         return false;
4429         }
4430 }
4431
4432 static void parse_init_declarator_rest(entity_t *entity)
4433 {
4434         type_t *orig_type = type_error_type;
4435
4436         if (entity->base.kind == ENTITY_TYPEDEF) {
4437                 errorf(&entity->base.source_position,
4438                        "typedef '%Y' is initialized (use __typeof__ instead)",
4439                        entity->base.symbol);
4440         } else {
4441                 assert(is_declaration(entity));
4442                 orig_type = entity->declaration.type;
4443         }
4444         eat('=');
4445
4446         type_t *type = skip_typeref(orig_type);
4447
4448         if (entity->kind == ENTITY_VARIABLE
4449                         && entity->variable.initializer != NULL) {
4450                 parser_error_multiple_definition(entity, HERE);
4451         }
4452
4453         declaration_t *const declaration = &entity->declaration;
4454         bool must_be_constant = false;
4455         if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4456             entity->base.parent_scope  == file_scope) {
4457                 must_be_constant = true;
4458         }
4459
4460         if (is_type_function(type)) {
4461                 errorf(&entity->base.source_position,
4462                        "function '%#T' is initialized like a variable",
4463                        orig_type, entity->base.symbol);
4464                 orig_type = type_error_type;
4465         }
4466
4467         parse_initializer_env_t env;
4468         env.type             = orig_type;
4469         env.must_be_constant = must_be_constant;
4470         env.entity           = entity;
4471         current_init_decl    = entity;
4472
4473         initializer_t *initializer = parse_initializer(&env);
4474         current_init_decl = NULL;
4475
4476         if (entity->kind == ENTITY_VARIABLE) {
4477                 /* §6.7.5:22  array initializers for arrays with unknown size
4478                  * determine the array type size */
4479                 declaration->type            = env.type;
4480                 entity->variable.initializer = initializer;
4481         }
4482 }
4483
4484 /* parse rest of a declaration without any declarator */
4485 static void parse_anonymous_declaration_rest(
4486                 const declaration_specifiers_t *specifiers)
4487 {
4488         eat(';');
4489         anonymous_entity = NULL;
4490
4491         if (warning.other) {
4492                 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4493                                 specifiers->thread_local) {
4494                         warningf(&specifiers->source_position,
4495                                  "useless storage class in empty declaration");
4496                 }
4497
4498                 type_t *type = specifiers->type;
4499                 switch (type->kind) {
4500                         case TYPE_COMPOUND_STRUCT:
4501                         case TYPE_COMPOUND_UNION: {
4502                                 if (type->compound.compound->base.symbol == NULL) {
4503                                         warningf(&specifiers->source_position,
4504                                                  "unnamed struct/union that defines no instances");
4505                                 }
4506                                 break;
4507                         }
4508
4509                         case TYPE_ENUM:
4510                                 break;
4511
4512                         default:
4513                                 warningf(&specifiers->source_position, "empty declaration");
4514                                 break;
4515                 }
4516         }
4517 }
4518
4519 static void check_variable_type_complete(entity_t *ent)
4520 {
4521         if (ent->kind != ENTITY_VARIABLE)
4522                 return;
4523
4524         /* §6.7:7  If an identifier for an object is declared with no linkage, the
4525          *         type for the object shall be complete [...] */
4526         declaration_t *decl = &ent->declaration;
4527         if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4528                         decl->storage_class == STORAGE_CLASS_STATIC)
4529                 return;
4530
4531         type_t *const orig_type = decl->type;
4532         type_t *const type      = skip_typeref(orig_type);
4533         if (!is_type_incomplete(type))
4534                 return;
4535
4536         /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4537          * are given length one. */
4538         if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4539                 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4540                 return;
4541         }
4542
4543         errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4544                         orig_type, ent->base.symbol);
4545 }
4546
4547
4548 static void parse_declaration_rest(entity_t *ndeclaration,
4549                 const declaration_specifiers_t *specifiers,
4550                 parsed_declaration_func         finished_declaration,
4551                 declarator_flags_t              flags)
4552 {
4553         add_anchor_token(';');
4554         add_anchor_token(',');
4555         while (true) {
4556                 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4557
4558                 if (token.type == '=') {
4559                         parse_init_declarator_rest(entity);
4560                 } else if (entity->kind == ENTITY_VARIABLE) {
4561                         /* ISO/IEC 14882:1998(E) §8.5.3:3  The initializer can be omitted
4562                          * [...] where the extern specifier is explicitly used. */
4563                         declaration_t *decl = &entity->declaration;
4564                         if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4565                                 type_t *type = decl->type;
4566                                 if (is_type_reference(skip_typeref(type))) {
4567                                         errorf(&entity->base.source_position,
4568                                                         "reference '%#T' must be initialized",
4569                                                         type, entity->base.symbol);
4570                                 }
4571                         }
4572                 }
4573
4574                 check_variable_type_complete(entity);
4575
4576                 if (!next_if(','))
4577                         break;
4578
4579                 add_anchor_token('=');
4580                 ndeclaration = parse_declarator(specifiers, flags);
4581                 rem_anchor_token('=');
4582         }
4583         expect(';', end_error);
4584
4585 end_error:
4586         anonymous_entity = NULL;
4587         rem_anchor_token(';');
4588         rem_anchor_token(',');
4589 }
4590
4591 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4592 {
4593         symbol_t *symbol = entity->base.symbol;
4594         if (symbol == NULL) {
4595                 errorf(HERE, "anonymous declaration not valid as function parameter");
4596                 return entity;
4597         }
4598
4599         assert(entity->base.namespc == NAMESPACE_NORMAL);
4600         entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4601         if (previous_entity == NULL
4602                         || previous_entity->base.parent_scope != current_scope) {
4603                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4604                        symbol);
4605                 return entity;
4606         }
4607
4608         if (is_definition) {
4609                 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4610         }
4611
4612         return record_entity(entity, false);
4613 }
4614
4615 static void parse_declaration(parsed_declaration_func finished_declaration,
4616                               declarator_flags_t      flags)
4617 {
4618         declaration_specifiers_t specifiers;
4619         memset(&specifiers, 0, sizeof(specifiers));
4620
4621         add_anchor_token(';');
4622         parse_declaration_specifiers(&specifiers);
4623         rem_anchor_token(';');
4624
4625         if (token.type == ';') {
4626                 parse_anonymous_declaration_rest(&specifiers);
4627         } else {
4628                 entity_t *entity = parse_declarator(&specifiers, flags);
4629                 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4630         }
4631 }
4632
4633 /* §6.5.2.2:6 */
4634 static type_t *get_default_promoted_type(type_t *orig_type)
4635 {
4636         type_t *result = orig_type;
4637
4638         type_t *type = skip_typeref(orig_type);
4639         if (is_type_integer(type)) {
4640                 result = promote_integer(type);
4641         } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4642                 result = type_double;
4643         }
4644
4645         return result;
4646 }
4647
4648 static void parse_kr_declaration_list(entity_t *entity)
4649 {
4650         if (entity->kind != ENTITY_FUNCTION)
4651                 return;
4652
4653         type_t *type = skip_typeref(entity->declaration.type);
4654         assert(is_type_function(type));
4655         if (!type->function.kr_style_parameters)
4656                 return;
4657
4658         add_anchor_token('{');
4659
4660         /* push function parameters */
4661         size_t const  top       = environment_top();
4662         scope_t      *old_scope = scope_push(&entity->function.parameters);
4663
4664         entity_t *parameter = entity->function.parameters.entities;
4665         for ( ; parameter != NULL; parameter = parameter->base.next) {
4666                 assert(parameter->base.parent_scope == NULL);
4667                 parameter->base.parent_scope = current_scope;
4668                 environment_push(parameter);
4669         }
4670
4671         /* parse declaration list */
4672         for (;;) {
4673                 switch (token.type) {
4674                         DECLARATION_START
4675                         case T___extension__:
4676                         /* This covers symbols, which are no type, too, and results in
4677                          * better error messages.  The typical cases are misspelled type
4678                          * names and missing includes. */
4679                         case T_IDENTIFIER:
4680                                 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4681                                 break;
4682                         default:
4683                                 goto decl_list_end;
4684                 }
4685         }
4686 decl_list_end:
4687
4688         /* pop function parameters */
4689         assert(current_scope == &entity->function.parameters);
4690         scope_pop(old_scope);
4691         environment_pop_to(top);
4692
4693         /* update function type */
4694         type_t *new_type = duplicate_type(type);
4695
4696         function_parameter_t  *parameters = NULL;
4697         function_parameter_t **anchor     = &parameters;
4698
4699         /* did we have an earlier prototype? */
4700         entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4701         if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4702                 proto_type = NULL;
4703
4704         function_parameter_t *proto_parameter = NULL;
4705         if (proto_type != NULL) {
4706                 type_t *proto_type_type = proto_type->declaration.type;
4707                 proto_parameter         = proto_type_type->function.parameters;
4708                 /* If a K&R function definition has a variadic prototype earlier, then
4709                  * make the function definition variadic, too. This should conform to
4710                  * §6.7.5.3:15 and §6.9.1:8. */
4711                 new_type->function.variadic = proto_type_type->function.variadic;
4712         } else {
4713                 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4714                  * prototype */
4715                 new_type->function.unspecified_parameters = true;
4716         }
4717
4718         bool need_incompatible_warning = false;
4719         parameter = entity->function.parameters.entities;
4720         for (; parameter != NULL; parameter = parameter->base.next,
4721                         proto_parameter =
4722                                 proto_parameter == NULL ? NULL : proto_parameter->next) {
4723                 if (parameter->kind != ENTITY_PARAMETER)
4724                         continue;
4725
4726                 type_t *parameter_type = parameter->declaration.type;
4727                 if (parameter_type == NULL) {
4728                         if (strict_mode) {
4729                                 errorf(HERE, "no type specified for function parameter '%Y'",
4730                                        parameter->base.symbol);
4731                                 parameter_type = type_error_type;
4732                         } else {
4733                                 if (warning.implicit_int) {
4734                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4735                                                  parameter->base.symbol);
4736                                 }
4737                                 parameter_type = type_int;
4738                         }
4739                         parameter->declaration.type = parameter_type;
4740                 }
4741
4742                 semantic_parameter_incomplete(parameter);
4743
4744                 /* we need the default promoted types for the function type */
4745                 type_t *not_promoted = parameter_type;
4746                 parameter_type       = get_default_promoted_type(parameter_type);
4747
4748                 /* gcc special: if the type of the prototype matches the unpromoted
4749                  * type don't promote */
4750                 if (!strict_mode && proto_parameter != NULL) {
4751                         type_t *proto_p_type = skip_typeref(proto_parameter->type);
4752                         type_t *promo_skip   = skip_typeref(parameter_type);
4753                         type_t *param_skip   = skip_typeref(not_promoted);
4754                         if (!types_compatible(proto_p_type, promo_skip)
4755                                 && types_compatible(proto_p_type, param_skip)) {
4756                                 /* don't promote */
4757                                 need_incompatible_warning = true;
4758                                 parameter_type = not_promoted;
4759                         }
4760                 }
4761                 function_parameter_t *const parameter
4762                         = allocate_parameter(parameter_type);
4763
4764                 *anchor = parameter;
4765                 anchor  = &parameter->next;
4766         }
4767
4768         new_type->function.parameters = parameters;
4769         new_type = identify_new_type(new_type);
4770
4771         if (warning.other && need_incompatible_warning) {
4772                 type_t *proto_type_type = proto_type->declaration.type;
4773                 warningf(HERE,
4774                          "declaration '%#T' is incompatible with '%#T' (declared %P)",
4775                          proto_type_type, proto_type->base.symbol,
4776                          new_type, entity->base.symbol,
4777                          &proto_type->base.source_position);
4778         }
4779
4780         entity->declaration.type = new_type;
4781
4782         rem_anchor_token('{');
4783 }
4784
4785 static bool first_err = true;
4786
4787 /**
4788  * When called with first_err set, prints the name of the current function,
4789  * else does noting.
4790  */
4791 static void print_in_function(void)
4792 {
4793         if (first_err) {
4794                 first_err = false;
4795                 diagnosticf("%s: In function '%Y':\n",
4796                             current_function->base.base.source_position.input_name,
4797                             current_function->base.base.symbol);
4798         }
4799 }
4800
4801 /**
4802  * Check if all labels are defined in the current function.
4803  * Check if all labels are used in the current function.
4804  */
4805 static void check_labels(void)
4806 {
4807         for (const goto_statement_t *goto_statement = goto_first;
4808             goto_statement != NULL;
4809             goto_statement = goto_statement->next) {
4810                 /* skip computed gotos */
4811                 if (goto_statement->expression != NULL)
4812                         continue;
4813
4814                 label_t *label = goto_statement->label;
4815
4816                 label->used = true;
4817                 if (label->base.source_position.input_name == NULL) {
4818                         print_in_function();
4819                         errorf(&goto_statement->base.source_position,
4820                                "label '%Y' used but not defined", label->base.symbol);
4821                  }
4822         }
4823
4824         if (warning.unused_label) {
4825                 for (const label_statement_t *label_statement = label_first;
4826                          label_statement != NULL;
4827                          label_statement = label_statement->next) {
4828                         label_t *label = label_statement->label;
4829
4830                         if (! label->used) {
4831                                 print_in_function();
4832                                 warningf(&label_statement->base.source_position,
4833                                          "label '%Y' defined but not used", label->base.symbol);
4834                         }
4835                 }
4836         }
4837 }
4838
4839 static void warn_unused_entity(entity_t *entity, entity_t *last)
4840 {
4841         entity_t const *const end = last != NULL ? last->base.next : NULL;
4842         for (; entity != end; entity = entity->base.next) {
4843                 if (!is_declaration(entity))
4844                         continue;
4845
4846                 declaration_t *declaration = &entity->declaration;
4847                 if (declaration->implicit)
4848                         continue;
4849
4850                 if (!declaration->used) {
4851                         print_in_function();
4852                         const char *what = get_entity_kind_name(entity->kind);
4853                         warningf(&entity->base.source_position, "%s '%Y' is unused",
4854                                  what, entity->base.symbol);
4855                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4856                         print_in_function();
4857                         const char *what = get_entity_kind_name(entity->kind);
4858                         warningf(&entity->base.source_position, "%s '%Y' is never read",
4859                                  what, entity->base.symbol);
4860                 }
4861         }
4862 }
4863
4864 static void check_unused_variables(statement_t *const stmt, void *const env)
4865 {
4866         (void)env;
4867
4868         switch (stmt->kind) {
4869                 case STATEMENT_DECLARATION: {
4870                         declaration_statement_t const *const decls = &stmt->declaration;
4871                         warn_unused_entity(decls->declarations_begin,
4872                                            decls->declarations_end);
4873                         return;
4874                 }
4875
4876                 case STATEMENT_FOR:
4877                         warn_unused_entity(stmt->fors.scope.entities, NULL);
4878                         return;
4879
4880                 default:
4881                         return;
4882         }
4883 }
4884
4885 /**
4886  * Check declarations of current_function for unused entities.
4887  */
4888 static void check_declarations(void)
4889 {
4890         if (warning.unused_parameter) {
4891                 const scope_t *scope = &current_function->parameters;
4892
4893                 /* do not issue unused warnings for main */
4894                 if (!is_sym_main(current_function->base.base.symbol)) {
4895                         warn_unused_entity(scope->entities, NULL);
4896                 }
4897         }
4898         if (warning.unused_variable) {
4899                 walk_statements(current_function->statement, check_unused_variables,
4900                                 NULL);
4901         }
4902 }
4903
4904 static int determine_truth(expression_t const* const cond)
4905 {
4906         return
4907                 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4908                 fold_constant_to_bool(cond)                         ? 1 :
4909                 -1;
4910 }
4911
4912 static void check_reachable(statement_t *);
4913 static bool reaches_end;
4914
4915 static bool expression_returns(expression_t const *const expr)
4916 {
4917         switch (expr->kind) {
4918                 case EXPR_CALL: {
4919                         expression_t const *const func = expr->call.function;
4920                         if (func->kind == EXPR_REFERENCE) {
4921                                 entity_t *entity = func->reference.entity;
4922                                 if (entity->kind == ENTITY_FUNCTION
4923                                                 && entity->declaration.modifiers & DM_NORETURN)
4924                                         return false;
4925                         }
4926
4927                         if (!expression_returns(func))
4928                                 return false;
4929
4930                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4931                                 if (!expression_returns(arg->expression))
4932                                         return false;
4933                         }
4934
4935                         return true;
4936                 }
4937
4938                 case EXPR_REFERENCE:
4939                 case EXPR_REFERENCE_ENUM_VALUE:
4940                 EXPR_LITERAL_CASES
4941                 case EXPR_STRING_LITERAL:
4942                 case EXPR_WIDE_STRING_LITERAL:
4943                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4944                 case EXPR_LABEL_ADDRESS:
4945                 case EXPR_CLASSIFY_TYPE:
4946                 case EXPR_SIZEOF: // TODO handle obscure VLA case
4947                 case EXPR_ALIGNOF:
4948                 case EXPR_FUNCNAME:
4949                 case EXPR_BUILTIN_CONSTANT_P:
4950                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4951                 case EXPR_OFFSETOF:
4952                 case EXPR_INVALID:
4953                         return true;
4954
4955                 case EXPR_STATEMENT: {
4956                         bool old_reaches_end = reaches_end;
4957                         reaches_end = false;
4958                         check_reachable(expr->statement.statement);
4959                         bool returns = reaches_end;
4960                         reaches_end = old_reaches_end;
4961                         return returns;
4962                 }
4963
4964                 case EXPR_CONDITIONAL:
4965                         // TODO handle constant expression
4966
4967                         if (!expression_returns(expr->conditional.condition))
4968                                 return false;
4969
4970                         if (expr->conditional.true_expression != NULL
4971                                         && expression_returns(expr->conditional.true_expression))
4972                                 return true;
4973
4974                         return expression_returns(expr->conditional.false_expression);
4975
4976                 case EXPR_SELECT:
4977                         return expression_returns(expr->select.compound);
4978
4979                 case EXPR_ARRAY_ACCESS:
4980                         return
4981                                 expression_returns(expr->array_access.array_ref) &&
4982                                 expression_returns(expr->array_access.index);
4983
4984                 case EXPR_VA_START:
4985                         return expression_returns(expr->va_starte.ap);
4986
4987                 case EXPR_VA_ARG:
4988                         return expression_returns(expr->va_arge.ap);
4989
4990                 case EXPR_VA_COPY:
4991                         return expression_returns(expr->va_copye.src);
4992
4993                 EXPR_UNARY_CASES_MANDATORY
4994                         return expression_returns(expr->unary.value);
4995
4996                 case EXPR_UNARY_THROW:
4997                         return false;
4998
4999                 EXPR_BINARY_CASES
5000                         // TODO handle constant lhs of && and ||
5001                         return
5002                                 expression_returns(expr->binary.left) &&
5003                                 expression_returns(expr->binary.right);
5004
5005                 case EXPR_UNKNOWN:
5006                         break;
5007         }
5008
5009         panic("unhandled expression");
5010 }
5011
5012 static bool initializer_returns(initializer_t const *const init)
5013 {
5014         switch (init->kind) {
5015                 case INITIALIZER_VALUE:
5016                         return expression_returns(init->value.value);
5017
5018                 case INITIALIZER_LIST: {
5019                         initializer_t * const*       i       = init->list.initializers;
5020                         initializer_t * const* const end     = i + init->list.len;
5021                         bool                         returns = true;
5022                         for (; i != end; ++i) {
5023                                 if (!initializer_returns(*i))
5024                                         returns = false;
5025                         }
5026                         return returns;
5027                 }
5028
5029                 case INITIALIZER_STRING:
5030                 case INITIALIZER_WIDE_STRING:
5031                 case INITIALIZER_DESIGNATOR: // designators have no payload
5032                         return true;
5033         }
5034         panic("unhandled initializer");
5035 }
5036
5037 static bool noreturn_candidate;
5038
5039 static void check_reachable(statement_t *const stmt)
5040 {
5041         if (stmt->base.reachable)
5042                 return;
5043         if (stmt->kind != STATEMENT_DO_WHILE)
5044                 stmt->base.reachable = true;
5045
5046         statement_t *last = stmt;
5047         statement_t *next;
5048         switch (stmt->kind) {
5049                 case STATEMENT_INVALID:
5050                 case STATEMENT_EMPTY:
5051                 case STATEMENT_ASM:
5052                         next = stmt->base.next;
5053                         break;
5054
5055                 case STATEMENT_DECLARATION: {
5056                         declaration_statement_t const *const decl = &stmt->declaration;
5057                         entity_t                const *      ent  = decl->declarations_begin;
5058                         entity_t                const *const last = decl->declarations_end;
5059                         if (ent != NULL) {
5060                                 for (;; ent = ent->base.next) {
5061                                         if (ent->kind                 == ENTITY_VARIABLE &&
5062                                                         ent->variable.initializer != NULL            &&
5063                                                         !initializer_returns(ent->variable.initializer)) {
5064                                                 return;
5065                                         }
5066                                         if (ent == last)
5067                                                 break;
5068                                 }
5069                         }
5070                         next = stmt->base.next;
5071                         break;
5072                 }
5073
5074                 case STATEMENT_COMPOUND:
5075                         next = stmt->compound.statements;
5076                         if (next == NULL)
5077                                 next = stmt->base.next;
5078                         break;
5079
5080                 case STATEMENT_RETURN: {
5081                         expression_t const *const val = stmt->returns.value;
5082                         if (val == NULL || expression_returns(val))
5083                                 noreturn_candidate = false;
5084                         return;
5085                 }
5086
5087                 case STATEMENT_IF: {
5088                         if_statement_t const *const ifs  = &stmt->ifs;
5089                         expression_t   const *const cond = ifs->condition;
5090
5091                         if (!expression_returns(cond))
5092                                 return;
5093
5094                         int const val = determine_truth(cond);
5095
5096                         if (val >= 0)
5097                                 check_reachable(ifs->true_statement);
5098
5099                         if (val > 0)
5100                                 return;
5101
5102                         if (ifs->false_statement != NULL) {
5103                                 check_reachable(ifs->false_statement);
5104                                 return;
5105                         }
5106
5107                         next = stmt->base.next;
5108                         break;
5109                 }
5110
5111                 case STATEMENT_SWITCH: {
5112                         switch_statement_t const *const switchs = &stmt->switchs;
5113                         expression_t       const *const expr    = switchs->expression;
5114
5115                         if (!expression_returns(expr))
5116                                 return;
5117
5118                         if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5119                                 long                    const val      = fold_constant_to_int(expr);
5120                                 case_label_statement_t *      defaults = NULL;
5121                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5122                                         if (i->expression == NULL) {
5123                                                 defaults = i;
5124                                                 continue;
5125                                         }
5126
5127                                         if (i->first_case <= val && val <= i->last_case) {
5128                                                 check_reachable((statement_t*)i);
5129                                                 return;
5130                                         }
5131                                 }
5132
5133                                 if (defaults != NULL) {
5134                                         check_reachable((statement_t*)defaults);
5135                                         return;
5136                                 }
5137                         } else {
5138                                 bool has_default = false;
5139                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5140                                         if (i->expression == NULL)
5141                                                 has_default = true;
5142
5143                                         check_reachable((statement_t*)i);
5144                                 }
5145
5146                                 if (has_default)
5147                                         return;
5148                         }
5149
5150                         next = stmt->base.next;
5151                         break;
5152                 }
5153
5154                 case STATEMENT_EXPRESSION: {
5155                         /* Check for noreturn function call */
5156                         expression_t const *const expr = stmt->expression.expression;
5157                         if (!expression_returns(expr))
5158                                 return;
5159
5160                         next = stmt->base.next;
5161                         break;
5162                 }
5163
5164                 case STATEMENT_CONTINUE:
5165                         for (statement_t *parent = stmt;;) {
5166                                 parent = parent->base.parent;
5167                                 if (parent == NULL) /* continue not within loop */
5168                                         return;
5169
5170                                 next = parent;
5171                                 switch (parent->kind) {
5172                                         case STATEMENT_WHILE:    goto continue_while;
5173                                         case STATEMENT_DO_WHILE: goto continue_do_while;
5174                                         case STATEMENT_FOR:      goto continue_for;
5175
5176                                         default: break;
5177                                 }
5178                         }
5179
5180                 case STATEMENT_BREAK:
5181                         for (statement_t *parent = stmt;;) {
5182                                 parent = parent->base.parent;
5183                                 if (parent == NULL) /* break not within loop/switch */
5184                                         return;
5185
5186                                 switch (parent->kind) {
5187                                         case STATEMENT_SWITCH:
5188                                         case STATEMENT_WHILE:
5189                                         case STATEMENT_DO_WHILE:
5190                                         case STATEMENT_FOR:
5191                                                 last = parent;
5192                                                 next = parent->base.next;
5193                                                 goto found_break_parent;
5194
5195                                         default: break;
5196                                 }
5197                         }
5198 found_break_parent:
5199                         break;
5200
5201                 case STATEMENT_GOTO:
5202                         if (stmt->gotos.expression) {
5203                                 if (!expression_returns(stmt->gotos.expression))
5204                                         return;
5205
5206                                 statement_t *parent = stmt->base.parent;
5207                                 if (parent == NULL) /* top level goto */
5208                                         return;
5209                                 next = parent;
5210                         } else {
5211                                 next = stmt->gotos.label->statement;
5212                                 if (next == NULL) /* missing label */
5213                                         return;
5214                         }
5215                         break;
5216
5217                 case STATEMENT_LABEL:
5218                         next = stmt->label.statement;
5219                         break;
5220
5221                 case STATEMENT_CASE_LABEL:
5222                         next = stmt->case_label.statement;
5223                         break;
5224
5225                 case STATEMENT_WHILE: {
5226                         while_statement_t const *const whiles = &stmt->whiles;
5227                         expression_t      const *const cond   = whiles->condition;
5228
5229                         if (!expression_returns(cond))
5230                                 return;
5231
5232                         int const val = determine_truth(cond);
5233
5234                         if (val >= 0)
5235                                 check_reachable(whiles->body);
5236
5237                         if (val > 0)
5238                                 return;
5239
5240                         next = stmt->base.next;
5241                         break;
5242                 }
5243
5244                 case STATEMENT_DO_WHILE:
5245                         next = stmt->do_while.body;
5246                         break;
5247
5248                 case STATEMENT_FOR: {
5249                         for_statement_t *const fors = &stmt->fors;
5250
5251                         if (fors->condition_reachable)
5252                                 return;
5253                         fors->condition_reachable = true;
5254
5255                         expression_t const *const cond = fors->condition;
5256
5257                         int val;
5258                         if (cond == NULL) {
5259                                 val = 1;
5260                         } else if (expression_returns(cond)) {
5261                                 val = determine_truth(cond);
5262                         } else {
5263                                 return;
5264                         }
5265
5266                         if (val >= 0)
5267                                 check_reachable(fors->body);
5268
5269                         if (val > 0)
5270                                 return;
5271
5272                         next = stmt->base.next;
5273                         break;
5274                 }
5275
5276                 case STATEMENT_MS_TRY: {
5277                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
5278                         check_reachable(ms_try->try_statement);
5279                         next = ms_try->final_statement;
5280                         break;
5281                 }
5282
5283                 case STATEMENT_LEAVE: {
5284                         statement_t *parent = stmt;
5285                         for (;;) {
5286                                 parent = parent->base.parent;
5287                                 if (parent == NULL) /* __leave not within __try */
5288                                         return;
5289
5290                                 if (parent->kind == STATEMENT_MS_TRY) {
5291                                         last = parent;
5292                                         next = parent->ms_try.final_statement;
5293                                         break;
5294                                 }
5295                         }
5296                         break;
5297                 }
5298
5299                 default:
5300                         panic("invalid statement kind");
5301         }
5302
5303         while (next == NULL) {
5304                 next = last->base.parent;
5305                 if (next == NULL) {
5306                         noreturn_candidate = false;
5307
5308                         type_t *const type = skip_typeref(current_function->base.type);
5309                         assert(is_type_function(type));
5310                         type_t *const ret  = skip_typeref(type->function.return_type);
5311                         if (warning.return_type                    &&
5312                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5313                             is_type_valid(ret)                     &&
5314                             !is_sym_main(current_function->base.base.symbol)) {
5315                                 warningf(&stmt->base.source_position,
5316                                          "control reaches end of non-void function");
5317                         }
5318                         return;
5319                 }
5320
5321                 switch (next->kind) {
5322                         case STATEMENT_INVALID:
5323                         case STATEMENT_EMPTY:
5324                         case STATEMENT_DECLARATION:
5325                         case STATEMENT_EXPRESSION:
5326                         case STATEMENT_ASM:
5327                         case STATEMENT_RETURN:
5328                         case STATEMENT_CONTINUE:
5329                         case STATEMENT_BREAK:
5330                         case STATEMENT_GOTO:
5331                         case STATEMENT_LEAVE:
5332                                 panic("invalid control flow in function");
5333
5334                         case STATEMENT_COMPOUND:
5335                                 if (next->compound.stmt_expr) {
5336                                         reaches_end = true;
5337                                         return;
5338                                 }
5339                                 /* FALLTHROUGH */
5340                         case STATEMENT_IF:
5341                         case STATEMENT_SWITCH:
5342                         case STATEMENT_LABEL:
5343                         case STATEMENT_CASE_LABEL:
5344                                 last = next;
5345                                 next = next->base.next;
5346                                 break;
5347
5348                         case STATEMENT_WHILE: {
5349 continue_while:
5350                                 if (next->base.reachable)
5351                                         return;
5352                                 next->base.reachable = true;
5353
5354                                 while_statement_t const *const whiles = &next->whiles;
5355                                 expression_t      const *const cond   = whiles->condition;
5356
5357                                 if (!expression_returns(cond))
5358                                         return;
5359
5360                                 int const val = determine_truth(cond);
5361
5362                                 if (val >= 0)
5363                                         check_reachable(whiles->body);
5364
5365                                 if (val > 0)
5366                                         return;
5367
5368                                 last = next;
5369                                 next = next->base.next;
5370                                 break;
5371                         }
5372
5373                         case STATEMENT_DO_WHILE: {
5374 continue_do_while:
5375                                 if (next->base.reachable)
5376                                         return;
5377                                 next->base.reachable = true;
5378
5379                                 do_while_statement_t const *const dw   = &next->do_while;
5380                                 expression_t         const *const cond = dw->condition;
5381
5382                                 if (!expression_returns(cond))
5383                                         return;
5384
5385                                 int const val = determine_truth(cond);
5386
5387                                 if (val >= 0)
5388                                         check_reachable(dw->body);
5389
5390                                 if (val > 0)
5391                                         return;
5392
5393                                 last = next;
5394                                 next = next->base.next;
5395                                 break;
5396                         }
5397
5398                         case STATEMENT_FOR: {
5399 continue_for:;
5400                                 for_statement_t *const fors = &next->fors;
5401
5402                                 fors->step_reachable = true;
5403
5404                                 if (fors->condition_reachable)
5405                                         return;
5406                                 fors->condition_reachable = true;
5407
5408                                 expression_t const *const cond = fors->condition;
5409
5410                                 int val;
5411                                 if (cond == NULL) {
5412                                         val = 1;
5413                                 } else if (expression_returns(cond)) {
5414                                         val = determine_truth(cond);
5415                                 } else {
5416                                         return;
5417                                 }
5418
5419                                 if (val >= 0)
5420                                         check_reachable(fors->body);
5421
5422                                 if (val > 0)
5423                                         return;
5424
5425                                 last = next;
5426                                 next = next->base.next;
5427                                 break;
5428                         }
5429
5430                         case STATEMENT_MS_TRY:
5431                                 last = next;
5432                                 next = next->ms_try.final_statement;
5433                                 break;
5434                 }
5435         }
5436
5437         check_reachable(next);
5438 }
5439
5440 static void check_unreachable(statement_t* const stmt, void *const env)
5441 {
5442         (void)env;
5443
5444         switch (stmt->kind) {
5445                 case STATEMENT_DO_WHILE:
5446                         if (!stmt->base.reachable) {
5447                                 expression_t const *const cond = stmt->do_while.condition;
5448                                 if (determine_truth(cond) >= 0) {
5449                                         warningf(&cond->base.source_position,
5450                                                  "condition of do-while-loop is unreachable");
5451                                 }
5452                         }
5453                         return;
5454
5455                 case STATEMENT_FOR: {
5456                         for_statement_t const* const fors = &stmt->fors;
5457
5458                         // if init and step are unreachable, cond is unreachable, too
5459                         if (!stmt->base.reachable && !fors->step_reachable) {
5460                                 warningf(&stmt->base.source_position, "statement is unreachable");
5461                         } else {
5462                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
5463                                         warningf(&fors->initialisation->base.source_position,
5464                                                  "initialisation of for-statement is unreachable");
5465                                 }
5466
5467                                 if (!fors->condition_reachable && fors->condition != NULL) {
5468                                         warningf(&fors->condition->base.source_position,
5469                                                  "condition of for-statement is unreachable");
5470                                 }
5471
5472                                 if (!fors->step_reachable && fors->step != NULL) {
5473                                         warningf(&fors->step->base.source_position,
5474                                                  "step of for-statement is unreachable");
5475                                 }
5476                         }
5477                         return;
5478                 }
5479
5480                 case STATEMENT_COMPOUND:
5481                         if (stmt->compound.statements != NULL)
5482                                 return;
5483                         goto warn_unreachable;
5484
5485                 case STATEMENT_DECLARATION: {
5486                         /* Only warn if there is at least one declarator with an initializer.
5487                          * This typically occurs in switch statements. */
5488                         declaration_statement_t const *const decl = &stmt->declaration;
5489                         entity_t                const *      ent  = decl->declarations_begin;
5490                         entity_t                const *const last = decl->declarations_end;
5491                         if (ent != NULL) {
5492                                 for (;; ent = ent->base.next) {
5493                                         if (ent->kind                 == ENTITY_VARIABLE &&
5494                                                         ent->variable.initializer != NULL) {
5495                                                 goto warn_unreachable;
5496                                         }
5497                                         if (ent == last)
5498                                                 return;
5499                                 }
5500                         }
5501                 }
5502
5503                 default:
5504 warn_unreachable:
5505                         if (!stmt->base.reachable)
5506                                 warningf(&stmt->base.source_position, "statement is unreachable");
5507                         return;
5508         }
5509 }
5510
5511 static void parse_external_declaration(void)
5512 {
5513         /* function-definitions and declarations both start with declaration
5514          * specifiers */
5515         declaration_specifiers_t specifiers;
5516         memset(&specifiers, 0, sizeof(specifiers));
5517
5518         add_anchor_token(';');
5519         parse_declaration_specifiers(&specifiers);
5520         rem_anchor_token(';');
5521
5522         /* must be a declaration */
5523         if (token.type == ';') {
5524                 parse_anonymous_declaration_rest(&specifiers);
5525                 return;
5526         }
5527
5528         add_anchor_token(',');
5529         add_anchor_token('=');
5530         add_anchor_token(';');
5531         add_anchor_token('{');
5532
5533         /* declarator is common to both function-definitions and declarations */
5534         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5535
5536         rem_anchor_token('{');
5537         rem_anchor_token(';');
5538         rem_anchor_token('=');
5539         rem_anchor_token(',');
5540
5541         /* must be a declaration */
5542         switch (token.type) {
5543                 case ',':
5544                 case ';':
5545                 case '=':
5546                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5547                                         DECL_FLAGS_NONE);
5548                         return;
5549         }
5550
5551         /* must be a function definition */
5552         parse_kr_declaration_list(ndeclaration);
5553
5554         if (token.type != '{') {
5555                 parse_error_expected("while parsing function definition", '{', NULL);
5556                 eat_until_matching_token(';');
5557                 return;
5558         }
5559
5560         assert(is_declaration(ndeclaration));
5561         type_t *const orig_type = ndeclaration->declaration.type;
5562         type_t *      type      = skip_typeref(orig_type);
5563
5564         if (!is_type_function(type)) {
5565                 if (is_type_valid(type)) {
5566                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
5567                                type, ndeclaration->base.symbol);
5568                 }
5569                 eat_block();
5570                 return;
5571         } else if (is_typeref(orig_type)) {
5572                 /* §6.9.1:2 */
5573                 errorf(&ndeclaration->base.source_position,
5574                                 "type of function definition '%#T' is a typedef",
5575                                 orig_type, ndeclaration->base.symbol);
5576         }
5577
5578         if (warning.aggregate_return &&
5579             is_type_compound(skip_typeref(type->function.return_type))) {
5580                 warningf(HERE, "function '%Y' returns an aggregate",
5581                          ndeclaration->base.symbol);
5582         }
5583         if (warning.traditional && !type->function.unspecified_parameters) {
5584                 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5585                         ndeclaration->base.symbol);
5586         }
5587         if (warning.old_style_definition && type->function.unspecified_parameters) {
5588                 warningf(HERE, "old-style function definition '%Y'",
5589                         ndeclaration->base.symbol);
5590         }
5591
5592         /* §6.7.5.3:14 a function definition with () means no
5593          * parameters (and not unspecified parameters) */
5594         if (type->function.unspecified_parameters &&
5595                         type->function.parameters == NULL) {
5596                 type_t *copy                          = duplicate_type(type);
5597                 copy->function.unspecified_parameters = false;
5598                 type                                  = identify_new_type(copy);
5599
5600                 ndeclaration->declaration.type = type;
5601         }
5602
5603         entity_t *const entity = record_entity(ndeclaration, true);
5604         assert(entity->kind == ENTITY_FUNCTION);
5605         assert(ndeclaration->kind == ENTITY_FUNCTION);
5606
5607         function_t *const function = &entity->function;
5608         if (ndeclaration != entity) {
5609                 function->parameters = ndeclaration->function.parameters;
5610         }
5611         assert(is_declaration(entity));
5612         type = skip_typeref(entity->declaration.type);
5613
5614         /* push function parameters and switch scope */
5615         size_t const  top       = environment_top();
5616         scope_t      *old_scope = scope_push(&function->parameters);
5617
5618         entity_t *parameter = function->parameters.entities;
5619         for (; parameter != NULL; parameter = parameter->base.next) {
5620                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5621                         parameter->base.parent_scope = current_scope;
5622                 }
5623                 assert(parameter->base.parent_scope == NULL
5624                                 || parameter->base.parent_scope == current_scope);
5625                 parameter->base.parent_scope = current_scope;
5626                 if (parameter->base.symbol == NULL) {
5627                         errorf(&parameter->base.source_position, "parameter name omitted");
5628                         continue;
5629                 }
5630                 environment_push(parameter);
5631         }
5632
5633         if (function->statement != NULL) {
5634                 parser_error_multiple_definition(entity, HERE);
5635                 eat_block();
5636         } else {
5637                 /* parse function body */
5638                 int         label_stack_top      = label_top();
5639                 function_t *old_current_function = current_function;
5640                 entity_t   *old_current_entity   = current_entity;
5641                 current_function                 = function;
5642                 current_entity                   = entity;
5643                 current_parent                   = NULL;
5644
5645                 goto_first   = NULL;
5646                 goto_anchor  = &goto_first;
5647                 label_first  = NULL;
5648                 label_anchor = &label_first;
5649
5650                 statement_t *const body = parse_compound_statement(false);
5651                 function->statement = body;
5652                 first_err = true;
5653                 check_labels();
5654                 check_declarations();
5655                 if (warning.return_type      ||
5656                     warning.unreachable_code ||
5657                     (warning.missing_noreturn
5658                      && !(function->base.modifiers & DM_NORETURN))) {
5659                         noreturn_candidate = true;
5660                         check_reachable(body);
5661                         if (warning.unreachable_code)
5662                                 walk_statements(body, check_unreachable, NULL);
5663                         if (warning.missing_noreturn &&
5664                             noreturn_candidate       &&
5665                             !(function->base.modifiers & DM_NORETURN)) {
5666                                 warningf(&body->base.source_position,
5667                                          "function '%#T' is candidate for attribute 'noreturn'",
5668                                          type, entity->base.symbol);
5669                         }
5670                 }
5671
5672                 assert(current_parent   == NULL);
5673                 assert(current_function == function);
5674                 assert(current_entity   == entity);
5675                 current_entity   = old_current_entity;
5676                 current_function = old_current_function;
5677                 label_pop_to(label_stack_top);
5678         }
5679
5680         assert(current_scope == &function->parameters);
5681         scope_pop(old_scope);
5682         environment_pop_to(top);
5683 }
5684
5685 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5686                                   source_position_t *source_position,
5687                                   const symbol_t *symbol)
5688 {
5689         type_t *type = allocate_type_zero(TYPE_BITFIELD);
5690
5691         type->bitfield.base_type       = base_type;
5692         type->bitfield.size_expression = size;
5693
5694         il_size_t bit_size;
5695         type_t *skipped_type = skip_typeref(base_type);
5696         if (!is_type_integer(skipped_type)) {
5697                 errorf(HERE, "bitfield base type '%T' is not an integer type",
5698                        base_type);
5699                 bit_size = 0;
5700         } else {
5701                 bit_size = get_type_size(base_type) * 8;
5702         }
5703
5704         if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5705                 long v = fold_constant_to_int(size);
5706                 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5707
5708                 if (v < 0) {
5709                         errorf(source_position, "negative width in bit-field '%Y'",
5710                                user_symbol);
5711                 } else if (v == 0 && symbol != NULL) {
5712                         errorf(source_position, "zero width for bit-field '%Y'",
5713                                user_symbol);
5714                 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5715                         errorf(source_position, "width of '%Y' exceeds its type",
5716                                user_symbol);
5717                 } else {
5718                         type->bitfield.bit_size = v;
5719                 }
5720         }
5721
5722         return type;
5723 }
5724
5725 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5726 {
5727         entity_t *iter = compound->members.entities;
5728         for (; iter != NULL; iter = iter->base.next) {
5729                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5730                         continue;
5731
5732                 if (iter->base.symbol == symbol) {
5733                         return iter;
5734                 } else if (iter->base.symbol == NULL) {
5735                         /* search in anonymous structs and unions */
5736                         type_t *type = skip_typeref(iter->declaration.type);
5737                         if (is_type_compound(type)) {
5738                                 if (find_compound_entry(type->compound.compound, symbol)
5739                                                 != NULL)
5740                                         return iter;
5741                         }
5742                         continue;
5743                 }
5744         }
5745
5746         return NULL;
5747 }
5748
5749 static void check_deprecated(const source_position_t *source_position,
5750                              const entity_t *entity)
5751 {
5752         if (!warning.deprecated_declarations)
5753                 return;
5754         if (!is_declaration(entity))
5755                 return;
5756         if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5757                 return;
5758
5759         char const *const prefix = get_entity_kind_name(entity->kind);
5760         const char *deprecated_string
5761                         = get_deprecated_string(entity->declaration.attributes);
5762         if (deprecated_string != NULL) {
5763                 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5764                                  prefix, entity->base.symbol, &entity->base.source_position,
5765                                  deprecated_string);
5766         } else {
5767                 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5768                                  entity->base.symbol, &entity->base.source_position);
5769         }
5770 }
5771
5772
5773 static expression_t *create_select(const source_position_t *pos,
5774                                    expression_t *addr,
5775                                    type_qualifiers_t qualifiers,
5776                                                                    entity_t *entry)
5777 {
5778         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5779
5780         check_deprecated(pos, entry);
5781
5782         expression_t *select          = allocate_expression_zero(EXPR_SELECT);
5783         select->select.compound       = addr;
5784         select->select.compound_entry = entry;
5785
5786         type_t *entry_type = entry->declaration.type;
5787         type_t *res_type   = get_qualified_type(entry_type, qualifiers);
5788
5789         /* we always do the auto-type conversions; the & and sizeof parser contains
5790          * code to revert this! */
5791         select->base.type = automatic_type_conversion(res_type);
5792         if (res_type->kind == TYPE_BITFIELD) {
5793                 select->base.type = res_type->bitfield.base_type;
5794         }
5795
5796         return select;
5797 }
5798
5799 /**
5800  * Find entry with symbol in compound. Search anonymous structs and unions and
5801  * creates implicit select expressions for them.
5802  * Returns the adress for the innermost compound.
5803  */
5804 static expression_t *find_create_select(const source_position_t *pos,
5805                                         expression_t *addr,
5806                                         type_qualifiers_t qualifiers,
5807                                         compound_t *compound, symbol_t *symbol)
5808 {
5809         entity_t *iter = compound->members.entities;
5810         for (; iter != NULL; iter = iter->base.next) {
5811                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5812                         continue;
5813
5814                 symbol_t *iter_symbol = iter->base.symbol;
5815                 if (iter_symbol == NULL) {
5816                         type_t *type = iter->declaration.type;
5817                         if (type->kind != TYPE_COMPOUND_STRUCT
5818                                         && type->kind != TYPE_COMPOUND_UNION)
5819                                 continue;
5820
5821                         compound_t *sub_compound = type->compound.compound;
5822
5823                         if (find_compound_entry(sub_compound, symbol) == NULL)
5824                                 continue;
5825
5826                         expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5827                         sub_addr->base.source_position = *pos;
5828                         sub_addr->select.implicit      = true;
5829                         return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5830                                                   symbol);
5831                 }
5832
5833                 if (iter_symbol == symbol) {
5834                         return create_select(pos, addr, qualifiers, iter);
5835                 }
5836         }
5837
5838         return NULL;
5839 }
5840
5841 static void parse_compound_declarators(compound_t *compound,
5842                 const declaration_specifiers_t *specifiers)
5843 {
5844         do {
5845                 entity_t *entity;
5846
5847                 if (token.type == ':') {
5848                         source_position_t source_position = *HERE;
5849                         next_token();
5850
5851                         type_t *base_type = specifiers->type;
5852                         expression_t *size = parse_constant_expression();
5853
5854                         type_t *type = make_bitfield_type(base_type, size,
5855                                         &source_position, NULL);
5856
5857                         attribute_t  *attributes = parse_attributes(NULL);
5858                         attribute_t **anchor     = &attributes;
5859                         while (*anchor != NULL)
5860                                 anchor = &(*anchor)->next;
5861                         *anchor = specifiers->attributes;
5862
5863                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5864                         entity->base.namespc                       = NAMESPACE_NORMAL;
5865                         entity->base.source_position               = source_position;
5866                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5867                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
5868                         entity->declaration.type                   = type;
5869                         entity->declaration.attributes             = attributes;
5870
5871                         if (attributes != NULL) {
5872                                 handle_entity_attributes(attributes, entity);
5873                         }
5874                         append_entity(&compound->members, entity);
5875                 } else {
5876                         entity = parse_declarator(specifiers,
5877                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5878                         if (entity->kind == ENTITY_TYPEDEF) {
5879                                 errorf(&entity->base.source_position,
5880                                                 "typedef not allowed as compound member");
5881                         } else {
5882                                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5883
5884                                 /* make sure we don't define a symbol multiple times */
5885                                 symbol_t *symbol = entity->base.symbol;
5886                                 if (symbol != NULL) {
5887                                         entity_t *prev = find_compound_entry(compound, symbol);
5888                                         if (prev != NULL) {
5889                                                 errorf(&entity->base.source_position,
5890                                                                 "multiple declarations of symbol '%Y' (declared %P)",
5891                                                                 symbol, &prev->base.source_position);
5892                                         }
5893                                 }
5894
5895                                 if (token.type == ':') {
5896                                         source_position_t source_position = *HERE;
5897                                         next_token();
5898                                         expression_t *size = parse_constant_expression();
5899
5900                                         type_t *type          = entity->declaration.type;
5901                                         type_t *bitfield_type = make_bitfield_type(type, size,
5902                                                         &source_position, entity->base.symbol);
5903
5904                                         attribute_t *attributes = parse_attributes(NULL);
5905                                         entity->declaration.type = bitfield_type;
5906                                         handle_entity_attributes(attributes, entity);
5907                                 } else {
5908                                         type_t *orig_type = entity->declaration.type;
5909                                         type_t *type      = skip_typeref(orig_type);
5910                                         if (is_type_function(type)) {
5911                                                 errorf(&entity->base.source_position,
5912                                                        "compound member '%Y' must not have function type '%T'",
5913                                                                 entity->base.symbol, orig_type);
5914                                         } else if (is_type_incomplete(type)) {
5915                                                 /* §6.7.2.1:16 flexible array member */
5916                                                 if (!is_type_array(type)       ||
5917                                                                 token.type          != ';' ||
5918                                                                 look_ahead(1)->type != '}') {
5919                                                         errorf(&entity->base.source_position,
5920                                                                "compound member '%Y' has incomplete type '%T'",
5921                                                                         entity->base.symbol, orig_type);
5922                                                 }
5923                                         }
5924                                 }
5925
5926                                 append_entity(&compound->members, entity);
5927                         }
5928                 }
5929         } while (next_if(','));
5930         expect(';', end_error);
5931
5932 end_error:
5933         anonymous_entity = NULL;
5934 }
5935
5936 static void parse_compound_type_entries(compound_t *compound)
5937 {
5938         eat('{');
5939         add_anchor_token('}');
5940
5941         while (token.type != '}') {
5942                 if (token.type == T_EOF) {
5943                         errorf(HERE, "EOF while parsing struct");
5944                         break;
5945                 }
5946                 declaration_specifiers_t specifiers;
5947                 memset(&specifiers, 0, sizeof(specifiers));
5948                 parse_declaration_specifiers(&specifiers);
5949
5950                 parse_compound_declarators(compound, &specifiers);
5951         }
5952         rem_anchor_token('}');
5953         next_token();
5954
5955         /* §6.7.2.1:7 */
5956         compound->complete = true;
5957 }
5958
5959 static type_t *parse_typename(void)
5960 {
5961         declaration_specifiers_t specifiers;
5962         memset(&specifiers, 0, sizeof(specifiers));
5963         parse_declaration_specifiers(&specifiers);
5964         if (specifiers.storage_class != STORAGE_CLASS_NONE
5965                         || specifiers.thread_local) {
5966                 /* TODO: improve error message, user does probably not know what a
5967                  * storage class is...
5968                  */
5969                 errorf(HERE, "typename must not have a storage class");
5970         }
5971
5972         type_t *result = parse_abstract_declarator(specifiers.type);
5973
5974         return result;
5975 }
5976
5977
5978
5979
5980 typedef expression_t* (*parse_expression_function)(void);
5981 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5982
5983 typedef struct expression_parser_function_t expression_parser_function_t;
5984 struct expression_parser_function_t {
5985         parse_expression_function        parser;
5986         precedence_t                     infix_precedence;
5987         parse_expression_infix_function  infix_parser;
5988 };
5989
5990 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5991
5992 /**
5993  * Prints an error message if an expression was expected but not read
5994  */
5995 static expression_t *expected_expression_error(void)
5996 {
5997         /* skip the error message if the error token was read */
5998         if (token.type != T_ERROR) {
5999                 errorf(HERE, "expected expression, got token %K", &token);
6000         }
6001         next_token();
6002
6003         return create_invalid_expression();
6004 }
6005
6006 static type_t *get_string_type(void)
6007 {
6008         return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6009 }
6010
6011 static type_t *get_wide_string_type(void)
6012 {
6013         return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6014 }
6015
6016 /**
6017  * Parse a string constant.
6018  */
6019 static expression_t *parse_string_literal(void)
6020 {
6021         source_position_t begin   = token.source_position;
6022         string_t          res     = token.literal;
6023         bool              is_wide = (token.type == T_WIDE_STRING_LITERAL);
6024
6025         next_token();
6026         while (token.type == T_STRING_LITERAL
6027                         || token.type == T_WIDE_STRING_LITERAL) {
6028                 warn_string_concat(&token.source_position);
6029                 res = concat_strings(&res, &token.literal);
6030                 next_token();
6031                 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6032         }
6033
6034         expression_t *literal;
6035         if (is_wide) {
6036                 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6037                 literal->base.type = get_wide_string_type();
6038         } else {
6039                 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6040                 literal->base.type = get_string_type();
6041         }
6042         literal->base.source_position = begin;
6043         literal->literal.value        = res;
6044
6045         return literal;
6046 }
6047
6048 /**
6049  * Parse a boolean constant.
6050  */
6051 static expression_t *parse_boolean_literal(bool value)
6052 {
6053         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6054         literal->base.source_position = token.source_position;
6055         literal->base.type            = type_bool;
6056         literal->literal.value.begin  = value ? "true" : "false";
6057         literal->literal.value.size   = value ? 4 : 5;
6058
6059         next_token();
6060         return literal;
6061 }
6062
6063 static void warn_traditional_suffix(void)
6064 {
6065         if (!warning.traditional)
6066                 return;
6067         warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6068                  token.symbol);
6069 }
6070
6071 static void check_integer_suffix(void)
6072 {
6073         symbol_t *suffix = token.symbol;
6074         if (suffix == NULL)
6075                 return;
6076
6077         bool not_traditional = false;
6078         const char *c = suffix->string;
6079         if (*c == 'l' || *c == 'L') {
6080                 ++c;
6081                 if (*c == *(c-1)) {
6082                         not_traditional = true;
6083                         ++c;
6084                         if (*c == 'u' || *c == 'U') {
6085                                 ++c;
6086                         }
6087                 } else if (*c == 'u' || *c == 'U') {
6088                         not_traditional = true;
6089                         ++c;
6090                 }
6091         } else if (*c == 'u' || *c == 'U') {
6092                 not_traditional = true;
6093                 ++c;
6094                 if (*c == 'l' || *c == 'L') {
6095                         ++c;
6096                         if (*c == *(c-1)) {
6097                                 ++c;
6098                         }
6099                 }
6100         }
6101         if (*c != '\0') {
6102                 errorf(&token.source_position,
6103                        "invalid suffix '%s' on integer constant", suffix->string);
6104         } else if (not_traditional) {
6105                 warn_traditional_suffix();
6106         }
6107 }
6108
6109 static type_t *check_floatingpoint_suffix(void)
6110 {
6111         symbol_t *suffix = token.symbol;
6112         type_t   *type   = type_double;
6113         if (suffix == NULL)
6114                 return type;
6115
6116         bool not_traditional = false;
6117         const char *c = suffix->string;
6118         if (*c == 'f' || *c == 'F') {
6119                 ++c;
6120                 type = type_float;
6121         } else if (*c == 'l' || *c == 'L') {
6122                 ++c;
6123                 type = type_long_double;
6124         }
6125         if (*c != '\0') {
6126                 errorf(&token.source_position,
6127                        "invalid suffix '%s' on floatingpoint constant", suffix->string);
6128         } else if (not_traditional) {
6129                 warn_traditional_suffix();
6130         }
6131
6132         return type;
6133 }
6134
6135 /**
6136  * Parse an integer constant.
6137  */
6138 static expression_t *parse_number_literal(void)
6139 {
6140         expression_kind_t  kind;
6141         type_t            *type;
6142
6143         switch (token.type) {
6144         case T_INTEGER:
6145                 kind = EXPR_LITERAL_INTEGER;
6146                 check_integer_suffix();
6147                 type = type_int;
6148                 break;
6149         case T_INTEGER_OCTAL:
6150                 kind = EXPR_LITERAL_INTEGER_OCTAL;
6151                 check_integer_suffix();
6152                 type = type_int;
6153                 break;
6154         case T_INTEGER_HEXADECIMAL:
6155                 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6156                 check_integer_suffix();
6157                 type = type_int;
6158                 break;
6159         case T_FLOATINGPOINT:
6160                 kind = EXPR_LITERAL_FLOATINGPOINT;
6161                 type = check_floatingpoint_suffix();
6162                 break;
6163         case T_FLOATINGPOINT_HEXADECIMAL:
6164                 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6165                 type = check_floatingpoint_suffix();
6166                 break;
6167         default:
6168                 panic("unexpected token type in parse_number_literal");
6169         }
6170
6171         expression_t *literal = allocate_expression_zero(kind);
6172         literal->base.source_position = token.source_position;
6173         literal->base.type            = type;
6174         literal->literal.value        = token.literal;
6175         literal->literal.suffix       = token.symbol;
6176         next_token();
6177
6178         /* integer type depends on the size of the number and the size
6179          * representable by the types. The backend/codegeneration has to determine
6180          * that
6181          */
6182         determine_literal_type(&literal->literal);
6183         return literal;
6184 }
6185
6186 /**
6187  * Parse a character constant.
6188  */
6189 static expression_t *parse_character_constant(void)
6190 {
6191         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6192         literal->base.source_position = token.source_position;
6193         literal->base.type            = c_mode & _CXX ? type_char : type_int;
6194         literal->literal.value        = token.literal;
6195
6196         size_t len = literal->literal.value.size;
6197         if (len != 1) {
6198                 if (!GNU_MODE && !(c_mode & _C99)) {
6199                         errorf(HERE, "more than 1 character in character constant");
6200                 } else if (warning.multichar) {
6201                         literal->base.type = type_int;
6202                         warningf(HERE, "multi-character character constant");
6203                 }
6204         }
6205
6206         next_token();
6207         return literal;
6208 }
6209
6210 /**
6211  * Parse a wide character constant.
6212  */
6213 static expression_t *parse_wide_character_constant(void)
6214 {
6215         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6216         literal->base.source_position = token.source_position;
6217         literal->base.type            = type_int;
6218         literal->literal.value        = token.literal;
6219
6220         size_t len = wstrlen(&literal->literal.value);
6221         if (len != 1) {
6222                 warningf(HERE, "multi-character character constant");
6223         }
6224
6225         next_token();
6226         return literal;
6227 }
6228
6229 static entity_t *create_implicit_function(symbol_t *symbol,
6230                 const source_position_t *source_position)
6231 {
6232         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
6233         ntype->function.return_type            = type_int;
6234         ntype->function.unspecified_parameters = true;
6235         ntype->function.linkage                = LINKAGE_C;
6236         type_t *type                           = identify_new_type(ntype);
6237
6238         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6239         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
6240         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6241         entity->declaration.type                   = type;
6242         entity->declaration.implicit               = true;
6243         entity->base.namespc                       = NAMESPACE_NORMAL;
6244         entity->base.symbol                        = symbol;
6245         entity->base.source_position               = *source_position;
6246
6247         if (current_scope != NULL) {
6248                 bool strict_prototypes_old = warning.strict_prototypes;
6249                 warning.strict_prototypes  = false;
6250                 record_entity(entity, false);
6251                 warning.strict_prototypes = strict_prototypes_old;
6252         }
6253
6254         return entity;
6255 }
6256
6257 /**
6258  * Performs automatic type cast as described in §6.3.2.1.
6259  *
6260  * @param orig_type  the original type
6261  */
6262 static type_t *automatic_type_conversion(type_t *orig_type)
6263 {
6264         type_t *type = skip_typeref(orig_type);
6265         if (is_type_array(type)) {
6266                 array_type_t *array_type   = &type->array;
6267                 type_t       *element_type = array_type->element_type;
6268                 unsigned      qualifiers   = array_type->base.qualifiers;
6269
6270                 return make_pointer_type(element_type, qualifiers);
6271         }
6272
6273         if (is_type_function(type)) {
6274                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6275         }
6276
6277         return orig_type;
6278 }
6279
6280 /**
6281  * reverts the automatic casts of array to pointer types and function
6282  * to function-pointer types as defined §6.3.2.1
6283  */
6284 type_t *revert_automatic_type_conversion(const expression_t *expression)
6285 {
6286         switch (expression->kind) {
6287         case EXPR_REFERENCE: {
6288                 entity_t *entity = expression->reference.entity;
6289                 if (is_declaration(entity)) {
6290                         return entity->declaration.type;
6291                 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6292                         return entity->enum_value.enum_type;
6293                 } else {
6294                         panic("no declaration or enum in reference");
6295                 }
6296         }
6297
6298         case EXPR_SELECT: {
6299                 entity_t *entity = expression->select.compound_entry;
6300                 assert(is_declaration(entity));
6301                 type_t   *type   = entity->declaration.type;
6302                 return get_qualified_type(type,
6303                                 expression->base.type->base.qualifiers);
6304         }
6305
6306         case EXPR_UNARY_DEREFERENCE: {
6307                 const expression_t *const value = expression->unary.value;
6308                 type_t             *const type  = skip_typeref(value->base.type);
6309                 if (!is_type_pointer(type))
6310                         return type_error_type;
6311                 return type->pointer.points_to;
6312         }
6313
6314         case EXPR_ARRAY_ACCESS: {
6315                 const expression_t *array_ref = expression->array_access.array_ref;
6316                 type_t             *type_left = skip_typeref(array_ref->base.type);
6317                 if (!is_type_pointer(type_left))
6318                         return type_error_type;
6319                 return type_left->pointer.points_to;
6320         }
6321
6322         case EXPR_STRING_LITERAL: {
6323                 size_t size = expression->string_literal.value.size;
6324                 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6325         }
6326
6327         case EXPR_WIDE_STRING_LITERAL: {
6328                 size_t size = wstrlen(&expression->string_literal.value);
6329                 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6330         }
6331
6332         case EXPR_COMPOUND_LITERAL:
6333                 return expression->compound_literal.type;
6334
6335         default:
6336                 break;
6337         }
6338         return expression->base.type;
6339 }
6340
6341 /**
6342  * Find an entity matching a symbol in a scope.
6343  * Uses current scope if scope is NULL
6344  */
6345 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6346                                namespace_tag_t namespc)
6347 {
6348         if (scope == NULL) {
6349                 return get_entity(symbol, namespc);
6350         }
6351
6352         /* we should optimize here, if scope grows above a certain size we should
6353            construct a hashmap here... */
6354         entity_t *entity = scope->entities;
6355         for ( ; entity != NULL; entity = entity->base.next) {
6356                 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6357                         break;
6358         }
6359
6360         return entity;
6361 }
6362
6363 static entity_t *parse_qualified_identifier(void)
6364 {
6365         /* namespace containing the symbol */
6366         symbol_t          *symbol;
6367         source_position_t  pos;
6368         const scope_t     *lookup_scope = NULL;
6369
6370         if (next_if(T_COLONCOLON))
6371                 lookup_scope = &unit->scope;
6372
6373         entity_t *entity;
6374         while (true) {
6375                 if (token.type != T_IDENTIFIER) {
6376                         parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6377                         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6378                 }
6379                 symbol = token.symbol;
6380                 pos    = *HERE;
6381                 next_token();
6382
6383                 /* lookup entity */
6384                 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6385
6386                 if (!next_if(T_COLONCOLON))
6387                         break;
6388
6389                 switch (entity->kind) {
6390                 case ENTITY_NAMESPACE:
6391                         lookup_scope = &entity->namespacee.members;
6392                         break;
6393                 case ENTITY_STRUCT:
6394                 case ENTITY_UNION:
6395                 case ENTITY_CLASS:
6396                         lookup_scope = &entity->compound.members;
6397                         break;
6398                 default:
6399                         errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6400                                symbol, get_entity_kind_name(entity->kind));
6401                         goto end_error;
6402                 }
6403         }
6404
6405         if (entity == NULL) {
6406                 if (!strict_mode && token.type == '(') {
6407                         /* an implicitly declared function */
6408                         if (warning.error_implicit_function_declaration) {
6409                                 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6410                         } else if (warning.implicit_function_declaration) {
6411                                 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6412                         }
6413
6414                         entity = create_implicit_function(symbol, &pos);
6415                 } else {
6416                         errorf(&pos, "unknown identifier '%Y' found.", symbol);
6417                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
6418                 }
6419         }
6420
6421         return entity;
6422
6423 end_error:
6424         /* skip further qualifications */
6425         while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6426
6427         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6428 }
6429
6430 static expression_t *parse_reference(void)
6431 {
6432         entity_t *entity = parse_qualified_identifier();
6433
6434         type_t *orig_type;
6435         if (is_declaration(entity)) {
6436                 orig_type = entity->declaration.type;
6437         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6438                 orig_type = entity->enum_value.enum_type;
6439         } else {
6440                 panic("expected declaration or enum value in reference");
6441         }
6442
6443         /* we always do the auto-type conversions; the & and sizeof parser contains
6444          * code to revert this! */
6445         type_t *type = automatic_type_conversion(orig_type);
6446
6447         expression_kind_t kind = EXPR_REFERENCE;
6448         if (entity->kind == ENTITY_ENUM_VALUE)
6449                 kind = EXPR_REFERENCE_ENUM_VALUE;
6450
6451         expression_t *expression     = allocate_expression_zero(kind);
6452         expression->reference.entity = entity;
6453         expression->base.type        = type;
6454
6455         /* this declaration is used */
6456         if (is_declaration(entity)) {
6457                 entity->declaration.used = true;
6458         }
6459
6460         if (entity->base.parent_scope != file_scope
6461                 && (current_function != NULL
6462                         && entity->base.parent_scope->depth < current_function->parameters.depth)
6463                 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6464                 if (entity->kind == ENTITY_VARIABLE) {
6465                         /* access of a variable from an outer function */
6466                         entity->variable.address_taken = true;
6467                 } else if (entity->kind == ENTITY_PARAMETER) {
6468                         entity->parameter.address_taken = true;
6469                 }
6470                 current_function->need_closure = true;
6471         }
6472
6473         check_deprecated(HERE, entity);
6474
6475         if (warning.init_self && entity == current_init_decl && !in_type_prop
6476             && entity->kind == ENTITY_VARIABLE) {
6477                 current_init_decl = NULL;
6478                 warningf(HERE, "variable '%#T' is initialized by itself",
6479                          entity->declaration.type, entity->base.symbol);
6480         }
6481
6482         return expression;
6483 }
6484
6485 static bool semantic_cast(expression_t *cast)
6486 {
6487         expression_t            *expression      = cast->unary.value;
6488         type_t                  *orig_dest_type  = cast->base.type;
6489         type_t                  *orig_type_right = expression->base.type;
6490         type_t            const *dst_type        = skip_typeref(orig_dest_type);
6491         type_t            const *src_type        = skip_typeref(orig_type_right);
6492         source_position_t const *pos             = &cast->base.source_position;
6493
6494         /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6495         if (dst_type == type_void)
6496                 return true;
6497
6498         /* only integer and pointer can be casted to pointer */
6499         if (is_type_pointer(dst_type)  &&
6500             !is_type_pointer(src_type) &&
6501             !is_type_integer(src_type) &&
6502             is_type_valid(src_type)) {
6503                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6504                 return false;
6505         }
6506
6507         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6508                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6509                 return false;
6510         }
6511
6512         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6513                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6514                 return false;
6515         }
6516
6517         if (warning.cast_qual &&
6518             is_type_pointer(src_type) &&
6519             is_type_pointer(dst_type)) {
6520                 type_t *src = skip_typeref(src_type->pointer.points_to);
6521                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6522                 unsigned missing_qualifiers =
6523                         src->base.qualifiers & ~dst->base.qualifiers;
6524                 if (missing_qualifiers != 0) {
6525                         warningf(pos,
6526                                  "cast discards qualifiers '%Q' in pointer target type of '%T'",
6527                                  missing_qualifiers, orig_type_right);
6528                 }
6529         }
6530         return true;
6531 }
6532
6533 static expression_t *parse_compound_literal(type_t *type)
6534 {
6535         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6536
6537         parse_initializer_env_t env;
6538         env.type             = type;
6539         env.entity           = NULL;
6540         env.must_be_constant = false;
6541         initializer_t *initializer = parse_initializer(&env);
6542         type = env.type;
6543
6544         expression->compound_literal.initializer = initializer;
6545         expression->compound_literal.type        = type;
6546         expression->base.type                    = automatic_type_conversion(type);
6547
6548         return expression;
6549 }
6550
6551 /**
6552  * Parse a cast expression.
6553  */
6554 static expression_t *parse_cast(void)
6555 {
6556         add_anchor_token(')');
6557
6558         source_position_t source_position = token.source_position;
6559
6560         type_t *type = parse_typename();
6561
6562         rem_anchor_token(')');
6563         expect(')', end_error);
6564
6565         if (token.type == '{') {
6566                 return parse_compound_literal(type);
6567         }
6568
6569         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6570         cast->base.source_position = source_position;
6571
6572         expression_t *value = parse_subexpression(PREC_CAST);
6573         cast->base.type   = type;
6574         cast->unary.value = value;
6575
6576         if (! semantic_cast(cast)) {
6577                 /* TODO: record the error in the AST. else it is impossible to detect it */
6578         }
6579
6580         return cast;
6581 end_error:
6582         return create_invalid_expression();
6583 }
6584
6585 /**
6586  * Parse a statement expression.
6587  */
6588 static expression_t *parse_statement_expression(void)
6589 {
6590         add_anchor_token(')');
6591
6592         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6593
6594         statement_t *statement          = parse_compound_statement(true);
6595         statement->compound.stmt_expr   = true;
6596         expression->statement.statement = statement;
6597
6598         /* find last statement and use its type */
6599         type_t *type = type_void;
6600         const statement_t *stmt = statement->compound.statements;
6601         if (stmt != NULL) {
6602                 while (stmt->base.next != NULL)
6603                         stmt = stmt->base.next;
6604
6605                 if (stmt->kind == STATEMENT_EXPRESSION) {
6606                         type = stmt->expression.expression->base.type;
6607                 }
6608         } else if (warning.other) {
6609                 warningf(&expression->base.source_position, "empty statement expression ({})");
6610         }
6611         expression->base.type = type;
6612
6613         rem_anchor_token(')');
6614         expect(')', end_error);
6615
6616 end_error:
6617         return expression;
6618 }
6619
6620 /**
6621  * Parse a parenthesized expression.
6622  */
6623 static expression_t *parse_parenthesized_expression(void)
6624 {
6625         eat('(');
6626
6627         switch (token.type) {
6628         case '{':
6629                 /* gcc extension: a statement expression */
6630                 return parse_statement_expression();
6631
6632         TYPE_QUALIFIERS
6633         TYPE_SPECIFIERS
6634                 return parse_cast();
6635         case T_IDENTIFIER:
6636                 if (is_typedef_symbol(token.symbol)) {
6637                         return parse_cast();
6638                 }
6639         }
6640
6641         add_anchor_token(')');
6642         expression_t *result = parse_expression();
6643         result->base.parenthesized = true;
6644         rem_anchor_token(')');
6645         expect(')', end_error);
6646
6647 end_error:
6648         return result;
6649 }
6650
6651 static expression_t *parse_function_keyword(void)
6652 {
6653         /* TODO */
6654
6655         if (current_function == NULL) {
6656                 errorf(HERE, "'__func__' used outside of a function");
6657         }
6658
6659         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6660         expression->base.type     = type_char_ptr;
6661         expression->funcname.kind = FUNCNAME_FUNCTION;
6662
6663         next_token();
6664
6665         return expression;
6666 }
6667
6668 static expression_t *parse_pretty_function_keyword(void)
6669 {
6670         if (current_function == NULL) {
6671                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6672         }
6673
6674         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6675         expression->base.type     = type_char_ptr;
6676         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6677
6678         eat(T___PRETTY_FUNCTION__);
6679
6680         return expression;
6681 }
6682
6683 static expression_t *parse_funcsig_keyword(void)
6684 {
6685         if (current_function == NULL) {
6686                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6687         }
6688
6689         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6690         expression->base.type     = type_char_ptr;
6691         expression->funcname.kind = FUNCNAME_FUNCSIG;
6692
6693         eat(T___FUNCSIG__);
6694
6695         return expression;
6696 }
6697
6698 static expression_t *parse_funcdname_keyword(void)
6699 {
6700         if (current_function == NULL) {
6701                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6702         }
6703
6704         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6705         expression->base.type     = type_char_ptr;
6706         expression->funcname.kind = FUNCNAME_FUNCDNAME;
6707
6708         eat(T___FUNCDNAME__);
6709
6710         return expression;
6711 }
6712
6713 static designator_t *parse_designator(void)
6714 {
6715         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
6716         result->source_position = *HERE;
6717
6718         if (token.type != T_IDENTIFIER) {
6719                 parse_error_expected("while parsing member designator",
6720                                      T_IDENTIFIER, NULL);
6721                 return NULL;
6722         }
6723         result->symbol = token.symbol;
6724         next_token();
6725
6726         designator_t *last_designator = result;
6727         while (true) {
6728                 if (next_if('.')) {
6729                         if (token.type != T_IDENTIFIER) {
6730                                 parse_error_expected("while parsing member designator",
6731                                                      T_IDENTIFIER, NULL);
6732                                 return NULL;
6733                         }
6734                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6735                         designator->source_position = *HERE;
6736                         designator->symbol          = token.symbol;
6737                         next_token();
6738
6739                         last_designator->next = designator;
6740                         last_designator       = designator;
6741                         continue;
6742                 }
6743                 if (next_if('[')) {
6744                         add_anchor_token(']');
6745                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6746                         designator->source_position = *HERE;
6747                         designator->array_index     = parse_expression();
6748                         rem_anchor_token(']');
6749                         expect(']', end_error);
6750                         if (designator->array_index == NULL) {
6751                                 return NULL;
6752                         }
6753
6754                         last_designator->next = designator;
6755                         last_designator       = designator;
6756                         continue;
6757                 }
6758                 break;
6759         }
6760
6761         return result;
6762 end_error:
6763         return NULL;
6764 }
6765
6766 /**
6767  * Parse the __builtin_offsetof() expression.
6768  */
6769 static expression_t *parse_offsetof(void)
6770 {
6771         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6772         expression->base.type    = type_size_t;
6773
6774         eat(T___builtin_offsetof);
6775
6776         expect('(', end_error);
6777         add_anchor_token(',');
6778         type_t *type = parse_typename();
6779         rem_anchor_token(',');
6780         expect(',', end_error);
6781         add_anchor_token(')');
6782         designator_t *designator = parse_designator();
6783         rem_anchor_token(')');
6784         expect(')', end_error);
6785
6786         expression->offsetofe.type       = type;
6787         expression->offsetofe.designator = designator;
6788
6789         type_path_t path;
6790         memset(&path, 0, sizeof(path));
6791         path.top_type = type;
6792         path.path     = NEW_ARR_F(type_path_entry_t, 0);
6793
6794         descend_into_subtype(&path);
6795
6796         if (!walk_designator(&path, designator, true)) {
6797                 return create_invalid_expression();
6798         }
6799
6800         DEL_ARR_F(path.path);
6801
6802         return expression;
6803 end_error:
6804         return create_invalid_expression();
6805 }
6806
6807 /**
6808  * Parses a _builtin_va_start() expression.
6809  */
6810 static expression_t *parse_va_start(void)
6811 {
6812         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6813
6814         eat(T___builtin_va_start);
6815
6816         expect('(', end_error);
6817         add_anchor_token(',');
6818         expression->va_starte.ap = parse_assignment_expression();
6819         rem_anchor_token(',');
6820         expect(',', end_error);
6821         expression_t *const expr = parse_assignment_expression();
6822         if (expr->kind == EXPR_REFERENCE) {
6823                 entity_t *const entity = expr->reference.entity;
6824                 if (!current_function->base.type->function.variadic) {
6825                         errorf(&expr->base.source_position,
6826                                         "'va_start' used in non-variadic function");
6827                 } else if (entity->base.parent_scope != &current_function->parameters ||
6828                                 entity->base.next != NULL ||
6829                                 entity->kind != ENTITY_PARAMETER) {
6830                         errorf(&expr->base.source_position,
6831                                "second argument of 'va_start' must be last parameter of the current function");
6832                 } else {
6833                         expression->va_starte.parameter = &entity->variable;
6834                 }
6835                 expect(')', end_error);
6836                 return expression;
6837         }
6838         expect(')', end_error);
6839 end_error:
6840         return create_invalid_expression();
6841 }
6842
6843 /**
6844  * Parses a __builtin_va_arg() expression.
6845  */
6846 static expression_t *parse_va_arg(void)
6847 {
6848         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6849
6850         eat(T___builtin_va_arg);
6851
6852         expect('(', end_error);
6853         call_argument_t ap;
6854         ap.expression = parse_assignment_expression();
6855         expression->va_arge.ap = ap.expression;
6856         check_call_argument(type_valist, &ap, 1);
6857
6858         expect(',', end_error);
6859         expression->base.type = parse_typename();
6860         expect(')', end_error);
6861
6862         return expression;
6863 end_error:
6864         return create_invalid_expression();
6865 }
6866
6867 /**
6868  * Parses a __builtin_va_copy() expression.
6869  */
6870 static expression_t *parse_va_copy(void)
6871 {
6872         expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6873
6874         eat(T___builtin_va_copy);
6875
6876         expect('(', end_error);
6877         expression_t *dst = parse_assignment_expression();
6878         assign_error_t error = semantic_assign(type_valist, dst);
6879         report_assign_error(error, type_valist, dst, "call argument 1",
6880                             &dst->base.source_position);
6881         expression->va_copye.dst = dst;
6882
6883         expect(',', end_error);
6884
6885         call_argument_t src;
6886         src.expression = parse_assignment_expression();
6887         check_call_argument(type_valist, &src, 2);
6888         expression->va_copye.src = src.expression;
6889         expect(')', end_error);
6890
6891         return expression;
6892 end_error:
6893         return create_invalid_expression();
6894 }
6895
6896 /**
6897  * Parses a __builtin_constant_p() expression.
6898  */
6899 static expression_t *parse_builtin_constant(void)
6900 {
6901         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6902
6903         eat(T___builtin_constant_p);
6904
6905         expect('(', end_error);
6906         add_anchor_token(')');
6907         expression->builtin_constant.value = parse_assignment_expression();
6908         rem_anchor_token(')');
6909         expect(')', end_error);
6910         expression->base.type = type_int;
6911
6912         return expression;
6913 end_error:
6914         return create_invalid_expression();
6915 }
6916
6917 /**
6918  * Parses a __builtin_types_compatible_p() expression.
6919  */
6920 static expression_t *parse_builtin_types_compatible(void)
6921 {
6922         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6923
6924         eat(T___builtin_types_compatible_p);
6925
6926         expect('(', end_error);
6927         add_anchor_token(')');
6928         add_anchor_token(',');
6929         expression->builtin_types_compatible.left = parse_typename();
6930         rem_anchor_token(',');
6931         expect(',', end_error);
6932         expression->builtin_types_compatible.right = parse_typename();
6933         rem_anchor_token(')');
6934         expect(')', end_error);
6935         expression->base.type = type_int;
6936
6937         return expression;
6938 end_error:
6939         return create_invalid_expression();
6940 }
6941
6942 /**
6943  * Parses a __builtin_is_*() compare expression.
6944  */
6945 static expression_t *parse_compare_builtin(void)
6946 {
6947         expression_t *expression;
6948
6949         switch (token.type) {
6950         case T___builtin_isgreater:
6951                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6952                 break;
6953         case T___builtin_isgreaterequal:
6954                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6955                 break;
6956         case T___builtin_isless:
6957                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6958                 break;
6959         case T___builtin_islessequal:
6960                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6961                 break;
6962         case T___builtin_islessgreater:
6963                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6964                 break;
6965         case T___builtin_isunordered:
6966                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6967                 break;
6968         default:
6969                 internal_errorf(HERE, "invalid compare builtin found");
6970         }
6971         expression->base.source_position = *HERE;
6972         next_token();
6973
6974         expect('(', end_error);
6975         expression->binary.left = parse_assignment_expression();
6976         expect(',', end_error);
6977         expression->binary.right = parse_assignment_expression();
6978         expect(')', end_error);
6979
6980         type_t *const orig_type_left  = expression->binary.left->base.type;
6981         type_t *const orig_type_right = expression->binary.right->base.type;
6982
6983         type_t *const type_left  = skip_typeref(orig_type_left);
6984         type_t *const type_right = skip_typeref(orig_type_right);
6985         if (!is_type_float(type_left) && !is_type_float(type_right)) {
6986                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6987                         type_error_incompatible("invalid operands in comparison",
6988                                 &expression->base.source_position, orig_type_left, orig_type_right);
6989                 }
6990         } else {
6991                 semantic_comparison(&expression->binary);
6992         }
6993
6994         return expression;
6995 end_error:
6996         return create_invalid_expression();
6997 }
6998
6999 /**
7000  * Parses a MS assume() expression.
7001  */
7002 static expression_t *parse_assume(void)
7003 {
7004         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7005
7006         eat(T__assume);
7007
7008         expect('(', end_error);
7009         add_anchor_token(')');
7010         expression->unary.value = parse_assignment_expression();
7011         rem_anchor_token(')');
7012         expect(')', end_error);
7013
7014         expression->base.type = type_void;
7015         return expression;
7016 end_error:
7017         return create_invalid_expression();
7018 }
7019
7020 /**
7021  * Return the declaration for a given label symbol or create a new one.
7022  *
7023  * @param symbol  the symbol of the label
7024  */
7025 static label_t *get_label(symbol_t *symbol)
7026 {
7027         entity_t *label;
7028         assert(current_function != NULL);
7029
7030         label = get_entity(symbol, NAMESPACE_LABEL);
7031         /* if we found a local label, we already created the declaration */
7032         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7033                 if (label->base.parent_scope != current_scope) {
7034                         assert(label->base.parent_scope->depth < current_scope->depth);
7035                         current_function->goto_to_outer = true;
7036                 }
7037                 return &label->label;
7038         }
7039
7040         label = get_entity(symbol, NAMESPACE_LABEL);
7041         /* if we found a label in the same function, then we already created the
7042          * declaration */
7043         if (label != NULL
7044                         && label->base.parent_scope == &current_function->parameters) {
7045                 return &label->label;
7046         }
7047
7048         /* otherwise we need to create a new one */
7049         label               = allocate_entity_zero(ENTITY_LABEL);
7050         label->base.namespc = NAMESPACE_LABEL;
7051         label->base.symbol  = symbol;
7052
7053         label_push(label);
7054
7055         return &label->label;
7056 }
7057
7058 /**
7059  * Parses a GNU && label address expression.
7060  */
7061 static expression_t *parse_label_address(void)
7062 {
7063         source_position_t source_position = token.source_position;
7064         eat(T_ANDAND);
7065         if (token.type != T_IDENTIFIER) {
7066                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7067                 goto end_error;
7068         }
7069         symbol_t *symbol = token.symbol;
7070         next_token();
7071
7072         label_t *label       = get_label(symbol);
7073         label->used          = true;
7074         label->address_taken = true;
7075
7076         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7077         expression->base.source_position = source_position;
7078
7079         /* label address is threaten as a void pointer */
7080         expression->base.type           = type_void_ptr;
7081         expression->label_address.label = label;
7082         return expression;
7083 end_error:
7084         return create_invalid_expression();
7085 }
7086
7087 /**
7088  * Parse a microsoft __noop expression.
7089  */
7090 static expression_t *parse_noop_expression(void)
7091 {
7092         /* the result is a (int)0 */
7093         expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7094         literal->base.type            = type_int;
7095         literal->base.source_position = token.source_position;
7096         literal->literal.value.begin  = "__noop";
7097         literal->literal.value.size   = 6;
7098
7099         eat(T___noop);
7100
7101         if (token.type == '(') {
7102                 /* parse arguments */
7103                 eat('(');
7104                 add_anchor_token(')');
7105                 add_anchor_token(',');
7106
7107                 if (token.type != ')') do {
7108                         (void)parse_assignment_expression();
7109                 } while (next_if(','));
7110         }
7111         rem_anchor_token(',');
7112         rem_anchor_token(')');
7113         expect(')', end_error);
7114
7115 end_error:
7116         return literal;
7117 }
7118
7119 /**
7120  * Parses a primary expression.
7121  */
7122 static expression_t *parse_primary_expression(void)
7123 {
7124         switch (token.type) {
7125         case T_false:                        return parse_boolean_literal(false);
7126         case T_true:                         return parse_boolean_literal(true);
7127         case T_INTEGER:
7128         case T_INTEGER_OCTAL:
7129         case T_INTEGER_HEXADECIMAL:
7130         case T_FLOATINGPOINT:
7131         case T_FLOATINGPOINT_HEXADECIMAL:    return parse_number_literal();
7132         case T_CHARACTER_CONSTANT:           return parse_character_constant();
7133         case T_WIDE_CHARACTER_CONSTANT:      return parse_wide_character_constant();
7134         case T_STRING_LITERAL:
7135         case T_WIDE_STRING_LITERAL:          return parse_string_literal();
7136         case T___FUNCTION__:
7137         case T___func__:                     return parse_function_keyword();
7138         case T___PRETTY_FUNCTION__:          return parse_pretty_function_keyword();
7139         case T___FUNCSIG__:                  return parse_funcsig_keyword();
7140         case T___FUNCDNAME__:                return parse_funcdname_keyword();
7141         case T___builtin_offsetof:           return parse_offsetof();
7142         case T___builtin_va_start:           return parse_va_start();
7143         case T___builtin_va_arg:             return parse_va_arg();
7144         case T___builtin_va_copy:            return parse_va_copy();
7145         case T___builtin_isgreater:
7146         case T___builtin_isgreaterequal:
7147         case T___builtin_isless:
7148         case T___builtin_islessequal:
7149         case T___builtin_islessgreater:
7150         case T___builtin_isunordered:        return parse_compare_builtin();
7151         case T___builtin_constant_p:         return parse_builtin_constant();
7152         case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7153         case T__assume:                      return parse_assume();
7154         case T_ANDAND:
7155                 if (GNU_MODE)
7156                         return parse_label_address();
7157                 break;
7158
7159         case '(':                            return parse_parenthesized_expression();
7160         case T___noop:                       return parse_noop_expression();
7161
7162         /* Gracefully handle type names while parsing expressions. */
7163         case T_COLONCOLON:
7164                 return parse_reference();
7165         case T_IDENTIFIER:
7166                 if (!is_typedef_symbol(token.symbol)) {
7167                         return parse_reference();
7168                 }
7169                 /* FALLTHROUGH */
7170         TYPENAME_START {
7171                 source_position_t  const pos  = *HERE;
7172                 type_t const      *const type = parse_typename();
7173                 errorf(&pos, "encountered type '%T' while parsing expression", type);
7174                 return create_invalid_expression();
7175         }
7176         }
7177
7178         errorf(HERE, "unexpected token %K, expected an expression", &token);
7179         eat_until_anchor();
7180         return create_invalid_expression();
7181 }
7182
7183 /**
7184  * Check if the expression has the character type and issue a warning then.
7185  */
7186 static void check_for_char_index_type(const expression_t *expression)
7187 {
7188         type_t       *const type      = expression->base.type;
7189         const type_t *const base_type = skip_typeref(type);
7190
7191         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7192                         warning.char_subscripts) {
7193                 warningf(&expression->base.source_position,
7194                          "array subscript has type '%T'", type);
7195         }
7196 }
7197
7198 static expression_t *parse_array_expression(expression_t *left)
7199 {
7200         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7201
7202         eat('[');
7203         add_anchor_token(']');
7204
7205         expression_t *inside = parse_expression();
7206
7207         type_t *const orig_type_left   = left->base.type;
7208         type_t *const orig_type_inside = inside->base.type;
7209
7210         type_t *const type_left   = skip_typeref(orig_type_left);
7211         type_t *const type_inside = skip_typeref(orig_type_inside);
7212
7213         type_t                    *return_type;
7214         array_access_expression_t *array_access = &expression->array_access;
7215         if (is_type_pointer(type_left)) {
7216                 return_type             = type_left->pointer.points_to;
7217                 array_access->array_ref = left;
7218                 array_access->index     = inside;
7219                 check_for_char_index_type(inside);
7220         } else if (is_type_pointer(type_inside)) {
7221                 return_type             = type_inside->pointer.points_to;
7222                 array_access->array_ref = inside;
7223                 array_access->index     = left;
7224                 array_access->flipped   = true;
7225                 check_for_char_index_type(left);
7226         } else {
7227                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7228                         errorf(HERE,
7229                                 "array access on object with non-pointer types '%T', '%T'",
7230                                 orig_type_left, orig_type_inside);
7231                 }
7232                 return_type             = type_error_type;
7233                 array_access->array_ref = left;
7234                 array_access->index     = inside;
7235         }
7236
7237         expression->base.type = automatic_type_conversion(return_type);
7238
7239         rem_anchor_token(']');
7240         expect(']', end_error);
7241 end_error:
7242         return expression;
7243 }
7244
7245 static expression_t *parse_typeprop(expression_kind_t const kind)
7246 {
7247         expression_t  *tp_expression = allocate_expression_zero(kind);
7248         tp_expression->base.type     = type_size_t;
7249
7250         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7251
7252         /* we only refer to a type property, mark this case */
7253         bool old     = in_type_prop;
7254         in_type_prop = true;
7255
7256         type_t       *orig_type;
7257         expression_t *expression;
7258         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7259                 next_token();
7260                 add_anchor_token(')');
7261                 orig_type = parse_typename();
7262                 rem_anchor_token(')');
7263                 expect(')', end_error);
7264
7265                 if (token.type == '{') {
7266                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7267                          * starting with a compound literal */
7268                         expression = parse_compound_literal(orig_type);
7269                         goto typeprop_expression;
7270                 }
7271         } else {
7272                 expression = parse_subexpression(PREC_UNARY);
7273
7274 typeprop_expression:
7275                 tp_expression->typeprop.tp_expression = expression;
7276
7277                 orig_type = revert_automatic_type_conversion(expression);
7278                 expression->base.type = orig_type;
7279         }
7280
7281         tp_expression->typeprop.type   = orig_type;
7282         type_t const* const type       = skip_typeref(orig_type);
7283         char   const*       wrong_type = NULL;
7284         if (is_type_incomplete(type)) {
7285                 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7286                         wrong_type = "incomplete";
7287         } else if (type->kind == TYPE_FUNCTION) {
7288                 if (GNU_MODE) {
7289                         /* function types are allowed (and return 1) */
7290                         if (warning.other) {
7291                                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7292                                 warningf(&tp_expression->base.source_position,
7293                                          "%s expression with function argument returns invalid result", what);
7294                         }
7295                 } else {
7296                         wrong_type = "function";
7297                 }
7298         } else {
7299                 if (is_type_incomplete(type))
7300                         wrong_type = "incomplete";
7301         }
7302         if (type->kind == TYPE_BITFIELD)
7303                 wrong_type = "bitfield";
7304
7305         if (wrong_type != NULL) {
7306                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7307                 errorf(&tp_expression->base.source_position,
7308                                 "operand of %s expression must not be of %s type '%T'",
7309                                 what, wrong_type, orig_type);
7310         }
7311
7312 end_error:
7313         in_type_prop = old;
7314         return tp_expression;
7315 }
7316
7317 static expression_t *parse_sizeof(void)
7318 {
7319         return parse_typeprop(EXPR_SIZEOF);
7320 }
7321
7322 static expression_t *parse_alignof(void)
7323 {
7324         return parse_typeprop(EXPR_ALIGNOF);
7325 }
7326
7327 static expression_t *parse_select_expression(expression_t *addr)
7328 {
7329         assert(token.type == '.' || token.type == T_MINUSGREATER);
7330         bool select_left_arrow = (token.type == T_MINUSGREATER);
7331         source_position_t const pos = *HERE;
7332         next_token();
7333
7334         if (token.type != T_IDENTIFIER) {
7335                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7336                 return create_invalid_expression();
7337         }
7338         symbol_t *symbol = token.symbol;
7339         next_token();
7340
7341         type_t *const orig_type = addr->base.type;
7342         type_t *const type      = skip_typeref(orig_type);
7343
7344         type_t *type_left;
7345         bool    saw_error = false;
7346         if (is_type_pointer(type)) {
7347                 if (!select_left_arrow) {
7348                         errorf(&pos,
7349                                "request for member '%Y' in something not a struct or union, but '%T'",
7350                                symbol, orig_type);
7351                         saw_error = true;
7352                 }
7353                 type_left = skip_typeref(type->pointer.points_to);
7354         } else {
7355                 if (select_left_arrow && is_type_valid(type)) {
7356                         errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7357                         saw_error = true;
7358                 }
7359                 type_left = type;
7360         }
7361
7362         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7363             type_left->kind != TYPE_COMPOUND_UNION) {
7364
7365                 if (is_type_valid(type_left) && !saw_error) {
7366                         errorf(&pos,
7367                                "request for member '%Y' in something not a struct or union, but '%T'",
7368                                symbol, type_left);
7369                 }
7370                 return create_invalid_expression();
7371         }
7372
7373         compound_t *compound = type_left->compound.compound;
7374         if (!compound->complete) {
7375                 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7376                        symbol, type_left);
7377                 return create_invalid_expression();
7378         }
7379
7380         type_qualifiers_t  qualifiers = type_left->base.qualifiers;
7381         expression_t      *result     =
7382                 find_create_select(&pos, addr, qualifiers, compound, symbol);
7383
7384         if (result == NULL) {
7385                 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7386                 return create_invalid_expression();
7387         }
7388
7389         return result;
7390 }
7391
7392 static void check_call_argument(type_t          *expected_type,
7393                                 call_argument_t *argument, unsigned pos)
7394 {
7395         type_t         *expected_type_skip = skip_typeref(expected_type);
7396         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7397         expression_t   *arg_expr           = argument->expression;
7398         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7399
7400         /* handle transparent union gnu extension */
7401         if (is_type_union(expected_type_skip)
7402                         && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7403                 compound_t *union_decl  = expected_type_skip->compound.compound;
7404                 type_t     *best_type   = NULL;
7405                 entity_t   *entry       = union_decl->members.entities;
7406                 for ( ; entry != NULL; entry = entry->base.next) {
7407                         assert(is_declaration(entry));
7408                         type_t *decl_type = entry->declaration.type;
7409                         error = semantic_assign(decl_type, arg_expr);
7410                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7411                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7412                                 continue;
7413
7414                         if (error == ASSIGN_SUCCESS) {
7415                                 best_type = decl_type;
7416                         } else if (best_type == NULL) {
7417                                 best_type = decl_type;
7418                         }
7419                 }
7420
7421                 if (best_type != NULL) {
7422                         expected_type = best_type;
7423                 }
7424         }
7425
7426         error                = semantic_assign(expected_type, arg_expr);
7427         argument->expression = create_implicit_cast(arg_expr, expected_type);
7428
7429         if (error != ASSIGN_SUCCESS) {
7430                 /* report exact scope in error messages (like "in argument 3") */
7431                 char buf[64];
7432                 snprintf(buf, sizeof(buf), "call argument %u", pos);
7433                 report_assign_error(error, expected_type, arg_expr, buf,
7434                                     &arg_expr->base.source_position);
7435         } else if (warning.traditional || warning.conversion) {
7436                 type_t *const promoted_type = get_default_promoted_type(arg_type);
7437                 if (!types_compatible(expected_type_skip, promoted_type) &&
7438                     !types_compatible(expected_type_skip, type_void_ptr) &&
7439                     !types_compatible(type_void_ptr,      promoted_type)) {
7440                         /* Deliberately show the skipped types in this warning */
7441                         warningf(&arg_expr->base.source_position,
7442                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
7443                                 pos, expected_type_skip, promoted_type);
7444                 }
7445         }
7446 }
7447
7448 /**
7449  * Handle the semantic restrictions of builtin calls
7450  */
7451 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7452         switch (call->function->reference.entity->function.btk) {
7453                 case bk_gnu_builtin_return_address:
7454                 case bk_gnu_builtin_frame_address: {
7455                         /* argument must be constant */
7456                         call_argument_t *argument = call->arguments;
7457
7458                         if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7459                                 errorf(&call->base.source_position,
7460                                        "argument of '%Y' must be a constant expression",
7461                                        call->function->reference.entity->base.symbol);
7462                         }
7463                         break;
7464                 }
7465                 case bk_gnu_builtin_object_size:
7466                         if (call->arguments == NULL)
7467                                 break;
7468
7469                         call_argument_t *arg = call->arguments->next;
7470                         if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7471                                 errorf(&call->base.source_position,
7472                                            "second argument of '%Y' must be a constant expression",
7473                                            call->function->reference.entity->base.symbol);
7474                         }
7475                         break;
7476                 case bk_gnu_builtin_prefetch:
7477                         /* second and third argument must be constant if existent */
7478                         if (call->arguments == NULL)
7479                                 break;
7480                         call_argument_t *rw = call->arguments->next;
7481                         call_argument_t *locality = NULL;
7482
7483                         if (rw != NULL) {
7484                                 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7485                                         errorf(&call->base.source_position,
7486                                                "second argument of '%Y' must be a constant expression",
7487                                                call->function->reference.entity->base.symbol);
7488                                 }
7489                                 locality = rw->next;
7490                         }
7491                         if (locality != NULL) {
7492                                 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7493                                         errorf(&call->base.source_position,
7494                                                "third argument of '%Y' must be a constant expression",
7495                                                call->function->reference.entity->base.symbol);
7496                                 }
7497                                 locality = rw->next;
7498                         }
7499                         break;
7500                 default:
7501                         break;
7502         }
7503 }
7504
7505 /**
7506  * Parse a call expression, ie. expression '( ... )'.
7507  *
7508  * @param expression  the function address
7509  */
7510 static expression_t *parse_call_expression(expression_t *expression)
7511 {
7512         expression_t      *result = allocate_expression_zero(EXPR_CALL);
7513         call_expression_t *call   = &result->call;
7514         call->function            = expression;
7515
7516         type_t *const orig_type = expression->base.type;
7517         type_t *const type      = skip_typeref(orig_type);
7518
7519         function_type_t *function_type = NULL;
7520         if (is_type_pointer(type)) {
7521                 type_t *const to_type = skip_typeref(type->pointer.points_to);
7522
7523                 if (is_type_function(to_type)) {
7524                         function_type   = &to_type->function;
7525                         call->base.type = function_type->return_type;
7526                 }
7527         }
7528
7529         if (function_type == NULL && is_type_valid(type)) {
7530                 errorf(HERE,
7531                        "called object '%E' (type '%T') is not a pointer to a function",
7532                        expression, orig_type);
7533         }
7534
7535         /* parse arguments */
7536         eat('(');
7537         add_anchor_token(')');
7538         add_anchor_token(',');
7539
7540         if (token.type != ')') {
7541                 call_argument_t **anchor = &call->arguments;
7542                 do {
7543                         call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7544                         argument->expression = parse_assignment_expression();
7545
7546                         *anchor = argument;
7547                         anchor  = &argument->next;
7548                 } while (next_if(','));
7549         }
7550         rem_anchor_token(',');
7551         rem_anchor_token(')');
7552         expect(')', end_error);
7553
7554         if (function_type == NULL)
7555                 return result;
7556
7557         /* check type and count of call arguments */
7558         function_parameter_t *parameter = function_type->parameters;
7559         call_argument_t      *argument  = call->arguments;
7560         if (!function_type->unspecified_parameters) {
7561                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7562                                 parameter = parameter->next, argument = argument->next) {
7563                         check_call_argument(parameter->type, argument, ++pos);
7564                 }
7565
7566                 if (parameter != NULL) {
7567                         errorf(HERE, "too few arguments to function '%E'", expression);
7568                 } else if (argument != NULL && !function_type->variadic) {
7569                         errorf(HERE, "too many arguments to function '%E'", expression);
7570                 }
7571         }
7572
7573         /* do default promotion for other arguments */
7574         for (; argument != NULL; argument = argument->next) {
7575                 type_t *type = argument->expression->base.type;
7576                 if (!is_type_object(skip_typeref(type))) {
7577                         errorf(&argument->expression->base.source_position,
7578                                "call argument '%E' must not be void", argument->expression);
7579                 }
7580
7581                 type = get_default_promoted_type(type);
7582
7583                 argument->expression
7584                         = create_implicit_cast(argument->expression, type);
7585         }
7586
7587         check_format(&result->call);
7588
7589         if (warning.aggregate_return &&
7590             is_type_compound(skip_typeref(function_type->return_type))) {
7591                 warningf(&result->base.source_position,
7592                          "function call has aggregate value");
7593         }
7594
7595         if (call->function->kind == EXPR_REFERENCE) {
7596                 reference_expression_t *reference = &call->function->reference;
7597                 if (reference->entity->kind == ENTITY_FUNCTION &&
7598                     reference->entity->function.btk != bk_none)
7599                         handle_builtin_argument_restrictions(call);
7600         }
7601
7602 end_error:
7603         return result;
7604 }
7605
7606 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7607
7608 static bool same_compound_type(const type_t *type1, const type_t *type2)
7609 {
7610         return
7611                 is_type_compound(type1) &&
7612                 type1->kind == type2->kind &&
7613                 type1->compound.compound == type2->compound.compound;
7614 }
7615
7616 static expression_t const *get_reference_address(expression_t const *expr)
7617 {
7618         bool regular_take_address = true;
7619         for (;;) {
7620                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7621                         expr = expr->unary.value;
7622                 } else {
7623                         regular_take_address = false;
7624                 }
7625
7626                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7627                         break;
7628
7629                 expr = expr->unary.value;
7630         }
7631
7632         if (expr->kind != EXPR_REFERENCE)
7633                 return NULL;
7634
7635         /* special case for functions which are automatically converted to a
7636          * pointer to function without an extra TAKE_ADDRESS operation */
7637         if (!regular_take_address &&
7638                         expr->reference.entity->kind != ENTITY_FUNCTION) {
7639                 return NULL;
7640         }
7641
7642         return expr;
7643 }
7644
7645 static void warn_reference_address_as_bool(expression_t const* expr)
7646 {
7647         if (!warning.address)
7648                 return;
7649
7650         expr = get_reference_address(expr);
7651         if (expr != NULL) {
7652                 warningf(&expr->base.source_position,
7653                          "the address of '%Y' will always evaluate as 'true'",
7654                          expr->reference.entity->base.symbol);
7655         }
7656 }
7657
7658 static void warn_assignment_in_condition(const expression_t *const expr)
7659 {
7660         if (!warning.parentheses)
7661                 return;
7662         if (expr->base.kind != EXPR_BINARY_ASSIGN)
7663                 return;
7664         if (expr->base.parenthesized)
7665                 return;
7666         warningf(&expr->base.source_position,
7667                         "suggest parentheses around assignment used as truth value");
7668 }
7669
7670 static void semantic_condition(expression_t const *const expr,
7671                                char const *const context)
7672 {
7673         type_t *const type = skip_typeref(expr->base.type);
7674         if (is_type_scalar(type)) {
7675                 warn_reference_address_as_bool(expr);
7676                 warn_assignment_in_condition(expr);
7677         } else if (is_type_valid(type)) {
7678                 errorf(&expr->base.source_position,
7679                                 "%s must have scalar type", context);
7680         }
7681 }
7682
7683 /**
7684  * Parse a conditional expression, ie. 'expression ? ... : ...'.
7685  *
7686  * @param expression  the conditional expression
7687  */
7688 static expression_t *parse_conditional_expression(expression_t *expression)
7689 {
7690         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7691
7692         conditional_expression_t *conditional = &result->conditional;
7693         conditional->condition                = expression;
7694
7695         eat('?');
7696         add_anchor_token(':');
7697
7698         /* §6.5.15:2  The first operand shall have scalar type. */
7699         semantic_condition(expression, "condition of conditional operator");
7700
7701         expression_t *true_expression = expression;
7702         bool          gnu_cond = false;
7703         if (GNU_MODE && token.type == ':') {
7704                 gnu_cond = true;
7705         } else {
7706                 true_expression = parse_expression();
7707         }
7708         rem_anchor_token(':');
7709         expect(':', end_error);
7710 end_error:;
7711         expression_t *false_expression =
7712                 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7713
7714         type_t *const orig_true_type  = true_expression->base.type;
7715         type_t *const orig_false_type = false_expression->base.type;
7716         type_t *const true_type       = skip_typeref(orig_true_type);
7717         type_t *const false_type      = skip_typeref(orig_false_type);
7718
7719         /* 6.5.15.3 */
7720         type_t *result_type;
7721         if (is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
7722                         is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7723                 /* ISO/IEC 14882:1998(E) §5.16:2 */
7724                 if (true_expression->kind == EXPR_UNARY_THROW) {
7725                         result_type = false_type;
7726                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7727                         result_type = true_type;
7728                 } else {
7729                         if (warning.other && (
7730                                                 !is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
7731                                                 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7732                                         )) {
7733                                 warningf(&conditional->base.source_position,
7734                                                 "ISO C forbids conditional expression with only one void side");
7735                         }
7736                         result_type = type_void;
7737                 }
7738         } else if (is_type_arithmetic(true_type)
7739                    && is_type_arithmetic(false_type)) {
7740                 result_type = semantic_arithmetic(true_type, false_type);
7741         } else if (same_compound_type(true_type, false_type)) {
7742                 /* just take 1 of the 2 types */
7743                 result_type = true_type;
7744         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7745                 type_t *pointer_type;
7746                 type_t *other_type;
7747                 expression_t *other_expression;
7748                 if (is_type_pointer(true_type) &&
7749                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7750                         pointer_type     = true_type;
7751                         other_type       = false_type;
7752                         other_expression = false_expression;
7753                 } else {
7754                         pointer_type     = false_type;
7755                         other_type       = true_type;
7756                         other_expression = true_expression;
7757                 }
7758
7759                 if (is_null_pointer_constant(other_expression)) {
7760                         result_type = pointer_type;
7761                 } else if (is_type_pointer(other_type)) {
7762                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7763                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
7764
7765                         type_t *to;
7766                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7767                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7768                                 to = type_void;
7769                         } else if (types_compatible(get_unqualified_type(to1),
7770                                                     get_unqualified_type(to2))) {
7771                                 to = to1;
7772                         } else {
7773                                 if (warning.other) {
7774                                         warningf(&conditional->base.source_position,
7775                                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
7776                                                         true_type, false_type);
7777                                 }
7778                                 to = type_void;
7779                         }
7780
7781                         type_t *const type =
7782                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7783                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7784                 } else if (is_type_integer(other_type)) {
7785                         if (warning.other) {
7786                                 warningf(&conditional->base.source_position,
7787                                                 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7788                         }
7789                         result_type = pointer_type;
7790                 } else {
7791                         if (is_type_valid(other_type)) {
7792                                 type_error_incompatible("while parsing conditional",
7793                                                 &expression->base.source_position, true_type, false_type);
7794                         }
7795                         result_type = type_error_type;
7796                 }
7797         } else {
7798                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7799                         type_error_incompatible("while parsing conditional",
7800                                                 &conditional->base.source_position, true_type,
7801                                                 false_type);
7802                 }
7803                 result_type = type_error_type;
7804         }
7805
7806         conditional->true_expression
7807                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7808         conditional->false_expression
7809                 = create_implicit_cast(false_expression, result_type);
7810         conditional->base.type = result_type;
7811         return result;
7812 }
7813
7814 /**
7815  * Parse an extension expression.
7816  */
7817 static expression_t *parse_extension(void)
7818 {
7819         eat(T___extension__);
7820
7821         bool old_gcc_extension   = in_gcc_extension;
7822         in_gcc_extension         = true;
7823         expression_t *expression = parse_subexpression(PREC_UNARY);
7824         in_gcc_extension         = old_gcc_extension;
7825         return expression;
7826 }
7827
7828 /**
7829  * Parse a __builtin_classify_type() expression.
7830  */
7831 static expression_t *parse_builtin_classify_type(void)
7832 {
7833         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7834         result->base.type    = type_int;
7835
7836         eat(T___builtin_classify_type);
7837
7838         expect('(', end_error);
7839         add_anchor_token(')');
7840         expression_t *expression = parse_expression();
7841         rem_anchor_token(')');
7842         expect(')', end_error);
7843         result->classify_type.type_expression = expression;
7844
7845         return result;
7846 end_error:
7847         return create_invalid_expression();
7848 }
7849
7850 /**
7851  * Parse a delete expression
7852  * ISO/IEC 14882:1998(E) §5.3.5
7853  */
7854 static expression_t *parse_delete(void)
7855 {
7856         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7857         result->base.type          = type_void;
7858
7859         eat(T_delete);
7860
7861         if (next_if('[')) {
7862                 result->kind = EXPR_UNARY_DELETE_ARRAY;
7863                 expect(']', end_error);
7864 end_error:;
7865         }
7866
7867         expression_t *const value = parse_subexpression(PREC_CAST);
7868         result->unary.value = value;
7869
7870         type_t *const type = skip_typeref(value->base.type);
7871         if (!is_type_pointer(type)) {
7872                 if (is_type_valid(type)) {
7873                         errorf(&value->base.source_position,
7874                                         "operand of delete must have pointer type");
7875                 }
7876         } else if (warning.other &&
7877                         is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7878                 warningf(&value->base.source_position,
7879                                 "deleting 'void*' is undefined");
7880         }
7881
7882         return result;
7883 }
7884
7885 /**
7886  * Parse a throw expression
7887  * ISO/IEC 14882:1998(E) §15:1
7888  */
7889 static expression_t *parse_throw(void)
7890 {
7891         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7892         result->base.type          = type_void;
7893
7894         eat(T_throw);
7895
7896         expression_t *value = NULL;
7897         switch (token.type) {
7898                 EXPRESSION_START {
7899                         value = parse_assignment_expression();
7900                         /* ISO/IEC 14882:1998(E) §15.1:3 */
7901                         type_t *const orig_type = value->base.type;
7902                         type_t *const type      = skip_typeref(orig_type);
7903                         if (is_type_incomplete(type)) {
7904                                 errorf(&value->base.source_position,
7905                                                 "cannot throw object of incomplete type '%T'", orig_type);
7906                         } else if (is_type_pointer(type)) {
7907                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
7908                                 if (is_type_incomplete(points_to) &&
7909                                                 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7910                                         errorf(&value->base.source_position,
7911                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
7912                                 }
7913                         }
7914                 }
7915
7916                 default:
7917                         break;
7918         }
7919         result->unary.value = value;
7920
7921         return result;
7922 }
7923
7924 static bool check_pointer_arithmetic(const source_position_t *source_position,
7925                                      type_t *pointer_type,
7926                                      type_t *orig_pointer_type)
7927 {
7928         type_t *points_to = pointer_type->pointer.points_to;
7929         points_to = skip_typeref(points_to);
7930
7931         if (is_type_incomplete(points_to)) {
7932                 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7933                         errorf(source_position,
7934                                "arithmetic with pointer to incomplete type '%T' not allowed",
7935                                orig_pointer_type);
7936                         return false;
7937                 } else if (warning.pointer_arith) {
7938                         warningf(source_position,
7939                                  "pointer of type '%T' used in arithmetic",
7940                                  orig_pointer_type);
7941                 }
7942         } else if (is_type_function(points_to)) {
7943                 if (!GNU_MODE) {
7944                         errorf(source_position,
7945                                "arithmetic with pointer to function type '%T' not allowed",
7946                                orig_pointer_type);
7947                         return false;
7948                 } else if (warning.pointer_arith) {
7949                         warningf(source_position,
7950                                  "pointer to a function '%T' used in arithmetic",
7951                                  orig_pointer_type);
7952                 }
7953         }
7954         return true;
7955 }
7956
7957 static bool is_lvalue(const expression_t *expression)
7958 {
7959         /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7960         switch (expression->kind) {
7961         case EXPR_ARRAY_ACCESS:
7962         case EXPR_COMPOUND_LITERAL:
7963         case EXPR_REFERENCE:
7964         case EXPR_SELECT:
7965         case EXPR_UNARY_DEREFERENCE:
7966                 return true;
7967
7968         default: {
7969                 type_t *type = skip_typeref(expression->base.type);
7970                 return
7971                         /* ISO/IEC 14882:1998(E) §3.10:3 */
7972                         is_type_reference(type) ||
7973                         /* Claim it is an lvalue, if the type is invalid.  There was a parse
7974                          * error before, which maybe prevented properly recognizing it as
7975                          * lvalue. */
7976                         !is_type_valid(type);
7977         }
7978         }
7979 }
7980
7981 static void semantic_incdec(unary_expression_t *expression)
7982 {
7983         type_t *const orig_type = expression->value->base.type;
7984         type_t *const type      = skip_typeref(orig_type);
7985         if (is_type_pointer(type)) {
7986                 if (!check_pointer_arithmetic(&expression->base.source_position,
7987                                               type, orig_type)) {
7988                         return;
7989                 }
7990         } else if (!is_type_real(type) && is_type_valid(type)) {
7991                 /* TODO: improve error message */
7992                 errorf(&expression->base.source_position,
7993                        "operation needs an arithmetic or pointer type");
7994                 return;
7995         }
7996         if (!is_lvalue(expression->value)) {
7997                 /* TODO: improve error message */
7998                 errorf(&expression->base.source_position, "lvalue required as operand");
7999         }
8000         expression->base.type = orig_type;
8001 }
8002
8003 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8004 {
8005         type_t *const orig_type = expression->value->base.type;
8006         type_t *const type      = skip_typeref(orig_type);
8007         if (!is_type_arithmetic(type)) {
8008                 if (is_type_valid(type)) {
8009                         /* TODO: improve error message */
8010                         errorf(&expression->base.source_position,
8011                                 "operation needs an arithmetic type");
8012                 }
8013                 return;
8014         }
8015
8016         expression->base.type = orig_type;
8017 }
8018
8019 static void semantic_unexpr_plus(unary_expression_t *expression)
8020 {
8021         semantic_unexpr_arithmetic(expression);
8022         if (warning.traditional)
8023                 warningf(&expression->base.source_position,
8024                         "traditional C rejects the unary plus operator");
8025 }
8026
8027 static void semantic_not(unary_expression_t *expression)
8028 {
8029         /* §6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
8030         semantic_condition(expression->value, "operand of !");
8031         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8032 }
8033
8034 static void semantic_unexpr_integer(unary_expression_t *expression)
8035 {
8036         type_t *const orig_type = expression->value->base.type;
8037         type_t *const type      = skip_typeref(orig_type);
8038         if (!is_type_integer(type)) {
8039                 if (is_type_valid(type)) {
8040                         errorf(&expression->base.source_position,
8041                                "operand of ~ must be of integer type");
8042                 }
8043                 return;
8044         }
8045
8046         expression->base.type = orig_type;
8047 }
8048
8049 static void semantic_dereference(unary_expression_t *expression)
8050 {
8051         type_t *const orig_type = expression->value->base.type;
8052         type_t *const type      = skip_typeref(orig_type);
8053         if (!is_type_pointer(type)) {
8054                 if (is_type_valid(type)) {
8055                         errorf(&expression->base.source_position,
8056                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8057                 }
8058                 return;
8059         }
8060
8061         type_t *result_type   = type->pointer.points_to;
8062         result_type           = automatic_type_conversion(result_type);
8063         expression->base.type = result_type;
8064 }
8065
8066 /**
8067  * Record that an address is taken (expression represents an lvalue).
8068  *
8069  * @param expression       the expression
8070  * @param may_be_register  if true, the expression might be an register
8071  */
8072 static void set_address_taken(expression_t *expression, bool may_be_register)
8073 {
8074         if (expression->kind != EXPR_REFERENCE)
8075                 return;
8076
8077         entity_t *const entity = expression->reference.entity;
8078
8079         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8080                 return;
8081
8082         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8083                         && !may_be_register) {
8084                 errorf(&expression->base.source_position,
8085                        "address of register %s '%Y' requested",
8086                        get_entity_kind_name(entity->kind), entity->base.symbol);
8087         }
8088
8089         if (entity->kind == ENTITY_VARIABLE) {
8090                 entity->variable.address_taken = true;
8091         } else {
8092                 assert(entity->kind == ENTITY_PARAMETER);
8093                 entity->parameter.address_taken = true;
8094         }
8095 }
8096
8097 /**
8098  * Check the semantic of the address taken expression.
8099  */
8100 static void semantic_take_addr(unary_expression_t *expression)
8101 {
8102         expression_t *value = expression->value;
8103         value->base.type    = revert_automatic_type_conversion(value);
8104
8105         type_t *orig_type = value->base.type;
8106         type_t *type      = skip_typeref(orig_type);
8107         if (!is_type_valid(type))
8108                 return;
8109
8110         /* §6.5.3.2 */
8111         if (!is_lvalue(value)) {
8112                 errorf(&expression->base.source_position, "'&' requires an lvalue");
8113         }
8114         if (type->kind == TYPE_BITFIELD) {
8115                 errorf(&expression->base.source_position,
8116                        "'&' not allowed on object with bitfield type '%T'",
8117                        type);
8118         }
8119
8120         set_address_taken(value, false);
8121
8122         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8123 }
8124
8125 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8126 static expression_t *parse_##unexpression_type(void)                         \
8127 {                                                                            \
8128         expression_t *unary_expression                                           \
8129                 = allocate_expression_zero(unexpression_type);                       \
8130         eat(token_type);                                                         \
8131         unary_expression->unary.value = parse_subexpression(PREC_UNARY);         \
8132                                                                                  \
8133         sfunc(&unary_expression->unary);                                         \
8134                                                                                  \
8135         return unary_expression;                                                 \
8136 }
8137
8138 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8139                                semantic_unexpr_arithmetic)
8140 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8141                                semantic_unexpr_plus)
8142 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8143                                semantic_not)
8144 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8145                                semantic_dereference)
8146 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8147                                semantic_take_addr)
8148 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8149                                semantic_unexpr_integer)
8150 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
8151                                semantic_incdec)
8152 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8153                                semantic_incdec)
8154
8155 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8156                                                sfunc)                         \
8157 static expression_t *parse_##unexpression_type(expression_t *left)            \
8158 {                                                                             \
8159         expression_t *unary_expression                                            \
8160                 = allocate_expression_zero(unexpression_type);                        \
8161         eat(token_type);                                                          \
8162         unary_expression->unary.value = left;                                     \
8163                                                                                   \
8164         sfunc(&unary_expression->unary);                                          \
8165                                                                               \
8166         return unary_expression;                                                  \
8167 }
8168
8169 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8170                                        EXPR_UNARY_POSTFIX_INCREMENT,
8171                                        semantic_incdec)
8172 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8173                                        EXPR_UNARY_POSTFIX_DECREMENT,
8174                                        semantic_incdec)
8175
8176 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8177 {
8178         /* TODO: handle complex + imaginary types */
8179
8180         type_left  = get_unqualified_type(type_left);
8181         type_right = get_unqualified_type(type_right);
8182
8183         /* §6.3.1.8 Usual arithmetic conversions */
8184         if (type_left == type_long_double || type_right == type_long_double) {
8185                 return type_long_double;
8186         } else if (type_left == type_double || type_right == type_double) {
8187                 return type_double;
8188         } else if (type_left == type_float || type_right == type_float) {
8189                 return type_float;
8190         }
8191
8192         type_left  = promote_integer(type_left);
8193         type_right = promote_integer(type_right);
8194
8195         if (type_left == type_right)
8196                 return type_left;
8197
8198         bool const signed_left  = is_type_signed(type_left);
8199         bool const signed_right = is_type_signed(type_right);
8200         int const  rank_left    = get_rank(type_left);
8201         int const  rank_right   = get_rank(type_right);
8202
8203         if (signed_left == signed_right)
8204                 return rank_left >= rank_right ? type_left : type_right;
8205
8206         int     s_rank;
8207         int     u_rank;
8208         type_t *s_type;
8209         type_t *u_type;
8210         if (signed_left) {
8211                 s_rank = rank_left;
8212                 s_type = type_left;
8213                 u_rank = rank_right;
8214                 u_type = type_right;
8215         } else {
8216                 s_rank = rank_right;
8217                 s_type = type_right;
8218                 u_rank = rank_left;
8219                 u_type = type_left;
8220         }
8221
8222         if (u_rank >= s_rank)
8223                 return u_type;
8224
8225         /* casting rank to atomic_type_kind is a bit hacky, but makes things
8226          * easier here... */
8227         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8228                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
8229                 return s_type;
8230
8231         switch (s_rank) {
8232                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
8233                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
8234                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8235
8236                 default: panic("invalid atomic type");
8237         }
8238 }
8239
8240 /**
8241  * Check the semantic restrictions for a binary expression.
8242  */
8243 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8244 {
8245         expression_t *const left            = expression->left;
8246         expression_t *const right           = expression->right;
8247         type_t       *const orig_type_left  = left->base.type;
8248         type_t       *const orig_type_right = right->base.type;
8249         type_t       *const type_left       = skip_typeref(orig_type_left);
8250         type_t       *const type_right      = skip_typeref(orig_type_right);
8251
8252         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8253                 /* TODO: improve error message */
8254                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8255                         errorf(&expression->base.source_position,
8256                                "operation needs arithmetic types");
8257                 }
8258                 return;
8259         }
8260
8261         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8262         expression->left      = create_implicit_cast(left, arithmetic_type);
8263         expression->right     = create_implicit_cast(right, arithmetic_type);
8264         expression->base.type = arithmetic_type;
8265 }
8266
8267 static void semantic_binexpr_integer(binary_expression_t *const expression)
8268 {
8269         expression_t *const left            = expression->left;
8270         expression_t *const right           = expression->right;
8271         type_t       *const orig_type_left  = left->base.type;
8272         type_t       *const orig_type_right = right->base.type;
8273         type_t       *const type_left       = skip_typeref(orig_type_left);
8274         type_t       *const type_right      = skip_typeref(orig_type_right);
8275
8276         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8277                 /* TODO: improve error message */
8278                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8279                         errorf(&expression->base.source_position,
8280                                "operation needs integer types");
8281                 }
8282                 return;
8283         }
8284
8285         type_t *const result_type = semantic_arithmetic(type_left, type_right);
8286         expression->left      = create_implicit_cast(left, result_type);
8287         expression->right     = create_implicit_cast(right, result_type);
8288         expression->base.type = result_type;
8289 }
8290
8291 static void warn_div_by_zero(binary_expression_t const *const expression)
8292 {
8293         if (!warning.div_by_zero ||
8294             !is_type_integer(expression->base.type))
8295                 return;
8296
8297         expression_t const *const right = expression->right;
8298         /* The type of the right operand can be different for /= */
8299         if (is_type_integer(right->base.type)                    &&
8300             is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8301             !fold_constant_to_bool(right)) {
8302                 warningf(&expression->base.source_position, "division by zero");
8303         }
8304 }
8305
8306 /**
8307  * Check the semantic restrictions for a div/mod expression.
8308  */
8309 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8310 {
8311         semantic_binexpr_arithmetic(expression);
8312         warn_div_by_zero(expression);
8313 }
8314
8315 static void warn_addsub_in_shift(const expression_t *const expr)
8316 {
8317         if (expr->base.parenthesized)
8318                 return;
8319
8320         char op;
8321         switch (expr->kind) {
8322                 case EXPR_BINARY_ADD: op = '+'; break;
8323                 case EXPR_BINARY_SUB: op = '-'; break;
8324                 default:              return;
8325         }
8326
8327         warningf(&expr->base.source_position,
8328                         "suggest parentheses around '%c' inside shift", op);
8329 }
8330
8331 static bool semantic_shift(binary_expression_t *expression)
8332 {
8333         expression_t *const left            = expression->left;
8334         expression_t *const right           = expression->right;
8335         type_t       *const orig_type_left  = left->base.type;
8336         type_t       *const orig_type_right = right->base.type;
8337         type_t       *      type_left       = skip_typeref(orig_type_left);
8338         type_t       *      type_right      = skip_typeref(orig_type_right);
8339
8340         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8341                 /* TODO: improve error message */
8342                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8343                         errorf(&expression->base.source_position,
8344                                "operands of shift operation must have integer types");
8345                 }
8346                 return false;
8347         }
8348
8349         type_left = promote_integer(type_left);
8350
8351         if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8352                 long count = fold_constant_to_int(right);
8353                 if (count < 0) {
8354                         warningf(&right->base.source_position,
8355                                         "shift count must be non-negative");
8356                 } else if ((unsigned long)count >=
8357                                 get_atomic_type_size(type_left->atomic.akind) * 8) {
8358                         warningf(&right->base.source_position,
8359                                         "shift count must be less than type width");
8360                 }
8361         }
8362
8363         type_right        = promote_integer(type_right);
8364         expression->right = create_implicit_cast(right, type_right);
8365
8366         return true;
8367 }
8368
8369 static void semantic_shift_op(binary_expression_t *expression)
8370 {
8371         expression_t *const left  = expression->left;
8372         expression_t *const right = expression->right;
8373
8374         if (!semantic_shift(expression))
8375                 return;
8376
8377         if (warning.parentheses) {
8378                 warn_addsub_in_shift(left);
8379                 warn_addsub_in_shift(right);
8380         }
8381
8382         type_t *const orig_type_left = left->base.type;
8383         type_t *      type_left      = skip_typeref(orig_type_left);
8384
8385         type_left             = promote_integer(type_left);
8386         expression->left      = create_implicit_cast(left, type_left);
8387         expression->base.type = type_left;
8388 }
8389
8390 static void semantic_add(binary_expression_t *expression)
8391 {
8392         expression_t *const left            = expression->left;
8393         expression_t *const right           = expression->right;
8394         type_t       *const orig_type_left  = left->base.type;
8395         type_t       *const orig_type_right = right->base.type;
8396         type_t       *const type_left       = skip_typeref(orig_type_left);
8397         type_t       *const type_right      = skip_typeref(orig_type_right);
8398
8399         /* §6.5.6 */
8400         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8401                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8402                 expression->left  = create_implicit_cast(left, arithmetic_type);
8403                 expression->right = create_implicit_cast(right, arithmetic_type);
8404                 expression->base.type = arithmetic_type;
8405         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8406                 check_pointer_arithmetic(&expression->base.source_position,
8407                                          type_left, orig_type_left);
8408                 expression->base.type = type_left;
8409         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8410                 check_pointer_arithmetic(&expression->base.source_position,
8411                                          type_right, orig_type_right);
8412                 expression->base.type = type_right;
8413         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8414                 errorf(&expression->base.source_position,
8415                        "invalid operands to binary + ('%T', '%T')",
8416                        orig_type_left, orig_type_right);
8417         }
8418 }
8419
8420 static void semantic_sub(binary_expression_t *expression)
8421 {
8422         expression_t            *const left            = expression->left;
8423         expression_t            *const right           = expression->right;
8424         type_t                  *const orig_type_left  = left->base.type;
8425         type_t                  *const orig_type_right = right->base.type;
8426         type_t                  *const type_left       = skip_typeref(orig_type_left);
8427         type_t                  *const type_right      = skip_typeref(orig_type_right);
8428         source_position_t const *const pos             = &expression->base.source_position;
8429
8430         /* §5.6.5 */
8431         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8432                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8433                 expression->left        = create_implicit_cast(left, arithmetic_type);
8434                 expression->right       = create_implicit_cast(right, arithmetic_type);
8435                 expression->base.type =  arithmetic_type;
8436         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8437                 check_pointer_arithmetic(&expression->base.source_position,
8438                                          type_left, orig_type_left);
8439                 expression->base.type = type_left;
8440         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8441                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8442                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8443                 if (!types_compatible(unqual_left, unqual_right)) {
8444                         errorf(pos,
8445                                "subtracting pointers to incompatible types '%T' and '%T'",
8446                                orig_type_left, orig_type_right);
8447                 } else if (!is_type_object(unqual_left)) {
8448                         if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8449                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8450                                        orig_type_left);
8451                         } else if (warning.other) {
8452                                 warningf(pos, "subtracting pointers to void");
8453                         }
8454                 }
8455                 expression->base.type = type_ptrdiff_t;
8456         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8457                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8458                        orig_type_left, orig_type_right);
8459         }
8460 }
8461
8462 static void warn_string_literal_address(expression_t const* expr)
8463 {
8464         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8465                 expr = expr->unary.value;
8466                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8467                         return;
8468                 expr = expr->unary.value;
8469         }
8470
8471         if (expr->kind == EXPR_STRING_LITERAL
8472                         || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8473                 warningf(&expr->base.source_position,
8474                         "comparison with string literal results in unspecified behaviour");
8475         }
8476 }
8477
8478 static void warn_comparison_in_comparison(const expression_t *const expr)
8479 {
8480         if (expr->base.parenthesized)
8481                 return;
8482         switch (expr->base.kind) {
8483                 case EXPR_BINARY_LESS:
8484                 case EXPR_BINARY_GREATER:
8485                 case EXPR_BINARY_LESSEQUAL:
8486                 case EXPR_BINARY_GREATEREQUAL:
8487                 case EXPR_BINARY_NOTEQUAL:
8488                 case EXPR_BINARY_EQUAL:
8489                         warningf(&expr->base.source_position,
8490                                         "comparisons like 'x <= y < z' do not have their mathematical meaning");
8491                         break;
8492                 default:
8493                         break;
8494         }
8495 }
8496
8497 static bool maybe_negative(expression_t const *const expr)
8498 {
8499         switch (is_constant_expression(expr)) {
8500                 case EXPR_CLASS_ERROR:    return false;
8501                 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8502                 default:                  return true;
8503         }
8504 }
8505
8506 /**
8507  * Check the semantics of comparison expressions.
8508  *
8509  * @param expression   The expression to check.
8510  */
8511 static void semantic_comparison(binary_expression_t *expression)
8512 {
8513         expression_t *left  = expression->left;
8514         expression_t *right = expression->right;
8515
8516         if (warning.address) {
8517                 warn_string_literal_address(left);
8518                 warn_string_literal_address(right);
8519
8520                 expression_t const* const func_left = get_reference_address(left);
8521                 if (func_left != NULL && is_null_pointer_constant(right)) {
8522                         warningf(&expression->base.source_position,
8523                                  "the address of '%Y' will never be NULL",
8524                                  func_left->reference.entity->base.symbol);
8525                 }
8526
8527                 expression_t const* const func_right = get_reference_address(right);
8528                 if (func_right != NULL && is_null_pointer_constant(right)) {
8529                         warningf(&expression->base.source_position,
8530                                  "the address of '%Y' will never be NULL",
8531                                  func_right->reference.entity->base.symbol);
8532                 }
8533         }
8534
8535         if (warning.parentheses) {
8536                 warn_comparison_in_comparison(left);
8537                 warn_comparison_in_comparison(right);
8538         }
8539
8540         type_t *orig_type_left  = left->base.type;
8541         type_t *orig_type_right = right->base.type;
8542         type_t *type_left       = skip_typeref(orig_type_left);
8543         type_t *type_right      = skip_typeref(orig_type_right);
8544
8545         /* TODO non-arithmetic types */
8546         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8547                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8548
8549                 /* test for signed vs unsigned compares */
8550                 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8551                         bool const signed_left  = is_type_signed(type_left);
8552                         bool const signed_right = is_type_signed(type_right);
8553                         if (signed_left != signed_right) {
8554                                 /* FIXME long long needs better const folding magic */
8555                                 /* TODO check whether constant value can be represented by other type */
8556                                 if ((signed_left  && maybe_negative(left)) ||
8557                                                 (signed_right && maybe_negative(right))) {
8558                                         warningf(&expression->base.source_position,
8559                                                         "comparison between signed and unsigned");
8560                                 }
8561                         }
8562                 }
8563
8564                 expression->left        = create_implicit_cast(left, arithmetic_type);
8565                 expression->right       = create_implicit_cast(right, arithmetic_type);
8566                 expression->base.type   = arithmetic_type;
8567                 if (warning.float_equal &&
8568                     (expression->base.kind == EXPR_BINARY_EQUAL ||
8569                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8570                     is_type_float(arithmetic_type)) {
8571                         warningf(&expression->base.source_position,
8572                                  "comparing floating point with == or != is unsafe");
8573                 }
8574         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8575                 /* TODO check compatibility */
8576         } else if (is_type_pointer(type_left)) {
8577                 expression->right = create_implicit_cast(right, type_left);
8578         } else if (is_type_pointer(type_right)) {
8579                 expression->left = create_implicit_cast(left, type_right);
8580         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8581                 type_error_incompatible("invalid operands in comparison",
8582                                         &expression->base.source_position,
8583                                         type_left, type_right);
8584         }
8585         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8586 }
8587
8588 /**
8589  * Checks if a compound type has constant fields.
8590  */
8591 static bool has_const_fields(const compound_type_t *type)
8592 {
8593         compound_t *compound = type->compound;
8594         entity_t   *entry    = compound->members.entities;
8595
8596         for (; entry != NULL; entry = entry->base.next) {
8597                 if (!is_declaration(entry))
8598                         continue;
8599
8600                 const type_t *decl_type = skip_typeref(entry->declaration.type);
8601                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8602                         return true;
8603         }
8604
8605         return false;
8606 }
8607
8608 static bool is_valid_assignment_lhs(expression_t const* const left)
8609 {
8610         type_t *const orig_type_left = revert_automatic_type_conversion(left);
8611         type_t *const type_left      = skip_typeref(orig_type_left);
8612
8613         if (!is_lvalue(left)) {
8614                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8615                        left);
8616                 return false;
8617         }
8618
8619         if (left->kind == EXPR_REFERENCE
8620                         && left->reference.entity->kind == ENTITY_FUNCTION) {
8621                 errorf(HERE, "cannot assign to function '%E'", left);
8622                 return false;
8623         }
8624
8625         if (is_type_array(type_left)) {
8626                 errorf(HERE, "cannot assign to array '%E'", left);
8627                 return false;
8628         }
8629         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8630                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8631                        orig_type_left);
8632                 return false;
8633         }
8634         if (is_type_incomplete(type_left)) {
8635                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8636                        left, orig_type_left);
8637                 return false;
8638         }
8639         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8640                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8641                        left, orig_type_left);
8642                 return false;
8643         }
8644
8645         return true;
8646 }
8647
8648 static void semantic_arithmetic_assign(binary_expression_t *expression)
8649 {
8650         expression_t *left            = expression->left;
8651         expression_t *right           = expression->right;
8652         type_t       *orig_type_left  = left->base.type;
8653         type_t       *orig_type_right = right->base.type;
8654
8655         if (!is_valid_assignment_lhs(left))
8656                 return;
8657
8658         type_t *type_left  = skip_typeref(orig_type_left);
8659         type_t *type_right = skip_typeref(orig_type_right);
8660
8661         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8662                 /* TODO: improve error message */
8663                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8664                         errorf(&expression->base.source_position,
8665                                "operation needs arithmetic types");
8666                 }
8667                 return;
8668         }
8669
8670         /* combined instructions are tricky. We can't create an implicit cast on
8671          * the left side, because we need the uncasted form for the store.
8672          * The ast2firm pass has to know that left_type must be right_type
8673          * for the arithmetic operation and create a cast by itself */
8674         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8675         expression->right       = create_implicit_cast(right, arithmetic_type);
8676         expression->base.type   = type_left;
8677 }
8678
8679 static void semantic_divmod_assign(binary_expression_t *expression)
8680 {
8681         semantic_arithmetic_assign(expression);
8682         warn_div_by_zero(expression);
8683 }
8684
8685 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8686 {
8687         expression_t *const left            = expression->left;
8688         expression_t *const right           = expression->right;
8689         type_t       *const orig_type_left  = left->base.type;
8690         type_t       *const orig_type_right = right->base.type;
8691         type_t       *const type_left       = skip_typeref(orig_type_left);
8692         type_t       *const type_right      = skip_typeref(orig_type_right);
8693
8694         if (!is_valid_assignment_lhs(left))
8695                 return;
8696
8697         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8698                 /* combined instructions are tricky. We can't create an implicit cast on
8699                  * the left side, because we need the uncasted form for the store.
8700                  * The ast2firm pass has to know that left_type must be right_type
8701                  * for the arithmetic operation and create a cast by itself */
8702                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8703                 expression->right     = create_implicit_cast(right, arithmetic_type);
8704                 expression->base.type = type_left;
8705         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8706                 check_pointer_arithmetic(&expression->base.source_position,
8707                                          type_left, orig_type_left);
8708                 expression->base.type = type_left;
8709         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8710                 errorf(&expression->base.source_position,
8711                        "incompatible types '%T' and '%T' in assignment",
8712                        orig_type_left, orig_type_right);
8713         }
8714 }
8715
8716 static void semantic_integer_assign(binary_expression_t *expression)
8717 {
8718         expression_t *left            = expression->left;
8719         expression_t *right           = expression->right;
8720         type_t       *orig_type_left  = left->base.type;
8721         type_t       *orig_type_right = right->base.type;
8722
8723         if (!is_valid_assignment_lhs(left))
8724                 return;
8725
8726         type_t *type_left  = skip_typeref(orig_type_left);
8727         type_t *type_right = skip_typeref(orig_type_right);
8728
8729         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8730                 /* TODO: improve error message */
8731                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8732                         errorf(&expression->base.source_position,
8733                                "operation needs integer types");
8734                 }
8735                 return;
8736         }
8737
8738         /* combined instructions are tricky. We can't create an implicit cast on
8739          * the left side, because we need the uncasted form for the store.
8740          * The ast2firm pass has to know that left_type must be right_type
8741          * for the arithmetic operation and create a cast by itself */
8742         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8743         expression->right       = create_implicit_cast(right, arithmetic_type);
8744         expression->base.type   = type_left;
8745 }
8746
8747 static void semantic_shift_assign(binary_expression_t *expression)
8748 {
8749         expression_t *left           = expression->left;
8750
8751         if (!is_valid_assignment_lhs(left))
8752                 return;
8753
8754         if (!semantic_shift(expression))
8755                 return;
8756
8757         expression->base.type = skip_typeref(left->base.type);
8758 }
8759
8760 static void warn_logical_and_within_or(const expression_t *const expr)
8761 {
8762         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8763                 return;
8764         if (expr->base.parenthesized)
8765                 return;
8766         warningf(&expr->base.source_position,
8767                         "suggest parentheses around && within ||");
8768 }
8769
8770 /**
8771  * Check the semantic restrictions of a logical expression.
8772  */
8773 static void semantic_logical_op(binary_expression_t *expression)
8774 {
8775         /* §6.5.13:2  Each of the operands shall have scalar type.
8776          * §6.5.14:2  Each of the operands shall have scalar type. */
8777         semantic_condition(expression->left,   "left operand of logical operator");
8778         semantic_condition(expression->right, "right operand of logical operator");
8779         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8780                         warning.parentheses) {
8781                 warn_logical_and_within_or(expression->left);
8782                 warn_logical_and_within_or(expression->right);
8783         }
8784         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8785 }
8786
8787 /**
8788  * Check the semantic restrictions of a binary assign expression.
8789  */
8790 static void semantic_binexpr_assign(binary_expression_t *expression)
8791 {
8792         expression_t *left           = expression->left;
8793         type_t       *orig_type_left = left->base.type;
8794
8795         if (!is_valid_assignment_lhs(left))
8796                 return;
8797
8798         assign_error_t error = semantic_assign(orig_type_left, expression->right);
8799         report_assign_error(error, orig_type_left, expression->right,
8800                         "assignment", &left->base.source_position);
8801         expression->right = create_implicit_cast(expression->right, orig_type_left);
8802         expression->base.type = orig_type_left;
8803 }
8804
8805 /**
8806  * Determine if the outermost operation (or parts thereof) of the given
8807  * expression has no effect in order to generate a warning about this fact.
8808  * Therefore in some cases this only examines some of the operands of the
8809  * expression (see comments in the function and examples below).
8810  * Examples:
8811  *   f() + 23;    // warning, because + has no effect
8812  *   x || f();    // no warning, because x controls execution of f()
8813  *   x ? y : f(); // warning, because y has no effect
8814  *   (void)x;     // no warning to be able to suppress the warning
8815  * This function can NOT be used for an "expression has definitely no effect"-
8816  * analysis. */
8817 static bool expression_has_effect(const expression_t *const expr)
8818 {
8819         switch (expr->kind) {
8820                 case EXPR_UNKNOWN:                    break;
8821                 case EXPR_INVALID:                    return true; /* do NOT warn */
8822                 case EXPR_REFERENCE:                  return false;
8823                 case EXPR_REFERENCE_ENUM_VALUE:       return false;
8824                 case EXPR_LABEL_ADDRESS:              return false;
8825
8826                 /* suppress the warning for microsoft __noop operations */
8827                 case EXPR_LITERAL_MS_NOOP:            return true;
8828                 case EXPR_LITERAL_BOOLEAN:
8829                 case EXPR_LITERAL_CHARACTER:
8830                 case EXPR_LITERAL_WIDE_CHARACTER:
8831                 case EXPR_LITERAL_INTEGER:
8832                 case EXPR_LITERAL_INTEGER_OCTAL:
8833                 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8834                 case EXPR_LITERAL_FLOATINGPOINT:
8835                 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8836                 case EXPR_STRING_LITERAL:             return false;
8837                 case EXPR_WIDE_STRING_LITERAL:        return false;
8838
8839                 case EXPR_CALL: {
8840                         const call_expression_t *const call = &expr->call;
8841                         if (call->function->kind != EXPR_REFERENCE)
8842                                 return true;
8843
8844                         switch (call->function->reference.entity->function.btk) {
8845                                 /* FIXME: which builtins have no effect? */
8846                                 default:                      return true;
8847                         }
8848                 }
8849
8850                 /* Generate the warning if either the left or right hand side of a
8851                  * conditional expression has no effect */
8852                 case EXPR_CONDITIONAL: {
8853                         conditional_expression_t const *const cond = &expr->conditional;
8854                         expression_t             const *const t    = cond->true_expression;
8855                         return
8856                                 (t == NULL || expression_has_effect(t)) &&
8857                                 expression_has_effect(cond->false_expression);
8858                 }
8859
8860                 case EXPR_SELECT:                     return false;
8861                 case EXPR_ARRAY_ACCESS:               return false;
8862                 case EXPR_SIZEOF:                     return false;
8863                 case EXPR_CLASSIFY_TYPE:              return false;
8864                 case EXPR_ALIGNOF:                    return false;
8865
8866                 case EXPR_FUNCNAME:                   return false;
8867                 case EXPR_BUILTIN_CONSTANT_P:         return false;
8868                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8869                 case EXPR_OFFSETOF:                   return false;
8870                 case EXPR_VA_START:                   return true;
8871                 case EXPR_VA_ARG:                     return true;
8872                 case EXPR_VA_COPY:                    return true;
8873                 case EXPR_STATEMENT:                  return true; // TODO
8874                 case EXPR_COMPOUND_LITERAL:           return false;
8875
8876                 case EXPR_UNARY_NEGATE:               return false;
8877                 case EXPR_UNARY_PLUS:                 return false;
8878                 case EXPR_UNARY_BITWISE_NEGATE:       return false;
8879                 case EXPR_UNARY_NOT:                  return false;
8880                 case EXPR_UNARY_DEREFERENCE:          return false;
8881                 case EXPR_UNARY_TAKE_ADDRESS:         return false;
8882                 case EXPR_UNARY_POSTFIX_INCREMENT:    return true;
8883                 case EXPR_UNARY_POSTFIX_DECREMENT:    return true;
8884                 case EXPR_UNARY_PREFIX_INCREMENT:     return true;
8885                 case EXPR_UNARY_PREFIX_DECREMENT:     return true;
8886
8887                 /* Treat void casts as if they have an effect in order to being able to
8888                  * suppress the warning */
8889                 case EXPR_UNARY_CAST: {
8890                         type_t *const type = skip_typeref(expr->base.type);
8891                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
8892                 }
8893
8894                 case EXPR_UNARY_CAST_IMPLICIT:        return true;
8895                 case EXPR_UNARY_ASSUME:               return true;
8896                 case EXPR_UNARY_DELETE:               return true;
8897                 case EXPR_UNARY_DELETE_ARRAY:         return true;
8898                 case EXPR_UNARY_THROW:                return true;
8899
8900                 case EXPR_BINARY_ADD:                 return false;
8901                 case EXPR_BINARY_SUB:                 return false;
8902                 case EXPR_BINARY_MUL:                 return false;
8903                 case EXPR_BINARY_DIV:                 return false;
8904                 case EXPR_BINARY_MOD:                 return false;
8905                 case EXPR_BINARY_EQUAL:               return false;
8906                 case EXPR_BINARY_NOTEQUAL:            return false;
8907                 case EXPR_BINARY_LESS:                return false;
8908                 case EXPR_BINARY_LESSEQUAL:           return false;
8909                 case EXPR_BINARY_GREATER:             return false;
8910                 case EXPR_BINARY_GREATEREQUAL:        return false;
8911                 case EXPR_BINARY_BITWISE_AND:         return false;
8912                 case EXPR_BINARY_BITWISE_OR:          return false;
8913                 case EXPR_BINARY_BITWISE_XOR:         return false;
8914                 case EXPR_BINARY_SHIFTLEFT:           return false;
8915                 case EXPR_BINARY_SHIFTRIGHT:          return false;
8916                 case EXPR_BINARY_ASSIGN:              return true;
8917                 case EXPR_BINARY_MUL_ASSIGN:          return true;
8918                 case EXPR_BINARY_DIV_ASSIGN:          return true;
8919                 case EXPR_BINARY_MOD_ASSIGN:          return true;
8920                 case EXPR_BINARY_ADD_ASSIGN:          return true;
8921                 case EXPR_BINARY_SUB_ASSIGN:          return true;
8922                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:    return true;
8923                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:   return true;
8924                 case EXPR_BINARY_BITWISE_AND_ASSIGN:  return true;
8925                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:  return true;
8926                 case EXPR_BINARY_BITWISE_OR_ASSIGN:   return true;
8927
8928                 /* Only examine the right hand side of && and ||, because the left hand
8929                  * side already has the effect of controlling the execution of the right
8930                  * hand side */
8931                 case EXPR_BINARY_LOGICAL_AND:
8932                 case EXPR_BINARY_LOGICAL_OR:
8933                 /* Only examine the right hand side of a comma expression, because the left
8934                  * hand side has a separate warning */
8935                 case EXPR_BINARY_COMMA:
8936                         return expression_has_effect(expr->binary.right);
8937
8938                 case EXPR_BINARY_ISGREATER:           return false;
8939                 case EXPR_BINARY_ISGREATEREQUAL:      return false;
8940                 case EXPR_BINARY_ISLESS:              return false;
8941                 case EXPR_BINARY_ISLESSEQUAL:         return false;
8942                 case EXPR_BINARY_ISLESSGREATER:       return false;
8943                 case EXPR_BINARY_ISUNORDERED:         return false;
8944         }
8945
8946         internal_errorf(HERE, "unexpected expression");
8947 }
8948
8949 static void semantic_comma(binary_expression_t *expression)
8950 {
8951         if (warning.unused_value) {
8952                 const expression_t *const left = expression->left;
8953                 if (!expression_has_effect(left)) {
8954                         warningf(&left->base.source_position,
8955                                  "left-hand operand of comma expression has no effect");
8956                 }
8957         }
8958         expression->base.type = expression->right->base.type;
8959 }
8960
8961 /**
8962  * @param prec_r precedence of the right operand
8963  */
8964 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8965 static expression_t *parse_##binexpression_type(expression_t *left)          \
8966 {                                                                            \
8967         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
8968         binexpr->binary.left  = left;                                            \
8969         eat(token_type);                                                         \
8970                                                                              \
8971         expression_t *right = parse_subexpression(prec_r);                       \
8972                                                                              \
8973         binexpr->binary.right = right;                                           \
8974         sfunc(&binexpr->binary);                                                 \
8975                                                                              \
8976         return binexpr;                                                          \
8977 }
8978
8979 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
8980 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
8981 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
8982 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
8983 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
8984 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
8985 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
8986 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
8987 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
8988 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
8989 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
8990 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
8991 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
8992 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_integer)
8993 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_integer)
8994 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_integer)
8995 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
8996 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
8997 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
8998 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
8999 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9000 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9001 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9002 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9003 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_shift_assign)
9004 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_shift_assign)
9005 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
9006 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_integer_assign)
9007 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
9008 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
9009
9010
9011 static expression_t *parse_subexpression(precedence_t precedence)
9012 {
9013         if (token.type < 0) {
9014                 return expected_expression_error();
9015         }
9016
9017         expression_parser_function_t *parser
9018                 = &expression_parsers[token.type];
9019         source_position_t             source_position = token.source_position;
9020         expression_t                 *left;
9021
9022         if (parser->parser != NULL) {
9023                 left = parser->parser();
9024         } else {
9025                 left = parse_primary_expression();
9026         }
9027         assert(left != NULL);
9028         left->base.source_position = source_position;
9029
9030         while (true) {
9031                 if (token.type < 0) {
9032                         return expected_expression_error();
9033                 }
9034
9035                 parser = &expression_parsers[token.type];
9036                 if (parser->infix_parser == NULL)
9037                         break;
9038                 if (parser->infix_precedence < precedence)
9039                         break;
9040
9041                 left = parser->infix_parser(left);
9042
9043                 assert(left != NULL);
9044                 assert(left->kind != EXPR_UNKNOWN);
9045                 left->base.source_position = source_position;
9046         }
9047
9048         return left;
9049 }
9050
9051 /**
9052  * Parse an expression.
9053  */
9054 static expression_t *parse_expression(void)
9055 {
9056         return parse_subexpression(PREC_EXPRESSION);
9057 }
9058
9059 /**
9060  * Register a parser for a prefix-like operator.
9061  *
9062  * @param parser      the parser function
9063  * @param token_type  the token type of the prefix token
9064  */
9065 static void register_expression_parser(parse_expression_function parser,
9066                                        int token_type)
9067 {
9068         expression_parser_function_t *entry = &expression_parsers[token_type];
9069
9070         if (entry->parser != NULL) {
9071                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9072                 panic("trying to register multiple expression parsers for a token");
9073         }
9074         entry->parser = parser;
9075 }
9076
9077 /**
9078  * Register a parser for an infix operator with given precedence.
9079  *
9080  * @param parser      the parser function
9081  * @param token_type  the token type of the infix operator
9082  * @param precedence  the precedence of the operator
9083  */
9084 static void register_infix_parser(parse_expression_infix_function parser,
9085                                   int token_type, precedence_t precedence)
9086 {
9087         expression_parser_function_t *entry = &expression_parsers[token_type];
9088
9089         if (entry->infix_parser != NULL) {
9090                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9091                 panic("trying to register multiple infix expression parsers for a "
9092                       "token");
9093         }
9094         entry->infix_parser     = parser;
9095         entry->infix_precedence = precedence;
9096 }
9097
9098 /**
9099  * Initialize the expression parsers.
9100  */
9101 static void init_expression_parsers(void)
9102 {
9103         memset(&expression_parsers, 0, sizeof(expression_parsers));
9104
9105         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
9106         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
9107         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
9108         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
9109         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
9110         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
9111         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
9112         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
9113         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
9114         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
9115         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
9116         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
9117         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
9118         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
9119         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
9120         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
9121         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
9122         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
9123         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9124         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
9125         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
9126         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
9127         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
9128         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
9129         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
9130         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
9131         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
9132         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
9133         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
9134         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
9135         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
9136         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
9137         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
9138         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
9139         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
9140         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
9141         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
9142
9143         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
9144         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
9145         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
9146         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
9147         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
9148         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
9149         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9150         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9151         register_expression_parser(parse_sizeof,                      T_sizeof);
9152         register_expression_parser(parse_alignof,                     T___alignof__);
9153         register_expression_parser(parse_extension,                   T___extension__);
9154         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
9155         register_expression_parser(parse_delete,                      T_delete);
9156         register_expression_parser(parse_throw,                       T_throw);
9157 }
9158
9159 /**
9160  * Parse a asm statement arguments specification.
9161  */
9162 static asm_argument_t *parse_asm_arguments(bool is_out)
9163 {
9164         asm_argument_t  *result = NULL;
9165         asm_argument_t **anchor = &result;
9166
9167         while (token.type == T_STRING_LITERAL || token.type == '[') {
9168                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9169                 memset(argument, 0, sizeof(argument[0]));
9170
9171                 if (next_if('[')) {
9172                         if (token.type != T_IDENTIFIER) {
9173                                 parse_error_expected("while parsing asm argument",
9174                                                      T_IDENTIFIER, NULL);
9175                                 return NULL;
9176                         }
9177                         argument->symbol = token.symbol;
9178
9179                         expect(']', end_error);
9180                 }
9181
9182                 argument->constraints = parse_string_literals();
9183                 expect('(', end_error);
9184                 add_anchor_token(')');
9185                 expression_t *expression = parse_expression();
9186                 rem_anchor_token(')');
9187                 if (is_out) {
9188                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
9189                          * change size or type representation (e.g. int -> long is ok, but
9190                          * int -> float is not) */
9191                         if (expression->kind == EXPR_UNARY_CAST) {
9192                                 type_t      *const type = expression->base.type;
9193                                 type_kind_t  const kind = type->kind;
9194                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9195                                         unsigned flags;
9196                                         unsigned size;
9197                                         if (kind == TYPE_ATOMIC) {
9198                                                 atomic_type_kind_t const akind = type->atomic.akind;
9199                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9200                                                 size  = get_atomic_type_size(akind);
9201                                         } else {
9202                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9203                                                 size  = get_atomic_type_size(get_intptr_kind());
9204                                         }
9205
9206                                         do {
9207                                                 expression_t *const value      = expression->unary.value;
9208                                                 type_t       *const value_type = value->base.type;
9209                                                 type_kind_t   const value_kind = value_type->kind;
9210
9211                                                 unsigned value_flags;
9212                                                 unsigned value_size;
9213                                                 if (value_kind == TYPE_ATOMIC) {
9214                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
9215                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9216                                                         value_size  = get_atomic_type_size(value_akind);
9217                                                 } else if (value_kind == TYPE_POINTER) {
9218                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9219                                                         value_size  = get_atomic_type_size(get_intptr_kind());
9220                                                 } else {
9221                                                         break;
9222                                                 }
9223
9224                                                 if (value_flags != flags || value_size != size)
9225                                                         break;
9226
9227                                                 expression = value;
9228                                         } while (expression->kind == EXPR_UNARY_CAST);
9229                                 }
9230                         }
9231
9232                         if (!is_lvalue(expression)) {
9233                                 errorf(&expression->base.source_position,
9234                                        "asm output argument is not an lvalue");
9235                         }
9236
9237                         if (argument->constraints.begin[0] == '=')
9238                                 determine_lhs_ent(expression, NULL);
9239                         else
9240                                 mark_vars_read(expression, NULL);
9241                 } else {
9242                         mark_vars_read(expression, NULL);
9243                 }
9244                 argument->expression = expression;
9245                 expect(')', end_error);
9246
9247                 set_address_taken(expression, true);
9248
9249                 *anchor = argument;
9250                 anchor  = &argument->next;
9251
9252                 if (!next_if(','))
9253                         break;
9254         }
9255
9256         return result;
9257 end_error:
9258         return NULL;
9259 }
9260
9261 /**
9262  * Parse a asm statement clobber specification.
9263  */
9264 static asm_clobber_t *parse_asm_clobbers(void)
9265 {
9266         asm_clobber_t *result  = NULL;
9267         asm_clobber_t **anchor = &result;
9268
9269         while (token.type == T_STRING_LITERAL) {
9270                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9271                 clobber->clobber       = parse_string_literals();
9272
9273                 *anchor = clobber;
9274                 anchor  = &clobber->next;
9275
9276                 if (!next_if(','))
9277                         break;
9278         }
9279
9280         return result;
9281 }
9282
9283 /**
9284  * Parse an asm statement.
9285  */
9286 static statement_t *parse_asm_statement(void)
9287 {
9288         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
9289         asm_statement_t *asm_statement = &statement->asms;
9290
9291         eat(T_asm);
9292
9293         if (next_if(T_volatile))
9294                 asm_statement->is_volatile = true;
9295
9296         expect('(', end_error);
9297         add_anchor_token(')');
9298         if (token.type != T_STRING_LITERAL) {
9299                 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9300                 goto end_of_asm;
9301         }
9302         asm_statement->asm_text = parse_string_literals();
9303
9304         add_anchor_token(':');
9305         if (!next_if(':')) {
9306                 rem_anchor_token(':');
9307                 goto end_of_asm;
9308         }
9309
9310         asm_statement->outputs = parse_asm_arguments(true);
9311         if (!next_if(':')) {
9312                 rem_anchor_token(':');
9313                 goto end_of_asm;
9314         }
9315
9316         asm_statement->inputs = parse_asm_arguments(false);
9317         if (!next_if(':')) {
9318                 rem_anchor_token(':');
9319                 goto end_of_asm;
9320         }
9321         rem_anchor_token(':');
9322
9323         asm_statement->clobbers = parse_asm_clobbers();
9324
9325 end_of_asm:
9326         rem_anchor_token(')');
9327         expect(')', end_error);
9328         expect(';', end_error);
9329
9330         if (asm_statement->outputs == NULL) {
9331                 /* GCC: An 'asm' instruction without any output operands will be treated
9332                  * identically to a volatile 'asm' instruction. */
9333                 asm_statement->is_volatile = true;
9334         }
9335
9336         return statement;
9337 end_error:
9338         return create_invalid_statement();
9339 }
9340
9341 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9342 {
9343         statement_t *inner_stmt;
9344         switch (token.type) {
9345                 case '}':
9346                         errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9347                         inner_stmt = create_invalid_statement();
9348                         break;
9349
9350                 case ';':
9351                         if (label->kind == STATEMENT_LABEL) {
9352                                 /* Eat an empty statement here, to avoid the warning about an empty
9353                                  * statement after a label.  label:; is commonly used to have a label
9354                                  * before a closing brace. */
9355                                 inner_stmt = create_empty_statement();
9356                                 next_token();
9357                                 break;
9358                         }
9359                         /* FALLTHROUGH */
9360
9361                 default:
9362                         inner_stmt = parse_statement();
9363                         /* ISO/IEC 14882:1998(E) §6:1/§6.7  Declarations are statements */
9364                         if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9365                                 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9366                         }
9367                         break;
9368         }
9369         return inner_stmt;
9370 }
9371
9372 /**
9373  * Parse a case statement.
9374  */
9375 static statement_t *parse_case_statement(void)
9376 {
9377         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9378         source_position_t *const pos       = &statement->base.source_position;
9379
9380         eat(T_case);
9381
9382         expression_t *const expression   = parse_expression();
9383         statement->case_label.expression = expression;
9384         expression_classification_t const expr_class = is_constant_expression(expression);
9385         if (expr_class != EXPR_CLASS_CONSTANT) {
9386                 if (expr_class != EXPR_CLASS_ERROR) {
9387                         errorf(pos, "case label does not reduce to an integer constant");
9388                 }
9389                 statement->case_label.is_bad = true;
9390         } else {
9391                 long const val = fold_constant_to_int(expression);
9392                 statement->case_label.first_case = val;
9393                 statement->case_label.last_case  = val;
9394         }
9395
9396         if (GNU_MODE) {
9397                 if (next_if(T_DOTDOTDOT)) {
9398                         expression_t *const end_range   = parse_expression();
9399                         statement->case_label.end_range = end_range;
9400                         expression_classification_t const end_class = is_constant_expression(end_range);
9401                         if (end_class != EXPR_CLASS_CONSTANT) {
9402                                 if (end_class != EXPR_CLASS_ERROR) {
9403                                         errorf(pos, "case range does not reduce to an integer constant");
9404                                 }
9405                                 statement->case_label.is_bad = true;
9406                         } else {
9407                                 long const val = fold_constant_to_int(end_range);
9408                                 statement->case_label.last_case = val;
9409
9410                                 if (warning.other && val < statement->case_label.first_case) {
9411                                         statement->case_label.is_empty_range = true;
9412                                         warningf(pos, "empty range specified");
9413                                 }
9414                         }
9415                 }
9416         }
9417
9418         PUSH_PARENT(statement);
9419
9420         expect(':', end_error);
9421 end_error:
9422
9423         if (current_switch != NULL) {
9424                 if (! statement->case_label.is_bad) {
9425                         /* Check for duplicate case values */
9426                         case_label_statement_t *c = &statement->case_label;
9427                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9428                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9429                                         continue;
9430
9431                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9432                                         continue;
9433
9434                                 errorf(pos, "duplicate case value (previously used %P)",
9435                                        &l->base.source_position);
9436                                 break;
9437                         }
9438                 }
9439                 /* link all cases into the switch statement */
9440                 if (current_switch->last_case == NULL) {
9441                         current_switch->first_case      = &statement->case_label;
9442                 } else {
9443                         current_switch->last_case->next = &statement->case_label;
9444                 }
9445                 current_switch->last_case = &statement->case_label;
9446         } else {
9447                 errorf(pos, "case label not within a switch statement");
9448         }
9449
9450         statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9451
9452         POP_PARENT;
9453         return statement;
9454 }
9455
9456 /**
9457  * Parse a default statement.
9458  */
9459 static statement_t *parse_default_statement(void)
9460 {
9461         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9462
9463         eat(T_default);
9464
9465         PUSH_PARENT(statement);
9466
9467         expect(':', end_error);
9468 end_error:
9469
9470         if (current_switch != NULL) {
9471                 const case_label_statement_t *def_label = current_switch->default_label;
9472                 if (def_label != NULL) {
9473                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9474                                &def_label->base.source_position);
9475                 } else {
9476                         current_switch->default_label = &statement->case_label;
9477
9478                         /* link all cases into the switch statement */
9479                         if (current_switch->last_case == NULL) {
9480                                 current_switch->first_case      = &statement->case_label;
9481                         } else {
9482                                 current_switch->last_case->next = &statement->case_label;
9483                         }
9484                         current_switch->last_case = &statement->case_label;
9485                 }
9486         } else {
9487                 errorf(&statement->base.source_position,
9488                         "'default' label not within a switch statement");
9489         }
9490
9491         statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9492
9493         POP_PARENT;
9494         return statement;
9495 }
9496
9497 /**
9498  * Parse a label statement.
9499  */
9500 static statement_t *parse_label_statement(void)
9501 {
9502         assert(token.type == T_IDENTIFIER);
9503         symbol_t *symbol = token.symbol;
9504         label_t  *label  = get_label(symbol);
9505
9506         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9507         statement->label.label       = label;
9508
9509         next_token();
9510
9511         PUSH_PARENT(statement);
9512
9513         /* if statement is already set then the label is defined twice,
9514          * otherwise it was just mentioned in a goto/local label declaration so far
9515          */
9516         if (label->statement != NULL) {
9517                 errorf(HERE, "duplicate label '%Y' (declared %P)",
9518                        symbol, &label->base.source_position);
9519         } else {
9520                 label->base.source_position = token.source_position;
9521                 label->statement            = statement;
9522         }
9523
9524         eat(':');
9525
9526         statement->label.statement = parse_label_inner_statement(statement, "label");
9527
9528         /* remember the labels in a list for later checking */
9529         *label_anchor = &statement->label;
9530         label_anchor  = &statement->label.next;
9531
9532         POP_PARENT;
9533         return statement;
9534 }
9535
9536 /**
9537  * Parse an if statement.
9538  */
9539 static statement_t *parse_if(void)
9540 {
9541         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9542
9543         eat(T_if);
9544
9545         PUSH_PARENT(statement);
9546
9547         add_anchor_token('{');
9548
9549         expect('(', end_error);
9550         add_anchor_token(')');
9551         expression_t *const expr = parse_expression();
9552         statement->ifs.condition = expr;
9553         /* §6.8.4.1:1  The controlling expression of an if statement shall have
9554          *             scalar type. */
9555         semantic_condition(expr, "condition of 'if'-statment");
9556         mark_vars_read(expr, NULL);
9557         rem_anchor_token(')');
9558         expect(')', end_error);
9559
9560 end_error:
9561         rem_anchor_token('{');
9562
9563         add_anchor_token(T_else);
9564         statement_t *const true_stmt = parse_statement();
9565         statement->ifs.true_statement = true_stmt;
9566         rem_anchor_token(T_else);
9567
9568         if (next_if(T_else)) {
9569                 statement->ifs.false_statement = parse_statement();
9570         } else if (warning.parentheses &&
9571                         true_stmt->kind == STATEMENT_IF &&
9572                         true_stmt->ifs.false_statement != NULL) {
9573                 warningf(&true_stmt->base.source_position,
9574                                 "suggest explicit braces to avoid ambiguous 'else'");
9575         }
9576
9577         POP_PARENT;
9578         return statement;
9579 }
9580
9581 /**
9582  * Check that all enums are handled in a switch.
9583  *
9584  * @param statement  the switch statement to check
9585  */
9586 static void check_enum_cases(const switch_statement_t *statement)
9587 {
9588         const type_t *type = skip_typeref(statement->expression->base.type);
9589         if (! is_type_enum(type))
9590                 return;
9591         const enum_type_t *enumt = &type->enumt;
9592
9593         /* if we have a default, no warnings */
9594         if (statement->default_label != NULL)
9595                 return;
9596
9597         /* FIXME: calculation of value should be done while parsing */
9598         /* TODO: quadratic algorithm here. Change to an n log n one */
9599         long            last_value = -1;
9600         const entity_t *entry      = enumt->enume->base.next;
9601         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9602              entry = entry->base.next) {
9603                 const expression_t *expression = entry->enum_value.value;
9604                 long                value      = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9605                 bool                found      = false;
9606                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9607                         if (l->expression == NULL)
9608                                 continue;
9609                         if (l->first_case <= value && value <= l->last_case) {
9610                                 found = true;
9611                                 break;
9612                         }
9613                 }
9614                 if (! found) {
9615                         warningf(&statement->base.source_position,
9616                                  "enumeration value '%Y' not handled in switch",
9617                                  entry->base.symbol);
9618                 }
9619                 last_value = value;
9620         }
9621 }
9622
9623 /**
9624  * Parse a switch statement.
9625  */
9626 static statement_t *parse_switch(void)
9627 {
9628         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9629
9630         eat(T_switch);
9631
9632         PUSH_PARENT(statement);
9633
9634         expect('(', end_error);
9635         add_anchor_token(')');
9636         expression_t *const expr = parse_expression();
9637         mark_vars_read(expr, NULL);
9638         type_t       *      type = skip_typeref(expr->base.type);
9639         if (is_type_integer(type)) {
9640                 type = promote_integer(type);
9641                 if (warning.traditional) {
9642                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9643                                 warningf(&expr->base.source_position,
9644                                         "'%T' switch expression not converted to '%T' in ISO C",
9645                                         type, type_int);
9646                         }
9647                 }
9648         } else if (is_type_valid(type)) {
9649                 errorf(&expr->base.source_position,
9650                        "switch quantity is not an integer, but '%T'", type);
9651                 type = type_error_type;
9652         }
9653         statement->switchs.expression = create_implicit_cast(expr, type);
9654         expect(')', end_error);
9655         rem_anchor_token(')');
9656
9657         switch_statement_t *rem = current_switch;
9658         current_switch          = &statement->switchs;
9659         statement->switchs.body = parse_statement();
9660         current_switch          = rem;
9661
9662         if (warning.switch_default &&
9663             statement->switchs.default_label == NULL) {
9664                 warningf(&statement->base.source_position, "switch has no default case");
9665         }
9666         if (warning.switch_enum)
9667                 check_enum_cases(&statement->switchs);
9668
9669         POP_PARENT;
9670         return statement;
9671 end_error:
9672         POP_PARENT;
9673         return create_invalid_statement();
9674 }
9675
9676 static statement_t *parse_loop_body(statement_t *const loop)
9677 {
9678         statement_t *const rem = current_loop;
9679         current_loop = loop;
9680
9681         statement_t *const body = parse_statement();
9682
9683         current_loop = rem;
9684         return body;
9685 }
9686
9687 /**
9688  * Parse a while statement.
9689  */
9690 static statement_t *parse_while(void)
9691 {
9692         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9693
9694         eat(T_while);
9695
9696         PUSH_PARENT(statement);
9697
9698         expect('(', end_error);
9699         add_anchor_token(')');
9700         expression_t *const cond = parse_expression();
9701         statement->whiles.condition = cond;
9702         /* §6.8.5:2    The controlling expression of an iteration statement shall
9703          *             have scalar type. */
9704         semantic_condition(cond, "condition of 'while'-statement");
9705         mark_vars_read(cond, NULL);
9706         rem_anchor_token(')');
9707         expect(')', end_error);
9708
9709         statement->whiles.body = parse_loop_body(statement);
9710
9711         POP_PARENT;
9712         return statement;
9713 end_error:
9714         POP_PARENT;
9715         return create_invalid_statement();
9716 }
9717
9718 /**
9719  * Parse a do statement.
9720  */
9721 static statement_t *parse_do(void)
9722 {
9723         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9724
9725         eat(T_do);
9726
9727         PUSH_PARENT(statement);
9728
9729         add_anchor_token(T_while);
9730         statement->do_while.body = parse_loop_body(statement);
9731         rem_anchor_token(T_while);
9732
9733         expect(T_while, end_error);
9734         expect('(', end_error);
9735         add_anchor_token(')');
9736         expression_t *const cond = parse_expression();
9737         statement->do_while.condition = cond;
9738         /* §6.8.5:2    The controlling expression of an iteration statement shall
9739          *             have scalar type. */
9740         semantic_condition(cond, "condition of 'do-while'-statement");
9741         mark_vars_read(cond, NULL);
9742         rem_anchor_token(')');
9743         expect(')', end_error);
9744         expect(';', end_error);
9745
9746         POP_PARENT;
9747         return statement;
9748 end_error:
9749         POP_PARENT;
9750         return create_invalid_statement();
9751 }
9752
9753 /**
9754  * Parse a for statement.
9755  */
9756 static statement_t *parse_for(void)
9757 {
9758         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9759
9760         eat(T_for);
9761
9762         expect('(', end_error1);
9763         add_anchor_token(')');
9764
9765         PUSH_PARENT(statement);
9766
9767         size_t const  top       = environment_top();
9768         scope_t      *old_scope = scope_push(&statement->fors.scope);
9769
9770         bool old_gcc_extension = in_gcc_extension;
9771         while (next_if(T___extension__)) {
9772                 in_gcc_extension = true;
9773         }
9774
9775         if (next_if(';')) {
9776         } else if (is_declaration_specifier(&token, false)) {
9777                 parse_declaration(record_entity, DECL_FLAGS_NONE);
9778         } else {
9779                 add_anchor_token(';');
9780                 expression_t *const init = parse_expression();
9781                 statement->fors.initialisation = init;
9782                 mark_vars_read(init, ENT_ANY);
9783                 if (warning.unused_value && !expression_has_effect(init)) {
9784                         warningf(&init->base.source_position,
9785                                         "initialisation of 'for'-statement has no effect");
9786                 }
9787                 rem_anchor_token(';');
9788                 expect(';', end_error2);
9789         }
9790         in_gcc_extension = old_gcc_extension;
9791
9792         if (token.type != ';') {
9793                 add_anchor_token(';');
9794                 expression_t *const cond = parse_expression();
9795                 statement->fors.condition = cond;
9796                 /* §6.8.5:2    The controlling expression of an iteration statement
9797                  *             shall have scalar type. */
9798                 semantic_condition(cond, "condition of 'for'-statement");
9799                 mark_vars_read(cond, NULL);
9800                 rem_anchor_token(';');
9801         }
9802         expect(';', end_error2);
9803         if (token.type != ')') {
9804                 expression_t *const step = parse_expression();
9805                 statement->fors.step = step;
9806                 mark_vars_read(step, ENT_ANY);
9807                 if (warning.unused_value && !expression_has_effect(step)) {
9808                         warningf(&step->base.source_position,
9809                                  "step of 'for'-statement has no effect");
9810                 }
9811         }
9812         expect(')', end_error2);
9813         rem_anchor_token(')');
9814         statement->fors.body = parse_loop_body(statement);
9815
9816         assert(current_scope == &statement->fors.scope);
9817         scope_pop(old_scope);
9818         environment_pop_to(top);
9819
9820         POP_PARENT;
9821         return statement;
9822
9823 end_error2:
9824         POP_PARENT;
9825         rem_anchor_token(')');
9826         assert(current_scope == &statement->fors.scope);
9827         scope_pop(old_scope);
9828         environment_pop_to(top);
9829         /* fallthrough */
9830
9831 end_error1:
9832         return create_invalid_statement();
9833 }
9834
9835 /**
9836  * Parse a goto statement.
9837  */
9838 static statement_t *parse_goto(void)
9839 {
9840         statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9841         eat(T_goto);
9842
9843         if (GNU_MODE && next_if('*')) {
9844                 expression_t *expression = parse_expression();
9845                 mark_vars_read(expression, NULL);
9846
9847                 /* Argh: although documentation says the expression must be of type void*,
9848                  * gcc accepts anything that can be casted into void* without error */
9849                 type_t *type = expression->base.type;
9850
9851                 if (type != type_error_type) {
9852                         if (!is_type_pointer(type) && !is_type_integer(type)) {
9853                                 errorf(&expression->base.source_position,
9854                                         "cannot convert to a pointer type");
9855                         } else if (warning.other && type != type_void_ptr) {
9856                                 warningf(&expression->base.source_position,
9857                                         "type of computed goto expression should be 'void*' not '%T'", type);
9858                         }
9859                         expression = create_implicit_cast(expression, type_void_ptr);
9860                 }
9861
9862                 statement->gotos.expression = expression;
9863         } else if (token.type == T_IDENTIFIER) {
9864                 symbol_t *symbol = token.symbol;
9865                 next_token();
9866                 statement->gotos.label = get_label(symbol);
9867         } else {
9868                 if (GNU_MODE)
9869                         parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9870                 else
9871                         parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9872                 eat_until_anchor();
9873                 return create_invalid_statement();
9874         }
9875
9876         /* remember the goto's in a list for later checking */
9877         *goto_anchor = &statement->gotos;
9878         goto_anchor  = &statement->gotos.next;
9879
9880         expect(';', end_error);
9881
9882 end_error:
9883         return statement;
9884 }
9885
9886 /**
9887  * Parse a continue statement.
9888  */
9889 static statement_t *parse_continue(void)
9890 {
9891         if (current_loop == NULL) {
9892                 errorf(HERE, "continue statement not within loop");
9893         }
9894
9895         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9896
9897         eat(T_continue);
9898         expect(';', end_error);
9899
9900 end_error:
9901         return statement;
9902 }
9903
9904 /**
9905  * Parse a break statement.
9906  */
9907 static statement_t *parse_break(void)
9908 {
9909         if (current_switch == NULL && current_loop == NULL) {
9910                 errorf(HERE, "break statement not within loop or switch");
9911         }
9912
9913         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9914
9915         eat(T_break);
9916         expect(';', end_error);
9917
9918 end_error:
9919         return statement;
9920 }
9921
9922 /**
9923  * Parse a __leave statement.
9924  */
9925 static statement_t *parse_leave_statement(void)
9926 {
9927         if (current_try == NULL) {
9928                 errorf(HERE, "__leave statement not within __try");
9929         }
9930
9931         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9932
9933         eat(T___leave);
9934         expect(';', end_error);
9935
9936 end_error:
9937         return statement;
9938 }
9939
9940 /**
9941  * Check if a given entity represents a local variable.
9942  */
9943 static bool is_local_variable(const entity_t *entity)
9944 {
9945         if (entity->kind != ENTITY_VARIABLE)
9946                 return false;
9947
9948         switch ((storage_class_tag_t) entity->declaration.storage_class) {
9949         case STORAGE_CLASS_AUTO:
9950         case STORAGE_CLASS_REGISTER: {
9951                 const type_t *type = skip_typeref(entity->declaration.type);
9952                 if (is_type_function(type)) {
9953                         return false;
9954                 } else {
9955                         return true;
9956                 }
9957         }
9958         default:
9959                 return false;
9960         }
9961 }
9962
9963 /**
9964  * Check if a given expression represents a local variable.
9965  */
9966 static bool expression_is_local_variable(const expression_t *expression)
9967 {
9968         if (expression->base.kind != EXPR_REFERENCE) {
9969                 return false;
9970         }
9971         const entity_t *entity = expression->reference.entity;
9972         return is_local_variable(entity);
9973 }
9974
9975 /**
9976  * Check if a given expression represents a local variable and
9977  * return its declaration then, else return NULL.
9978  */
9979 entity_t *expression_is_variable(const expression_t *expression)
9980 {
9981         if (expression->base.kind != EXPR_REFERENCE) {
9982                 return NULL;
9983         }
9984         entity_t *entity = expression->reference.entity;
9985         if (entity->kind != ENTITY_VARIABLE)
9986                 return NULL;
9987
9988         return entity;
9989 }
9990
9991 /**
9992  * Parse a return statement.
9993  */
9994 static statement_t *parse_return(void)
9995 {
9996         eat(T_return);
9997
9998         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9999
10000         expression_t *return_value = NULL;
10001         if (token.type != ';') {
10002                 return_value = parse_expression();
10003                 mark_vars_read(return_value, NULL);
10004         }
10005
10006         const type_t *const func_type = skip_typeref(current_function->base.type);
10007         assert(is_type_function(func_type));
10008         type_t *const return_type = skip_typeref(func_type->function.return_type);
10009
10010         source_position_t const *const pos = &statement->base.source_position;
10011         if (return_value != NULL) {
10012                 type_t *return_value_type = skip_typeref(return_value->base.type);
10013
10014                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10015                         if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10016                                 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10017                                 /* Only warn in C mode, because GCC does the same */
10018                                 if (c_mode & _CXX || strict_mode) {
10019                                         errorf(pos,
10020                                                         "'return' with a value, in function returning 'void'");
10021                                 } else if (warning.other) {
10022                                         warningf(pos,
10023                                                         "'return' with a value, in function returning 'void'");
10024                                 }
10025                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10026                                 /* Only warn in C mode, because GCC does the same */
10027                                 if (strict_mode) {
10028                                         errorf(pos,
10029                                                         "'return' with expression in function returning 'void'");
10030                                 } else if (warning.other) {
10031                                         warningf(pos,
10032                                                         "'return' with expression in function returning 'void'");
10033                                 }
10034                         }
10035                 } else {
10036                         assign_error_t error = semantic_assign(return_type, return_value);
10037                         report_assign_error(error, return_type, return_value, "'return'",
10038                                             pos);
10039                 }
10040                 return_value = create_implicit_cast(return_value, return_type);
10041                 /* check for returning address of a local var */
10042                 if (warning.other && return_value != NULL
10043                     && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10044                         const expression_t *expression = return_value->unary.value;
10045                         if (expression_is_local_variable(expression)) {
10046                                 warningf(pos, "function returns address of local variable");
10047                         }
10048                 }
10049         } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10050                 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10051                 if (c_mode & _CXX || strict_mode) {
10052                         errorf(pos,
10053                                "'return' without value, in function returning non-void");
10054                 } else {
10055                         warningf(pos,
10056                                  "'return' without value, in function returning non-void");
10057                 }
10058         }
10059         statement->returns.value = return_value;
10060
10061         expect(';', end_error);
10062
10063 end_error:
10064         return statement;
10065 }
10066
10067 /**
10068  * Parse a declaration statement.
10069  */
10070 static statement_t *parse_declaration_statement(void)
10071 {
10072         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10073
10074         entity_t *before = current_scope->last_entity;
10075         if (GNU_MODE) {
10076                 parse_external_declaration();
10077         } else {
10078                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10079         }
10080
10081         declaration_statement_t *const decl  = &statement->declaration;
10082         entity_t                *const begin =
10083                 before != NULL ? before->base.next : current_scope->entities;
10084         decl->declarations_begin = begin;
10085         decl->declarations_end   = begin != NULL ? current_scope->last_entity : NULL;
10086
10087         return statement;
10088 }
10089
10090 /**
10091  * Parse an expression statement, ie. expr ';'.
10092  */
10093 static statement_t *parse_expression_statement(void)
10094 {
10095         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10096
10097         expression_t *const expr         = parse_expression();
10098         statement->expression.expression = expr;
10099         mark_vars_read(expr, ENT_ANY);
10100
10101         expect(';', end_error);
10102
10103 end_error:
10104         return statement;
10105 }
10106
10107 /**
10108  * Parse a microsoft __try { } __finally { } or
10109  * __try{ } __except() { }
10110  */
10111 static statement_t *parse_ms_try_statment(void)
10112 {
10113         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10114         eat(T___try);
10115
10116         PUSH_PARENT(statement);
10117
10118         ms_try_statement_t *rem = current_try;
10119         current_try = &statement->ms_try;
10120         statement->ms_try.try_statement = parse_compound_statement(false);
10121         current_try = rem;
10122
10123         POP_PARENT;
10124
10125         if (next_if(T___except)) {
10126                 expect('(', end_error);
10127                 add_anchor_token(')');
10128                 expression_t *const expr = parse_expression();
10129                 mark_vars_read(expr, NULL);
10130                 type_t       *      type = skip_typeref(expr->base.type);
10131                 if (is_type_integer(type)) {
10132                         type = promote_integer(type);
10133                 } else if (is_type_valid(type)) {
10134                         errorf(&expr->base.source_position,
10135                                "__expect expression is not an integer, but '%T'", type);
10136                         type = type_error_type;
10137                 }
10138                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10139                 rem_anchor_token(')');
10140                 expect(')', end_error);
10141                 statement->ms_try.final_statement = parse_compound_statement(false);
10142         } else if (next_if(T__finally)) {
10143                 statement->ms_try.final_statement = parse_compound_statement(false);
10144         } else {
10145                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10146                 return create_invalid_statement();
10147         }
10148         return statement;
10149 end_error:
10150         return create_invalid_statement();
10151 }
10152
10153 static statement_t *parse_empty_statement(void)
10154 {
10155         if (warning.empty_statement) {
10156                 warningf(HERE, "statement is empty");
10157         }
10158         statement_t *const statement = create_empty_statement();
10159         eat(';');
10160         return statement;
10161 }
10162
10163 static statement_t *parse_local_label_declaration(void)
10164 {
10165         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10166
10167         eat(T___label__);
10168
10169         entity_t *begin   = NULL;
10170         entity_t *end     = NULL;
10171         entity_t **anchor = &begin;
10172         do {
10173                 if (token.type != T_IDENTIFIER) {
10174                         parse_error_expected("while parsing local label declaration",
10175                                 T_IDENTIFIER, NULL);
10176                         goto end_error;
10177                 }
10178                 symbol_t *symbol = token.symbol;
10179                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10180                 if (entity != NULL && entity->base.parent_scope == current_scope) {
10181                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10182                                symbol, &entity->base.source_position);
10183                 } else {
10184                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10185
10186                         entity->base.parent_scope    = current_scope;
10187                         entity->base.namespc         = NAMESPACE_LABEL;
10188                         entity->base.source_position = token.source_position;
10189                         entity->base.symbol          = symbol;
10190
10191                         *anchor = entity;
10192                         anchor  = &entity->base.next;
10193                         end     = entity;
10194
10195                         environment_push(entity);
10196                 }
10197                 next_token();
10198         } while (next_if(','));
10199         expect(';', end_error);
10200 end_error:
10201         statement->declaration.declarations_begin = begin;
10202         statement->declaration.declarations_end   = end;
10203         return statement;
10204 }
10205
10206 static void parse_namespace_definition(void)
10207 {
10208         eat(T_namespace);
10209
10210         entity_t *entity = NULL;
10211         symbol_t *symbol = NULL;
10212
10213         if (token.type == T_IDENTIFIER) {
10214                 symbol = token.symbol;
10215                 next_token();
10216
10217                 entity = get_entity(symbol, NAMESPACE_NORMAL);
10218                 if (entity != NULL
10219                                 && entity->kind != ENTITY_NAMESPACE
10220                                 && entity->base.parent_scope == current_scope) {
10221                         if (is_entity_valid(entity)) {
10222                                 error_redefined_as_different_kind(&token.source_position,
10223                                                 entity, ENTITY_NAMESPACE);
10224                         }
10225                         entity = NULL;
10226                 }
10227         }
10228
10229         if (entity == NULL) {
10230                 entity                       = allocate_entity_zero(ENTITY_NAMESPACE);
10231                 entity->base.symbol          = symbol;
10232                 entity->base.source_position = token.source_position;
10233                 entity->base.namespc         = NAMESPACE_NORMAL;
10234                 entity->base.parent_scope    = current_scope;
10235         }
10236
10237         if (token.type == '=') {
10238                 /* TODO: parse namespace alias */
10239                 panic("namespace alias definition not supported yet");
10240         }
10241
10242         environment_push(entity);
10243         append_entity(current_scope, entity);
10244
10245         size_t const  top       = environment_top();
10246         scope_t      *old_scope = scope_push(&entity->namespacee.members);
10247
10248         entity_t     *old_current_entity = current_entity;
10249         current_entity = entity;
10250
10251         expect('{', end_error);
10252         parse_externals();
10253         expect('}', end_error);
10254
10255 end_error:
10256         assert(current_scope == &entity->namespacee.members);
10257         assert(current_entity == entity);
10258         current_entity = old_current_entity;
10259         scope_pop(old_scope);
10260         environment_pop_to(top);
10261 }
10262
10263 /**
10264  * Parse a statement.
10265  * There's also parse_statement() which additionally checks for
10266  * "statement has no effect" warnings
10267  */
10268 static statement_t *intern_parse_statement(void)
10269 {
10270         statement_t *statement = NULL;
10271
10272         /* declaration or statement */
10273         add_anchor_token(';');
10274         switch (token.type) {
10275         case T_IDENTIFIER: {
10276                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10277                 if (la1_type == ':') {
10278                         statement = parse_label_statement();
10279                 } else if (is_typedef_symbol(token.symbol)) {
10280                         statement = parse_declaration_statement();
10281                 } else {
10282                         /* it's an identifier, the grammar says this must be an
10283                          * expression statement. However it is common that users mistype
10284                          * declaration types, so we guess a bit here to improve robustness
10285                          * for incorrect programs */
10286                         switch (la1_type) {
10287                         case '&':
10288                         case '*':
10289                                 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10290                         default:
10291                                         statement = parse_expression_statement();
10292                                 } else {
10293                         DECLARATION_START
10294                         case T_IDENTIFIER:
10295                                         statement = parse_declaration_statement();
10296                                 }
10297                                 break;
10298                         }
10299                 }
10300                 break;
10301         }
10302
10303         case T___extension__:
10304                 /* This can be a prefix to a declaration or an expression statement.
10305                  * We simply eat it now and parse the rest with tail recursion. */
10306                 while (next_if(T___extension__)) {}
10307                 bool old_gcc_extension = in_gcc_extension;
10308                 in_gcc_extension       = true;
10309                 statement = intern_parse_statement();
10310                 in_gcc_extension = old_gcc_extension;
10311                 break;
10312
10313         DECLARATION_START
10314                 statement = parse_declaration_statement();
10315                 break;
10316
10317         case T___label__:
10318                 statement = parse_local_label_declaration();
10319                 break;
10320
10321         case ';':         statement = parse_empty_statement();         break;
10322         case '{':         statement = parse_compound_statement(false); break;
10323         case T___leave:   statement = parse_leave_statement();         break;
10324         case T___try:     statement = parse_ms_try_statment();         break;
10325         case T_asm:       statement = parse_asm_statement();           break;
10326         case T_break:     statement = parse_break();                   break;
10327         case T_case:      statement = parse_case_statement();          break;
10328         case T_continue:  statement = parse_continue();                break;
10329         case T_default:   statement = parse_default_statement();       break;
10330         case T_do:        statement = parse_do();                      break;
10331         case T_for:       statement = parse_for();                     break;
10332         case T_goto:      statement = parse_goto();                    break;
10333         case T_if:        statement = parse_if();                      break;
10334         case T_return:    statement = parse_return();                  break;
10335         case T_switch:    statement = parse_switch();                  break;
10336         case T_while:     statement = parse_while();                   break;
10337
10338         EXPRESSION_START
10339                 statement = parse_expression_statement();
10340                 break;
10341
10342         default:
10343                 errorf(HERE, "unexpected token %K while parsing statement", &token);
10344                 statement = create_invalid_statement();
10345                 if (!at_anchor())
10346                         next_token();
10347                 break;
10348         }
10349         rem_anchor_token(';');
10350
10351         assert(statement != NULL
10352                         && statement->base.source_position.input_name != NULL);
10353
10354         return statement;
10355 }
10356
10357 /**
10358  * parse a statement and emits "statement has no effect" warning if needed
10359  * (This is really a wrapper around intern_parse_statement with check for 1
10360  *  single warning. It is needed, because for statement expressions we have
10361  *  to avoid the warning on the last statement)
10362  */
10363 static statement_t *parse_statement(void)
10364 {
10365         statement_t *statement = intern_parse_statement();
10366
10367         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10368                 expression_t *expression = statement->expression.expression;
10369                 if (!expression_has_effect(expression)) {
10370                         warningf(&expression->base.source_position,
10371                                         "statement has no effect");
10372                 }
10373         }
10374
10375         return statement;
10376 }
10377
10378 /**
10379  * Parse a compound statement.
10380  */
10381 static statement_t *parse_compound_statement(bool inside_expression_statement)
10382 {
10383         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10384
10385         PUSH_PARENT(statement);
10386
10387         eat('{');
10388         add_anchor_token('}');
10389         /* tokens, which can start a statement */
10390         /* TODO MS, __builtin_FOO */
10391         add_anchor_token('!');
10392         add_anchor_token('&');
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(T_CHARACTER_CONSTANT);
10400         add_anchor_token(T_COLONCOLON);
10401         add_anchor_token(T_FLOATINGPOINT);
10402         add_anchor_token(T_IDENTIFIER);
10403         add_anchor_token(T_INTEGER);
10404         add_anchor_token(T_MINUSMINUS);
10405         add_anchor_token(T_PLUSPLUS);
10406         add_anchor_token(T_STRING_LITERAL);
10407         add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10408         add_anchor_token(T_WIDE_STRING_LITERAL);
10409         add_anchor_token(T__Bool);
10410         add_anchor_token(T__Complex);
10411         add_anchor_token(T__Imaginary);
10412         add_anchor_token(T___FUNCTION__);
10413         add_anchor_token(T___PRETTY_FUNCTION__);
10414         add_anchor_token(T___alignof__);
10415         add_anchor_token(T___attribute__);
10416         add_anchor_token(T___builtin_va_start);
10417         add_anchor_token(T___extension__);
10418         add_anchor_token(T___func__);
10419         add_anchor_token(T___imag__);
10420         add_anchor_token(T___label__);
10421         add_anchor_token(T___real__);
10422         add_anchor_token(T___thread);
10423         add_anchor_token(T_asm);
10424         add_anchor_token(T_auto);
10425         add_anchor_token(T_bool);
10426         add_anchor_token(T_break);
10427         add_anchor_token(T_case);
10428         add_anchor_token(T_char);
10429         add_anchor_token(T_class);
10430         add_anchor_token(T_const);
10431         add_anchor_token(T_const_cast);
10432         add_anchor_token(T_continue);
10433         add_anchor_token(T_default);
10434         add_anchor_token(T_delete);
10435         add_anchor_token(T_double);
10436         add_anchor_token(T_do);
10437         add_anchor_token(T_dynamic_cast);
10438         add_anchor_token(T_enum);
10439         add_anchor_token(T_extern);
10440         add_anchor_token(T_false);
10441         add_anchor_token(T_float);
10442         add_anchor_token(T_for);
10443         add_anchor_token(T_goto);
10444         add_anchor_token(T_if);
10445         add_anchor_token(T_inline);
10446         add_anchor_token(T_int);
10447         add_anchor_token(T_long);
10448         add_anchor_token(T_new);
10449         add_anchor_token(T_operator);
10450         add_anchor_token(T_register);
10451         add_anchor_token(T_reinterpret_cast);
10452         add_anchor_token(T_restrict);
10453         add_anchor_token(T_return);
10454         add_anchor_token(T_short);
10455         add_anchor_token(T_signed);
10456         add_anchor_token(T_sizeof);
10457         add_anchor_token(T_static);
10458         add_anchor_token(T_static_cast);
10459         add_anchor_token(T_struct);
10460         add_anchor_token(T_switch);
10461         add_anchor_token(T_template);
10462         add_anchor_token(T_this);
10463         add_anchor_token(T_throw);
10464         add_anchor_token(T_true);
10465         add_anchor_token(T_try);
10466         add_anchor_token(T_typedef);
10467         add_anchor_token(T_typeid);
10468         add_anchor_token(T_typename);
10469         add_anchor_token(T_typeof);
10470         add_anchor_token(T_union);
10471         add_anchor_token(T_unsigned);
10472         add_anchor_token(T_using);
10473         add_anchor_token(T_void);
10474         add_anchor_token(T_volatile);
10475         add_anchor_token(T_wchar_t);
10476         add_anchor_token(T_while);
10477
10478         size_t const  top       = environment_top();
10479         scope_t      *old_scope = scope_push(&statement->compound.scope);
10480
10481         statement_t **anchor            = &statement->compound.statements;
10482         bool          only_decls_so_far = true;
10483         while (token.type != '}') {
10484                 if (token.type == T_EOF) {
10485                         errorf(&statement->base.source_position,
10486                                "EOF while parsing compound statement");
10487                         break;
10488                 }
10489                 statement_t *sub_statement = intern_parse_statement();
10490                 if (is_invalid_statement(sub_statement)) {
10491                         /* an error occurred. if we are at an anchor, return */
10492                         if (at_anchor())
10493                                 goto end_error;
10494                         continue;
10495                 }
10496
10497                 if (warning.declaration_after_statement) {
10498                         if (sub_statement->kind != STATEMENT_DECLARATION) {
10499                                 only_decls_so_far = false;
10500                         } else if (!only_decls_so_far) {
10501                                 warningf(&sub_statement->base.source_position,
10502                                          "ISO C90 forbids mixed declarations and code");
10503                         }
10504                 }
10505
10506                 *anchor = sub_statement;
10507
10508                 while (sub_statement->base.next != NULL)
10509                         sub_statement = sub_statement->base.next;
10510
10511                 anchor = &sub_statement->base.next;
10512         }
10513         next_token();
10514
10515         /* look over all statements again to produce no effect warnings */
10516         if (warning.unused_value) {
10517                 statement_t *sub_statement = statement->compound.statements;
10518                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10519                         if (sub_statement->kind != STATEMENT_EXPRESSION)
10520                                 continue;
10521                         /* don't emit a warning for the last expression in an expression
10522                          * statement as it has always an effect */
10523                         if (inside_expression_statement && sub_statement->base.next == NULL)
10524                                 continue;
10525
10526                         expression_t *expression = sub_statement->expression.expression;
10527                         if (!expression_has_effect(expression)) {
10528                                 warningf(&expression->base.source_position,
10529                                          "statement has no effect");
10530                         }
10531                 }
10532         }
10533
10534 end_error:
10535         rem_anchor_token(T_while);
10536         rem_anchor_token(T_wchar_t);
10537         rem_anchor_token(T_volatile);
10538         rem_anchor_token(T_void);
10539         rem_anchor_token(T_using);
10540         rem_anchor_token(T_unsigned);
10541         rem_anchor_token(T_union);
10542         rem_anchor_token(T_typeof);
10543         rem_anchor_token(T_typename);
10544         rem_anchor_token(T_typeid);
10545         rem_anchor_token(T_typedef);
10546         rem_anchor_token(T_try);
10547         rem_anchor_token(T_true);
10548         rem_anchor_token(T_throw);
10549         rem_anchor_token(T_this);
10550         rem_anchor_token(T_template);
10551         rem_anchor_token(T_switch);
10552         rem_anchor_token(T_struct);
10553         rem_anchor_token(T_static_cast);
10554         rem_anchor_token(T_static);
10555         rem_anchor_token(T_sizeof);
10556         rem_anchor_token(T_signed);
10557         rem_anchor_token(T_short);
10558         rem_anchor_token(T_return);
10559         rem_anchor_token(T_restrict);
10560         rem_anchor_token(T_reinterpret_cast);
10561         rem_anchor_token(T_register);
10562         rem_anchor_token(T_operator);
10563         rem_anchor_token(T_new);
10564         rem_anchor_token(T_long);
10565         rem_anchor_token(T_int);
10566         rem_anchor_token(T_inline);
10567         rem_anchor_token(T_if);
10568         rem_anchor_token(T_goto);
10569         rem_anchor_token(T_for);
10570         rem_anchor_token(T_float);
10571         rem_anchor_token(T_false);
10572         rem_anchor_token(T_extern);
10573         rem_anchor_token(T_enum);
10574         rem_anchor_token(T_dynamic_cast);
10575         rem_anchor_token(T_do);
10576         rem_anchor_token(T_double);
10577         rem_anchor_token(T_delete);
10578         rem_anchor_token(T_default);
10579         rem_anchor_token(T_continue);
10580         rem_anchor_token(T_const_cast);
10581         rem_anchor_token(T_const);
10582         rem_anchor_token(T_class);
10583         rem_anchor_token(T_char);
10584         rem_anchor_token(T_case);
10585         rem_anchor_token(T_break);
10586         rem_anchor_token(T_bool);
10587         rem_anchor_token(T_auto);
10588         rem_anchor_token(T_asm);
10589         rem_anchor_token(T___thread);
10590         rem_anchor_token(T___real__);
10591         rem_anchor_token(T___label__);
10592         rem_anchor_token(T___imag__);
10593         rem_anchor_token(T___func__);
10594         rem_anchor_token(T___extension__);
10595         rem_anchor_token(T___builtin_va_start);
10596         rem_anchor_token(T___attribute__);
10597         rem_anchor_token(T___alignof__);
10598         rem_anchor_token(T___PRETTY_FUNCTION__);
10599         rem_anchor_token(T___FUNCTION__);
10600         rem_anchor_token(T__Imaginary);
10601         rem_anchor_token(T__Complex);
10602         rem_anchor_token(T__Bool);
10603         rem_anchor_token(T_WIDE_STRING_LITERAL);
10604         rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10605         rem_anchor_token(T_STRING_LITERAL);
10606         rem_anchor_token(T_PLUSPLUS);
10607         rem_anchor_token(T_MINUSMINUS);
10608         rem_anchor_token(T_INTEGER);
10609         rem_anchor_token(T_IDENTIFIER);
10610         rem_anchor_token(T_FLOATINGPOINT);
10611         rem_anchor_token(T_COLONCOLON);
10612         rem_anchor_token(T_CHARACTER_CONSTANT);
10613         rem_anchor_token('~');
10614         rem_anchor_token('{');
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         assert(current_scope == &statement->compound.scope);
10623         scope_pop(old_scope);
10624         environment_pop_to(top);
10625
10626         POP_PARENT;
10627         return statement;
10628 }
10629
10630 /**
10631  * Check for unused global static functions and variables
10632  */
10633 static void check_unused_globals(void)
10634 {
10635         if (!warning.unused_function && !warning.unused_variable)
10636                 return;
10637
10638         for (const entity_t *entity = file_scope->entities; entity != NULL;
10639              entity = entity->base.next) {
10640                 if (!is_declaration(entity))
10641                         continue;
10642
10643                 const declaration_t *declaration = &entity->declaration;
10644                 if (declaration->used                  ||
10645                     declaration->modifiers & DM_UNUSED ||
10646                     declaration->modifiers & DM_USED   ||
10647                     declaration->storage_class != STORAGE_CLASS_STATIC)
10648                         continue;
10649
10650                 type_t *const type = declaration->type;
10651                 const char *s;
10652                 if (entity->kind == ENTITY_FUNCTION) {
10653                         /* inhibit warning for static inline functions */
10654                         if (entity->function.is_inline)
10655                                 continue;
10656
10657                         s = entity->function.statement != NULL ? "defined" : "declared";
10658                 } else {
10659                         s = "defined";
10660                 }
10661
10662                 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10663                         type, declaration->base.symbol, s);
10664         }
10665 }
10666
10667 static void parse_global_asm(void)
10668 {
10669         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10670
10671         eat(T_asm);
10672         expect('(', end_error);
10673
10674         statement->asms.asm_text = parse_string_literals();
10675         statement->base.next     = unit->global_asm;
10676         unit->global_asm         = statement;
10677
10678         expect(')', end_error);
10679         expect(';', end_error);
10680
10681 end_error:;
10682 }
10683
10684 static void parse_linkage_specification(void)
10685 {
10686         eat(T_extern);
10687
10688         const char *linkage = parse_string_literals().begin;
10689
10690         linkage_kind_t old_linkage = current_linkage;
10691         linkage_kind_t new_linkage;
10692         if (strcmp(linkage, "C") == 0) {
10693                 new_linkage = LINKAGE_C;
10694         } else if (strcmp(linkage, "C++") == 0) {
10695                 new_linkage = LINKAGE_CXX;
10696         } else {
10697                 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10698                 new_linkage = LINKAGE_INVALID;
10699         }
10700         current_linkage = new_linkage;
10701
10702         if (next_if('{')) {
10703                 parse_externals();
10704                 expect('}', end_error);
10705         } else {
10706                 parse_external();
10707         }
10708
10709 end_error:
10710         assert(current_linkage == new_linkage);
10711         current_linkage = old_linkage;
10712 }
10713
10714 static void parse_external(void)
10715 {
10716         switch (token.type) {
10717                 DECLARATION_START_NO_EXTERN
10718                 case T_IDENTIFIER:
10719                 case T___extension__:
10720                 /* tokens below are for implicit int */
10721                 case '&': /* & x; -> int& x; (and error later, because C++ has no
10722                              implicit int) */
10723                 case '*': /* * x; -> int* x; */
10724                 case '(': /* (x); -> int (x); */
10725                         parse_external_declaration();
10726                         return;
10727
10728                 case T_extern:
10729                         if (look_ahead(1)->type == T_STRING_LITERAL) {
10730                                 parse_linkage_specification();
10731                         } else {
10732                                 parse_external_declaration();
10733                         }
10734                         return;
10735
10736                 case T_asm:
10737                         parse_global_asm();
10738                         return;
10739
10740                 case T_namespace:
10741                         parse_namespace_definition();
10742                         return;
10743
10744                 case ';':
10745                         if (!strict_mode) {
10746                                 if (warning.other)
10747                                         warningf(HERE, "stray ';' outside of function");
10748                                 next_token();
10749                                 return;
10750                         }
10751                         /* FALLTHROUGH */
10752
10753                 default:
10754                         errorf(HERE, "stray %K outside of function", &token);
10755                         if (token.type == '(' || token.type == '{' || token.type == '[')
10756                                 eat_until_matching_token(token.type);
10757                         next_token();
10758                         return;
10759         }
10760 }
10761
10762 static void parse_externals(void)
10763 {
10764         add_anchor_token('}');
10765         add_anchor_token(T_EOF);
10766
10767 #ifndef NDEBUG
10768         /* make a copy of the anchor set, so we can check if it is restored after parsing */
10769         unsigned char token_anchor_copy[T_LAST_TOKEN];
10770         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10771 #endif
10772
10773         while (token.type != T_EOF && token.type != '}') {
10774 #ifndef NDEBUG
10775                 bool anchor_leak = false;
10776                 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10777                         unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10778                         if (count != 0) {
10779                                 /* the anchor set and its copy differs */
10780                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10781                                 anchor_leak = true;
10782                         }
10783                 }
10784                 if (in_gcc_extension) {
10785                         /* an gcc extension scope was not closed */
10786                         errorf(HERE, "Leaked __extension__");
10787                         anchor_leak = true;
10788                 }
10789
10790                 if (anchor_leak)
10791                         abort();
10792 #endif
10793
10794                 parse_external();
10795         }
10796
10797         rem_anchor_token(T_EOF);
10798         rem_anchor_token('}');
10799 }
10800
10801 /**
10802  * Parse a translation unit.
10803  */
10804 static void parse_translation_unit(void)
10805 {
10806         add_anchor_token(T_EOF);
10807
10808         while (true) {
10809                 parse_externals();
10810
10811                 if (token.type == T_EOF)
10812                         break;
10813
10814                 errorf(HERE, "stray %K outside of function", &token);
10815                 if (token.type == '(' || token.type == '{' || token.type == '[')
10816                         eat_until_matching_token(token.type);
10817                 next_token();
10818         }
10819 }
10820
10821 /**
10822  * Parse the input.
10823  *
10824  * @return  the translation unit or NULL if errors occurred.
10825  */
10826 void start_parsing(void)
10827 {
10828         environment_stack = NEW_ARR_F(stack_entry_t, 0);
10829         label_stack       = NEW_ARR_F(stack_entry_t, 0);
10830         diagnostic_count  = 0;
10831         error_count       = 0;
10832         warning_count     = 0;
10833
10834         print_to_file(stderr);
10835
10836         assert(unit == NULL);
10837         unit = allocate_ast_zero(sizeof(unit[0]));
10838
10839         assert(file_scope == NULL);
10840         file_scope = &unit->scope;
10841
10842         assert(current_scope == NULL);
10843         scope_push(&unit->scope);
10844
10845         create_gnu_builtins();
10846         if (c_mode & _MS)
10847                 create_microsoft_intrinsics();
10848 }
10849
10850 translation_unit_t *finish_parsing(void)
10851 {
10852         assert(current_scope == &unit->scope);
10853         scope_pop(NULL);
10854
10855         assert(file_scope == &unit->scope);
10856         check_unused_globals();
10857         file_scope = NULL;
10858
10859         DEL_ARR_F(environment_stack);
10860         DEL_ARR_F(label_stack);
10861
10862         translation_unit_t *result = unit;
10863         unit = NULL;
10864         return result;
10865 }
10866
10867 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10868  * are given length one. */
10869 static void complete_incomplete_arrays(void)
10870 {
10871         size_t n = ARR_LEN(incomplete_arrays);
10872         for (size_t i = 0; i != n; ++i) {
10873                 declaration_t *const decl      = incomplete_arrays[i];
10874                 type_t        *const orig_type = decl->type;
10875                 type_t        *const type      = skip_typeref(orig_type);
10876
10877                 if (!is_type_incomplete(type))
10878                         continue;
10879
10880                 if (warning.other) {
10881                         warningf(&decl->base.source_position,
10882                                         "array '%#T' assumed to have one element",
10883                                         orig_type, decl->base.symbol);
10884                 }
10885
10886                 type_t *const new_type = duplicate_type(type);
10887                 new_type->array.size_constant     = true;
10888                 new_type->array.has_implicit_size = true;
10889                 new_type->array.size              = 1;
10890
10891                 type_t *const result = identify_new_type(new_type);
10892
10893                 decl->type = result;
10894         }
10895 }
10896
10897 void prepare_main_collect2(entity_t *entity)
10898 {
10899         // create call to __main
10900         symbol_t *symbol         = symbol_table_insert("__main");
10901         entity_t *subsubmain_ent
10902                 = create_implicit_function(symbol, &builtin_source_position);
10903
10904         expression_t *ref         = allocate_expression_zero(EXPR_REFERENCE);
10905         type_t       *ftype       = subsubmain_ent->declaration.type;
10906         ref->base.source_position = builtin_source_position;
10907         ref->base.type            = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10908         ref->reference.entity     = subsubmain_ent;
10909
10910         expression_t *call = allocate_expression_zero(EXPR_CALL);
10911         call->base.source_position = builtin_source_position;
10912         call->base.type            = type_void;
10913         call->call.function        = ref;
10914
10915         statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10916         expr_statement->base.source_position  = builtin_source_position;
10917         expr_statement->expression.expression = call;
10918
10919         statement_t *statement = entity->function.statement;
10920         assert(statement->kind == STATEMENT_COMPOUND);
10921         compound_statement_t *compounds = &statement->compound;
10922
10923         expr_statement->base.next = compounds->statements;
10924         compounds->statements     = expr_statement;
10925 }
10926
10927 void parse(void)
10928 {
10929         lookahead_bufpos = 0;
10930         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10931                 next_token();
10932         }
10933         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10934         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10935         parse_translation_unit();
10936         complete_incomplete_arrays();
10937         DEL_ARR_F(incomplete_arrays);
10938         incomplete_arrays = NULL;
10939 }
10940
10941 /**
10942  * Initialize the parser.
10943  */
10944 void init_parser(void)
10945 {
10946         sym_anonymous = symbol_table_insert("<anonymous>");
10947
10948         memset(token_anchor_set, 0, sizeof(token_anchor_set));
10949
10950         init_expression_parsers();
10951         obstack_init(&temp_obst);
10952
10953         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10954         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10955 }
10956
10957 /**
10958  * Terminate the parser.
10959  */
10960 void exit_parser(void)
10961 {
10962         obstack_free(&temp_obst, NULL);
10963 }