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