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