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