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