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