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