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