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