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