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