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