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