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