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