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