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