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