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