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