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