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