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