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