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