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