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