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