Implement -Wnested-externs.
[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                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3278                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3279                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3280                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3281                         | SPECIFIER_INT:
3282                         atomic_type = ATOMIC_TYPE_LONGLONG;
3283                         break;
3284                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3285                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3286                         | SPECIFIER_INT:
3287                         atomic_type = ATOMIC_TYPE_ULONGLONG;
3288                         break;
3289
3290                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3291                         atomic_type = unsigned_int8_type_kind;
3292                         break;
3293
3294                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3295                         atomic_type = unsigned_int16_type_kind;
3296                         break;
3297
3298                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3299                         atomic_type = unsigned_int32_type_kind;
3300                         break;
3301
3302                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3303                         atomic_type = unsigned_int64_type_kind;
3304                         break;
3305
3306                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3307                         atomic_type = unsigned_int128_type_kind;
3308                         break;
3309
3310                 case SPECIFIER_INT8:
3311                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3312                         atomic_type = int8_type_kind;
3313                         break;
3314
3315                 case SPECIFIER_INT16:
3316                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3317                         atomic_type = int16_type_kind;
3318                         break;
3319
3320                 case SPECIFIER_INT32:
3321                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3322                         atomic_type = int32_type_kind;
3323                         break;
3324
3325                 case SPECIFIER_INT64:
3326                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3327                         atomic_type = int64_type_kind;
3328                         break;
3329
3330                 case SPECIFIER_INT128:
3331                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3332                         atomic_type = int128_type_kind;
3333                         break;
3334
3335                 case SPECIFIER_FLOAT:
3336                         atomic_type = ATOMIC_TYPE_FLOAT;
3337                         break;
3338                 case SPECIFIER_DOUBLE:
3339                         atomic_type = ATOMIC_TYPE_DOUBLE;
3340                         break;
3341                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3342                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3343                         break;
3344                 case SPECIFIER_BOOL:
3345                         atomic_type = ATOMIC_TYPE_BOOL;
3346                         break;
3347                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3348                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3349                         atomic_type = ATOMIC_TYPE_FLOAT;
3350                         break;
3351                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3352                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3353                         atomic_type = ATOMIC_TYPE_DOUBLE;
3354                         break;
3355                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3356                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3357                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3358                         break;
3359                 default:
3360                         /* invalid specifier combination, give an error message */
3361                         if (type_specifiers == 0) {
3362                                 if (! strict_mode) {
3363                                         if (warning.implicit_int) {
3364                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
3365                                         }
3366                                         atomic_type = ATOMIC_TYPE_INT;
3367                                         break;
3368                                 } else {
3369                                         errorf(HERE, "no type specifiers given in declaration");
3370                                 }
3371                         } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3372                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
3373                                 errorf(HERE, "signed and unsigned specifiers gives");
3374                         } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3375                                 errorf(HERE, "only integer types can be signed or unsigned");
3376                         } else {
3377                                 errorf(HERE, "multiple datatypes in declaration");
3378                         }
3379                         atomic_type = ATOMIC_TYPE_INVALID;
3380                 }
3381
3382                 if (type_specifiers & SPECIFIER_COMPLEX &&
3383                    atomic_type != ATOMIC_TYPE_INVALID) {
3384                         type                = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3385                         type->complex.akind = atomic_type;
3386                 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3387                           atomic_type != ATOMIC_TYPE_INVALID) {
3388                         type                  = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3389                         type->imaginary.akind = atomic_type;
3390                 } else {
3391                         type               = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3392                         type->atomic.akind = atomic_type;
3393                 }
3394                 newtype = 1;
3395         } else {
3396                 if (type_specifiers != 0) {
3397                         errorf(HERE, "multiple datatypes in declaration");
3398                 }
3399         }
3400
3401         /* FIXME: check type qualifiers here */
3402
3403         type->base.qualifiers = qualifiers;
3404         type->base.modifiers  = modifiers;
3405
3406         type_t *result = typehash_insert(type);
3407         if (newtype && result != type) {
3408                 free_type(type);
3409         }
3410
3411         specifiers->type = result;
3412 end_error:
3413         return;
3414 }
3415
3416 static type_qualifiers_t parse_type_qualifiers(void)
3417 {
3418         type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3419
3420         while (true) {
3421                 switch(token.type) {
3422                 /* type qualifiers */
3423                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3424                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3425                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3426                 /* microsoft extended type modifiers */
3427                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3428                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3429                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3430                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3431                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3432
3433                 default:
3434                         return qualifiers;
3435                 }
3436         }
3437 }
3438
3439 static declaration_t *parse_identifier_list(void)
3440 {
3441         declaration_t *declarations     = NULL;
3442         declaration_t *last_declaration = NULL;
3443         do {
3444                 declaration_t *const declaration = allocate_declaration_zero();
3445                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
3446                 declaration->source_position = token.source_position;
3447                 declaration->symbol          = token.v.symbol;
3448                 next_token();
3449
3450                 if (last_declaration != NULL) {
3451                         last_declaration->next = declaration;
3452                 } else {
3453                         declarations = declaration;
3454                 }
3455                 last_declaration = declaration;
3456
3457                 if (token.type != ',') {
3458                         break;
3459                 }
3460                 next_token();
3461         } while (token.type == T_IDENTIFIER);
3462
3463         return declarations;
3464 }
3465
3466 static type_t *automatic_type_conversion(type_t *orig_type);
3467
3468 static void semantic_parameter(declaration_t *declaration)
3469 {
3470         /* TODO: improve error messages */
3471
3472         if (declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3473                 errorf(HERE, "typedef not allowed in parameter list");
3474         } else if (declaration->declared_storage_class != STORAGE_CLASS_NONE
3475                         && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3476                 errorf(HERE, "parameter may only have none or register storage class");
3477         }
3478
3479         type_t *const orig_type = declaration->type;
3480         /* Â§6.7.5.3(7): Array as last part of a parameter type is just syntactic
3481          * sugar.  Turn it into a pointer.
3482          * Â§6.7.5.3(8): A declaration of a parameter as ``function returning type''
3483          * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3484          */
3485         type_t *const type = automatic_type_conversion(orig_type);
3486         declaration->type = type;
3487
3488         if (is_type_incomplete(skip_typeref(type))) {
3489                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3490                        orig_type, declaration->symbol);
3491         }
3492 }
3493
3494 static declaration_t *parse_parameter(void)
3495 {
3496         declaration_specifiers_t specifiers;
3497         memset(&specifiers, 0, sizeof(specifiers));
3498
3499         parse_declaration_specifiers(&specifiers);
3500
3501         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3502
3503         return declaration;
3504 }
3505
3506 static declaration_t *parse_parameters(function_type_t *type)
3507 {
3508         declaration_t *declarations = NULL;
3509
3510         eat('(');
3511         add_anchor_token(')');
3512         int saved_comma_state = save_and_reset_anchor_state(',');
3513
3514         if (token.type == T_IDENTIFIER) {
3515                 symbol_t *symbol = token.v.symbol;
3516                 if (!is_typedef_symbol(symbol)) {
3517                         type->kr_style_parameters = true;
3518                         declarations = parse_identifier_list();
3519                         goto parameters_finished;
3520                 }
3521         }
3522
3523         if (token.type == ')') {
3524                 type->unspecified_parameters = 1;
3525                 goto parameters_finished;
3526         }
3527
3528         declaration_t        *declaration;
3529         declaration_t        *last_declaration = NULL;
3530         function_parameter_t *parameter;
3531         function_parameter_t *last_parameter = NULL;
3532
3533         while (true) {
3534                 switch(token.type) {
3535                 case T_DOTDOTDOT:
3536                         next_token();
3537                         type->variadic = 1;
3538                         goto parameters_finished;
3539
3540                 case T_IDENTIFIER:
3541                 case T___extension__:
3542                 DECLARATION_START
3543                         declaration = parse_parameter();
3544
3545                         /* func(void) is not a parameter */
3546                         if (last_parameter == NULL
3547                                         && token.type == ')'
3548                                         && declaration->symbol == NULL
3549                                         && skip_typeref(declaration->type) == type_void) {
3550                                 goto parameters_finished;
3551                         }
3552                         semantic_parameter(declaration);
3553
3554                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
3555                         memset(parameter, 0, sizeof(parameter[0]));
3556                         parameter->type = declaration->type;
3557
3558                         if (last_parameter != NULL) {
3559                                 last_declaration->next = declaration;
3560                                 last_parameter->next   = parameter;
3561                         } else {
3562                                 type->parameters = parameter;
3563                                 declarations     = declaration;
3564                         }
3565                         last_parameter   = parameter;
3566                         last_declaration = declaration;
3567                         break;
3568
3569                 default:
3570                         goto parameters_finished;
3571                 }
3572                 if (token.type != ',') {
3573                         goto parameters_finished;
3574                 }
3575                 next_token();
3576         }
3577
3578
3579 parameters_finished:
3580         rem_anchor_token(')');
3581         expect(')');
3582
3583         restore_anchor_state(',', saved_comma_state);
3584         return declarations;
3585
3586 end_error:
3587         restore_anchor_state(',', saved_comma_state);
3588         return NULL;
3589 }
3590
3591 typedef enum construct_type_kind_t {
3592         CONSTRUCT_INVALID,
3593         CONSTRUCT_POINTER,
3594         CONSTRUCT_FUNCTION,
3595         CONSTRUCT_ARRAY
3596 } construct_type_kind_t;
3597
3598 typedef struct construct_type_t construct_type_t;
3599 struct construct_type_t {
3600         construct_type_kind_t  kind;
3601         construct_type_t      *next;
3602 };
3603
3604 typedef struct parsed_pointer_t parsed_pointer_t;
3605 struct parsed_pointer_t {
3606         construct_type_t  construct_type;
3607         type_qualifiers_t type_qualifiers;
3608 };
3609
3610 typedef struct construct_function_type_t construct_function_type_t;
3611 struct construct_function_type_t {
3612         construct_type_t  construct_type;
3613         type_t           *function_type;
3614 };
3615
3616 typedef struct parsed_array_t parsed_array_t;
3617 struct parsed_array_t {
3618         construct_type_t  construct_type;
3619         type_qualifiers_t type_qualifiers;
3620         bool              is_static;
3621         bool              is_variable;
3622         expression_t     *size;
3623 };
3624
3625 typedef struct construct_base_type_t construct_base_type_t;
3626 struct construct_base_type_t {
3627         construct_type_t  construct_type;
3628         type_t           *type;
3629 };
3630
3631 static construct_type_t *parse_pointer_declarator(void)
3632 {
3633         eat('*');
3634
3635         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3636         memset(pointer, 0, sizeof(pointer[0]));
3637         pointer->construct_type.kind = CONSTRUCT_POINTER;
3638         pointer->type_qualifiers     = parse_type_qualifiers();
3639
3640         return (construct_type_t*) pointer;
3641 }
3642
3643 static construct_type_t *parse_array_declarator(void)
3644 {
3645         eat('[');
3646         add_anchor_token(']');
3647
3648         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3649         memset(array, 0, sizeof(array[0]));
3650         array->construct_type.kind = CONSTRUCT_ARRAY;
3651
3652         if (token.type == T_static) {
3653                 array->is_static = true;
3654                 next_token();
3655         }
3656
3657         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3658         if (type_qualifiers != 0) {
3659                 if (token.type == T_static) {
3660                         array->is_static = true;
3661                         next_token();
3662                 }
3663         }
3664         array->type_qualifiers = type_qualifiers;
3665
3666         if (token.type == '*' && look_ahead(1)->type == ']') {
3667                 array->is_variable = true;
3668                 next_token();
3669         } else if (token.type != ']') {
3670                 array->size = parse_assignment_expression();
3671         }
3672
3673         rem_anchor_token(']');
3674         expect(']');
3675
3676         return (construct_type_t*) array;
3677 end_error:
3678         return NULL;
3679 }
3680
3681 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3682 {
3683         type_t *type;
3684         if (declaration != NULL) {
3685                 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3686
3687                 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3688
3689                 if (mask & (mask-1)) {
3690                         const char *first = NULL, *second = NULL;
3691
3692                         /* more than one calling convention set */
3693                         if (declaration->modifiers & DM_CDECL) {
3694                                 if (first == NULL)       first = "cdecl";
3695                                 else if (second == NULL) second = "cdecl";
3696                         }
3697                         if (declaration->modifiers & DM_STDCALL) {
3698                                 if (first == NULL)       first = "stdcall";
3699                                 else if (second == NULL) second = "stdcall";
3700                         }
3701                         if (declaration->modifiers & DM_FASTCALL) {
3702                                 if (first == NULL)       first = "faslcall";
3703                                 else if (second == NULL) second = "fastcall";
3704                         }
3705                         if (declaration->modifiers & DM_THISCALL) {
3706                                 if (first == NULL)       first = "thiscall";
3707                                 else if (second == NULL) second = "thiscall";
3708                         }
3709                         errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3710                 }
3711
3712                 if (declaration->modifiers & DM_CDECL)
3713                         type->function.calling_convention = CC_CDECL;
3714                 else if (declaration->modifiers & DM_STDCALL)
3715                         type->function.calling_convention = CC_STDCALL;
3716                 else if (declaration->modifiers & DM_FASTCALL)
3717                         type->function.calling_convention = CC_FASTCALL;
3718                 else if (declaration->modifiers & DM_THISCALL)
3719                         type->function.calling_convention = CC_THISCALL;
3720         } else {
3721                 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3722         }
3723
3724         declaration_t *parameters = parse_parameters(&type->function);
3725         if (declaration != NULL) {
3726                 declaration->scope.declarations = parameters;
3727         }
3728
3729         construct_function_type_t *construct_function_type =
3730                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3731         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3732         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3733         construct_function_type->function_type       = type;
3734
3735         return &construct_function_type->construct_type;
3736 }
3737
3738 static void fix_declaration_type(declaration_t *declaration)
3739 {
3740         decl_modifiers_t declaration_modifiers = declaration->modifiers;
3741         type_modifiers_t type_modifiers        = declaration->type->base.modifiers;
3742
3743         if (declaration_modifiers & DM_TRANSPARENT_UNION)
3744                 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3745
3746         if (declaration->type->base.modifiers == type_modifiers)
3747                 return;
3748
3749         type_t *copy = duplicate_type(declaration->type);
3750         copy->base.modifiers = type_modifiers;
3751
3752         type_t *result = typehash_insert(copy);
3753         if (result != copy) {
3754                 obstack_free(type_obst, copy);
3755         }
3756
3757         declaration->type = result;
3758 }
3759
3760 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3761                 bool may_be_abstract)
3762 {
3763         /* construct a single linked list of construct_type_t's which describe
3764          * how to construct the final declarator type */
3765         construct_type_t *first = NULL;
3766         construct_type_t *last  = NULL;
3767         gnu_attribute_t  *attributes = NULL;
3768
3769         declaration->modifiers |= parse_attributes(&attributes);
3770
3771         /* pointers */
3772         while (token.type == '*') {
3773                 construct_type_t *type = parse_pointer_declarator();
3774
3775                 if (last == NULL) {
3776                         first = type;
3777                         last  = type;
3778                 } else {
3779                         last->next = type;
3780                         last       = type;
3781                 }
3782
3783                 /* TODO: find out if this is correct */
3784                 declaration->modifiers |= parse_attributes(&attributes);
3785         }
3786
3787         construct_type_t *inner_types = NULL;
3788
3789         switch(token.type) {
3790         case T_IDENTIFIER:
3791                 if (declaration == NULL) {
3792                         errorf(HERE, "no identifier expected in typename");
3793                 } else {
3794                         declaration->symbol          = token.v.symbol;
3795                         declaration->source_position = token.source_position;
3796                 }
3797                 next_token();
3798                 break;
3799         case '(':
3800                 next_token();
3801                 add_anchor_token(')');
3802                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3803                 rem_anchor_token(')');
3804                 expect(')');
3805                 break;
3806         default:
3807                 if (may_be_abstract)
3808                         break;
3809                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3810                 /* avoid a loop in the outermost scope, because eat_statement doesn't
3811                  * eat '}' */
3812                 if (token.type == '}' && current_function == NULL) {
3813                         next_token();
3814                 } else {
3815                         eat_statement();
3816                 }
3817                 return NULL;
3818         }
3819
3820         construct_type_t *p = last;
3821
3822         while(true) {
3823                 construct_type_t *type;
3824                 switch(token.type) {
3825                 case '(':
3826                         type = parse_function_declarator(declaration);
3827                         break;
3828                 case '[':
3829                         type = parse_array_declarator();
3830                         break;
3831                 default:
3832                         goto declarator_finished;
3833                 }
3834
3835                 /* insert in the middle of the list (behind p) */
3836                 if (p != NULL) {
3837                         type->next = p->next;
3838                         p->next    = type;
3839                 } else {
3840                         type->next = first;
3841                         first      = type;
3842                 }
3843                 if (last == p) {
3844                         last = type;
3845                 }
3846         }
3847
3848 declarator_finished:
3849         /* append inner_types at the end of the list, we don't to set last anymore
3850          * as it's not needed anymore */
3851         if (last == NULL) {
3852                 assert(first == NULL);
3853                 first = inner_types;
3854         } else {
3855                 last->next = inner_types;
3856         }
3857
3858         return first;
3859 end_error:
3860         return NULL;
3861 }
3862
3863 static void parse_declaration_attributes(declaration_t *declaration)
3864 {
3865         gnu_attribute_t  *attributes = NULL;
3866         decl_modifiers_t  modifiers  = parse_attributes(&attributes);
3867
3868         if (declaration == NULL)
3869                 return;
3870
3871         declaration->modifiers |= modifiers;
3872         /* check if we have these stupid mode attributes... */
3873         type_t *old_type = declaration->type;
3874         if (old_type == NULL)
3875                 return;
3876
3877         gnu_attribute_t *attribute = attributes;
3878         for ( ; attribute != NULL; attribute = attribute->next) {
3879                 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3880                         continue;
3881
3882                 atomic_type_kind_t  akind = attribute->u.akind;
3883                 if (!is_type_signed(old_type)) {
3884                         switch(akind) {
3885                         case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3886                         case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3887                         case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3888                         case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3889                         default:
3890                                 panic("invalid akind in mode attribute");
3891                         }
3892                 }
3893                 declaration->type
3894                         = make_atomic_type(akind, old_type->base.qualifiers);
3895         }
3896 }
3897
3898 static type_t *construct_declarator_type(construct_type_t *construct_list,
3899                                          type_t *type)
3900 {
3901         construct_type_t *iter = construct_list;
3902         for( ; iter != NULL; iter = iter->next) {
3903                 switch(iter->kind) {
3904                 case CONSTRUCT_INVALID:
3905                         internal_errorf(HERE, "invalid type construction found");
3906                 case CONSTRUCT_FUNCTION: {
3907                         construct_function_type_t *construct_function_type
3908                                 = (construct_function_type_t*) iter;
3909
3910                         type_t *function_type = construct_function_type->function_type;
3911
3912                         function_type->function.return_type = type;
3913
3914                         type_t *skipped_return_type = skip_typeref(type);
3915                         if (is_type_function(skipped_return_type)) {
3916                                 errorf(HERE, "function returning function is not allowed");
3917                                 type = type_error_type;
3918                         } else if (is_type_array(skipped_return_type)) {
3919                                 errorf(HERE, "function returning array is not allowed");
3920                                 type = type_error_type;
3921                         } else {
3922                                 type = function_type;
3923                         }
3924                         break;
3925                 }
3926
3927                 case CONSTRUCT_POINTER: {
3928                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3929                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, &null_position);
3930                         pointer_type->pointer.points_to  = type;
3931                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
3932
3933                         type = pointer_type;
3934                         break;
3935                 }
3936
3937                 case CONSTRUCT_ARRAY: {
3938                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
3939                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, &null_position);
3940
3941                         expression_t *size_expression = parsed_array->size;
3942                         if (size_expression != NULL) {
3943                                 size_expression
3944                                         = create_implicit_cast(size_expression, type_size_t);
3945                         }
3946
3947                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
3948                         array_type->array.element_type    = type;
3949                         array_type->array.is_static       = parsed_array->is_static;
3950                         array_type->array.is_variable     = parsed_array->is_variable;
3951                         array_type->array.size_expression = size_expression;
3952
3953                         if (size_expression != NULL) {
3954                                 if (is_constant_expression(size_expression)) {
3955                                         array_type->array.size_constant = true;
3956                                         array_type->array.size
3957                                                 = fold_constant(size_expression);
3958                                 } else {
3959                                         array_type->array.is_vla = true;
3960                                 }
3961                         }
3962
3963                         type_t *skipped_type = skip_typeref(type);
3964                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3965                                 errorf(HERE, "array of void is not allowed");
3966                                 type = type_error_type;
3967                         } else {
3968                                 type = array_type;
3969                         }
3970                         break;
3971                 }
3972                 }
3973
3974                 type_t *hashed_type = typehash_insert(type);
3975                 if (hashed_type != type) {
3976                         /* the function type was constructed earlier freeing it here will
3977                          * destroy other types... */
3978                         if (iter->kind != CONSTRUCT_FUNCTION) {
3979                                 free_type(type);
3980                         }
3981                         type = hashed_type;
3982                 }
3983         }
3984
3985         return type;
3986 }
3987
3988 static declaration_t *parse_declarator(
3989                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3990 {
3991         declaration_t *const declaration    = allocate_declaration_zero();
3992         declaration->declared_storage_class = specifiers->declared_storage_class;
3993         declaration->modifiers              = specifiers->modifiers;
3994         declaration->deprecated_string      = specifiers->deprecated_string;
3995         declaration->get_property_sym       = specifiers->get_property_sym;
3996         declaration->put_property_sym       = specifiers->put_property_sym;
3997         declaration->is_inline              = specifiers->is_inline;
3998
3999         declaration->storage_class          = specifiers->declared_storage_class;
4000         if (declaration->storage_class == STORAGE_CLASS_NONE
4001                         && scope != global_scope) {
4002                 declaration->storage_class = STORAGE_CLASS_AUTO;
4003         }
4004
4005         if (specifiers->alignment != 0) {
4006                 /* TODO: add checks here */
4007                 declaration->alignment = specifiers->alignment;
4008         }
4009
4010         construct_type_t *construct_type
4011                 = parse_inner_declarator(declaration, may_be_abstract);
4012         type_t *const type = specifiers->type;
4013         declaration->type = construct_declarator_type(construct_type, type);
4014
4015         parse_declaration_attributes(declaration);
4016
4017         fix_declaration_type(declaration);
4018
4019         if (construct_type != NULL) {
4020                 obstack_free(&temp_obst, construct_type);
4021         }
4022
4023         return declaration;
4024 }
4025
4026 static type_t *parse_abstract_declarator(type_t *base_type)
4027 {
4028         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4029
4030         type_t *result = construct_declarator_type(construct_type, base_type);
4031         if (construct_type != NULL) {
4032                 obstack_free(&temp_obst, construct_type);
4033         }
4034
4035         return result;
4036 }
4037
4038 static declaration_t *append_declaration(declaration_t* const declaration)
4039 {
4040         if (last_declaration != NULL) {
4041                 last_declaration->next = declaration;
4042         } else {
4043                 scope->declarations = declaration;
4044         }
4045         last_declaration = declaration;
4046         return declaration;
4047 }
4048
4049 /**
4050  * Check if the declaration of main is suspicious.  main should be a
4051  * function with external linkage, returning int, taking either zero
4052  * arguments, two, or three arguments of appropriate types, ie.
4053  *
4054  * int main([ int argc, char **argv [, char **env ] ]).
4055  *
4056  * @param decl    the declaration to check
4057  * @param type    the function type of the declaration
4058  */
4059 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4060 {
4061         if (decl->storage_class == STORAGE_CLASS_STATIC) {
4062                 warningf(&decl->source_position,
4063                          "'main' is normally a non-static function");
4064         }
4065         if (skip_typeref(func_type->return_type) != type_int) {
4066                 warningf(&decl->source_position,
4067                          "return type of 'main' should be 'int', but is '%T'",
4068                          func_type->return_type);
4069         }
4070         const function_parameter_t *parm = func_type->parameters;
4071         if (parm != NULL) {
4072                 type_t *const first_type = parm->type;
4073                 if (!types_compatible(skip_typeref(first_type), type_int)) {
4074                         warningf(&decl->source_position,
4075                                  "first argument of 'main' should be 'int', but is '%T'", first_type);
4076                 }
4077                 parm = parm->next;
4078                 if (parm != NULL) {
4079                         type_t *const second_type = parm->type;
4080                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4081                                 warningf(&decl->source_position,
4082                                          "second argument of 'main' should be 'char**', but is '%T'", second_type);
4083                         }
4084                         parm = parm->next;
4085                         if (parm != NULL) {
4086                                 type_t *const third_type = parm->type;
4087                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4088                                         warningf(&decl->source_position,
4089                                                  "third argument of 'main' should be 'char**', but is '%T'", third_type);
4090                                 }
4091                                 parm = parm->next;
4092                                 if (parm != NULL)
4093                                         goto warn_arg_count;
4094                         }
4095                 } else {
4096 warn_arg_count:
4097                         warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4098                 }
4099         }
4100 }
4101
4102 /**
4103  * Check if a symbol is the equal to "main".
4104  */
4105 static bool is_sym_main(const symbol_t *const sym)
4106 {
4107         return strcmp(sym->string, "main") == 0;
4108 }
4109
4110 static declaration_t *internal_record_declaration(
4111         declaration_t *const declaration,
4112         const bool is_definition)
4113 {
4114         const symbol_t *const symbol  = declaration->symbol;
4115         const namespace_t     namespc = (namespace_t)declaration->namespc;
4116
4117         assert(symbol != NULL);
4118         declaration_t *previous_declaration = get_declaration(symbol, namespc);
4119
4120         type_t *const orig_type = declaration->type;
4121         type_t *const type      = skip_typeref(orig_type);
4122         if (is_type_function(type) &&
4123                         type->function.unspecified_parameters &&
4124                         warning.strict_prototypes &&
4125                         previous_declaration == NULL) {
4126                 warningf(&declaration->source_position,
4127                          "function declaration '%#T' is not a prototype",
4128                          orig_type, declaration->symbol);
4129         }
4130
4131         if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4132                 check_type_of_main(declaration, &type->function);
4133         }
4134
4135         if (warning.nested_externs                             &&
4136             declaration->storage_class == STORAGE_CLASS_EXTERN &&
4137             scope                      != global_scope) {
4138                 warningf(&declaration->source_position,
4139                          "nested extern declaration of '%#T'", declaration->type, symbol);
4140         }
4141
4142         assert(declaration != previous_declaration);
4143         if (previous_declaration != NULL
4144                         && previous_declaration->parent_scope == scope) {
4145                 /* can happen for K&R style declarations */
4146                 if (previous_declaration->type == NULL) {
4147                         previous_declaration->type = declaration->type;
4148                 }
4149
4150                 const type_t *prev_type = skip_typeref(previous_declaration->type);
4151                 if (!types_compatible(type, prev_type)) {
4152                         errorf(&declaration->source_position,
4153                                    "declaration '%#T' is incompatible with '%#T' (declared %P)",
4154                                    orig_type, symbol, previous_declaration->type, symbol,
4155                                    &previous_declaration->source_position);
4156                 } else {
4157                         unsigned old_storage_class = previous_declaration->storage_class;
4158                         if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4159                                 errorf(&declaration->source_position,
4160                                            "redeclaration of enum entry '%Y' (declared %P)",
4161                                            symbol, &previous_declaration->source_position);
4162                                 return previous_declaration;
4163                         }
4164
4165                         if (warning.redundant_decls                                     &&
4166                             is_definition                                               &&
4167                             previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4168                             !(previous_declaration->modifiers & DM_USED)                &&
4169                             !previous_declaration->used) {
4170                                 warningf(&previous_declaration->source_position,
4171                                          "unnecessary static forward declaration for '%#T'",
4172                                          previous_declaration->type, symbol);
4173                         }
4174
4175                         unsigned new_storage_class = declaration->storage_class;
4176
4177                         if (is_type_incomplete(prev_type)) {
4178                                 previous_declaration->type = type;
4179                                 prev_type                  = type;
4180                         }
4181
4182                         /* pretend no storage class means extern for function
4183                          * declarations (except if the previous declaration is neither
4184                          * none nor extern) */
4185                         if (is_type_function(type)) {
4186                                 if (prev_type->function.unspecified_parameters) {
4187                                         previous_declaration->type = type;
4188                                         prev_type                  = type;
4189                                 }
4190
4191                                 switch (old_storage_class) {
4192                                 case STORAGE_CLASS_NONE:
4193                                         old_storage_class = STORAGE_CLASS_EXTERN;
4194                                         /* FALLTHROUGH */
4195
4196                                 case STORAGE_CLASS_EXTERN:
4197                                         if (is_definition) {
4198                                                 if (warning.missing_prototypes &&
4199                                                     prev_type->function.unspecified_parameters &&
4200                                                     !is_sym_main(symbol)) {
4201                                                         warningf(&declaration->source_position,
4202                                                                          "no previous prototype for '%#T'",
4203                                                                          orig_type, symbol);
4204                                                 }
4205                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
4206                                                 new_storage_class = STORAGE_CLASS_EXTERN;
4207                                         }
4208                                         break;
4209
4210                                 default:
4211                                         break;
4212                                 }
4213                         }
4214
4215                         if (old_storage_class == STORAGE_CLASS_EXTERN &&
4216                                         new_storage_class == STORAGE_CLASS_EXTERN) {
4217 warn_redundant_declaration:
4218                                 if (!is_definition          &&
4219                                     warning.redundant_decls &&
4220                                     strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4221                                         warningf(&declaration->source_position,
4222                                                  "redundant declaration for '%Y' (declared %P)",
4223                                                  symbol, &previous_declaration->source_position);
4224                                 }
4225                         } else if (current_function == NULL) {
4226                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
4227                                     new_storage_class == STORAGE_CLASS_STATIC) {
4228                                         errorf(&declaration->source_position,
4229                                                "static declaration of '%Y' follows non-static declaration (declared %P)",
4230                                                symbol, &previous_declaration->source_position);
4231                                 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4232                                         previous_declaration->storage_class          = STORAGE_CLASS_NONE;
4233                                         previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4234                                 } else {
4235                                         goto warn_redundant_declaration;
4236                                 }
4237                         } else if (old_storage_class == new_storage_class) {
4238                                 errorf(&declaration->source_position,
4239                                        "redeclaration of '%Y' (declared %P)",
4240                                        symbol, &previous_declaration->source_position);
4241                         } else {
4242                                 errorf(&declaration->source_position,
4243                                        "redeclaration of '%Y' with different linkage (declared %P)",
4244                                        symbol, &previous_declaration->source_position);
4245                         }
4246                 }
4247
4248                 previous_declaration->modifiers |= declaration->modifiers;
4249                 previous_declaration->is_inline |= declaration->is_inline;
4250                 return previous_declaration;
4251         } else if (is_type_function(type)) {
4252                 if (is_definition &&
4253                     declaration->storage_class != STORAGE_CLASS_STATIC) {
4254                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
4255                                 warningf(&declaration->source_position,
4256                                          "no previous prototype for '%#T'", orig_type, symbol);
4257                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4258                                 warningf(&declaration->source_position,
4259                                          "no previous declaration for '%#T'", orig_type,
4260                                          symbol);
4261                         }
4262                 }
4263         } else {
4264                 if (warning.missing_declarations &&
4265                     scope == global_scope && (
4266                       declaration->storage_class == STORAGE_CLASS_NONE ||
4267                       declaration->storage_class == STORAGE_CLASS_THREAD
4268                     )) {
4269                         warningf(&declaration->source_position,
4270                                  "no previous declaration for '%#T'", orig_type, symbol);
4271                 }
4272         }
4273
4274         assert(declaration->parent_scope == NULL);
4275         assert(scope != NULL);
4276
4277         declaration->parent_scope = scope;
4278
4279         environment_push(declaration);
4280         return append_declaration(declaration);
4281 }
4282
4283 static declaration_t *record_declaration(declaration_t *declaration)
4284 {
4285         return internal_record_declaration(declaration, false);
4286 }
4287
4288 static declaration_t *record_definition(declaration_t *declaration)
4289 {
4290         return internal_record_declaration(declaration, true);
4291 }
4292
4293 static void parser_error_multiple_definition(declaration_t *declaration,
4294                 const source_position_t *source_position)
4295 {
4296         errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4297                declaration->symbol, &declaration->source_position);
4298 }
4299
4300 static bool is_declaration_specifier(const token_t *token,
4301                                      bool only_specifiers_qualifiers)
4302 {
4303         switch(token->type) {
4304                 TYPE_SPECIFIERS
4305                 TYPE_QUALIFIERS
4306                         return true;
4307                 case T_IDENTIFIER:
4308                         return is_typedef_symbol(token->v.symbol);
4309
4310                 case T___extension__:
4311                 STORAGE_CLASSES
4312                         return !only_specifiers_qualifiers;
4313
4314                 default:
4315                         return false;
4316         }
4317 }
4318
4319 static void parse_init_declarator_rest(declaration_t *declaration)
4320 {
4321         eat('=');
4322
4323         type_t *orig_type = declaration->type;
4324         type_t *type      = skip_typeref(orig_type);
4325
4326         if (declaration->init.initializer != NULL) {
4327                 parser_error_multiple_definition(declaration, HERE);
4328         }
4329
4330         bool must_be_constant = false;
4331         if (declaration->storage_class == STORAGE_CLASS_STATIC
4332                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4333                         || declaration->parent_scope == global_scope) {
4334                 must_be_constant = true;
4335         }
4336
4337         parse_initializer_env_t env;
4338         env.type             = orig_type;
4339         env.must_be_constant = must_be_constant;
4340         env.declaration      = declaration;
4341
4342         initializer_t *initializer = parse_initializer(&env);
4343
4344         if (env.type != orig_type) {
4345                 orig_type         = env.type;
4346                 type              = skip_typeref(orig_type);
4347                 declaration->type = env.type;
4348         }
4349
4350         if (is_type_function(type)) {
4351                 errorf(&declaration->source_position,
4352                        "initializers not allowed for function types at declator '%Y' (type '%T')",
4353                        declaration->symbol, orig_type);
4354         } else {
4355                 declaration->init.initializer = initializer;
4356         }
4357 }
4358
4359 /* parse rest of a declaration without any declarator */
4360 static void parse_anonymous_declaration_rest(
4361                 const declaration_specifiers_t *specifiers,
4362                 parsed_declaration_func finished_declaration)
4363 {
4364         eat(';');
4365
4366         declaration_t *const declaration    = allocate_declaration_zero();
4367         declaration->type                   = specifiers->type;
4368         declaration->declared_storage_class = specifiers->declared_storage_class;
4369         declaration->source_position        = specifiers->source_position;
4370         declaration->modifiers              = specifiers->modifiers;
4371
4372         if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4373                 warningf(&declaration->source_position,
4374                          "useless storage class in empty declaration");
4375         }
4376         declaration->storage_class = STORAGE_CLASS_NONE;
4377
4378         type_t *type = declaration->type;
4379         switch (type->kind) {
4380                 case TYPE_COMPOUND_STRUCT:
4381                 case TYPE_COMPOUND_UNION: {
4382                         if (type->compound.declaration->symbol == NULL) {
4383                                 warningf(&declaration->source_position,
4384                                          "unnamed struct/union that defines no instances");
4385                         }
4386                         break;
4387                 }
4388
4389                 case TYPE_ENUM:
4390                         break;
4391
4392                 default:
4393                         warningf(&declaration->source_position, "empty declaration");
4394                         break;
4395         }
4396
4397         finished_declaration(declaration);
4398 }
4399
4400 static void parse_declaration_rest(declaration_t *ndeclaration,
4401                 const declaration_specifiers_t *specifiers,
4402                 parsed_declaration_func finished_declaration)
4403 {
4404         add_anchor_token(';');
4405         add_anchor_token('=');
4406         add_anchor_token(',');
4407         while(true) {
4408                 declaration_t *declaration = finished_declaration(ndeclaration);
4409
4410                 type_t *orig_type = declaration->type;
4411                 type_t *type      = skip_typeref(orig_type);
4412
4413                 if (type->kind != TYPE_FUNCTION &&
4414                     declaration->is_inline &&
4415                     is_type_valid(type)) {
4416                         warningf(&declaration->source_position,
4417                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
4418                 }
4419
4420                 if (token.type == '=') {
4421                         parse_init_declarator_rest(declaration);
4422                 }
4423
4424                 if (token.type != ',')
4425                         break;
4426                 eat(',');
4427
4428                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4429         }
4430         expect(';');
4431
4432 end_error:
4433         rem_anchor_token(';');
4434         rem_anchor_token('=');
4435         rem_anchor_token(',');
4436 }
4437
4438 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4439 {
4440         symbol_t *symbol  = declaration->symbol;
4441         if (symbol == NULL) {
4442                 errorf(HERE, "anonymous declaration not valid as function parameter");
4443                 return declaration;
4444         }
4445         namespace_t namespc = (namespace_t) declaration->namespc;
4446         if (namespc != NAMESPACE_NORMAL) {
4447                 return record_declaration(declaration);
4448         }
4449
4450         declaration_t *previous_declaration = get_declaration(symbol, namespc);
4451         if (previous_declaration == NULL ||
4452                         previous_declaration->parent_scope != scope) {
4453                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4454                        symbol);
4455                 return declaration;
4456         }
4457
4458         if (previous_declaration->type == NULL) {
4459                 previous_declaration->type          = declaration->type;
4460                 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4461                 previous_declaration->storage_class = declaration->storage_class;
4462                 previous_declaration->parent_scope  = scope;
4463                 return previous_declaration;
4464         } else {
4465                 return record_declaration(declaration);
4466         }
4467 }
4468
4469 static void parse_declaration(parsed_declaration_func finished_declaration)
4470 {
4471         declaration_specifiers_t specifiers;
4472         memset(&specifiers, 0, sizeof(specifiers));
4473         parse_declaration_specifiers(&specifiers);
4474
4475         if (token.type == ';') {
4476                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4477         } else {
4478                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4479                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4480         }
4481 }
4482
4483 static type_t *get_default_promoted_type(type_t *orig_type)
4484 {
4485         type_t *result = orig_type;
4486
4487         type_t *type = skip_typeref(orig_type);
4488         if (is_type_integer(type)) {
4489                 result = promote_integer(type);
4490         } else if (type == type_float) {
4491                 result = type_double;
4492         }
4493
4494         return result;
4495 }
4496
4497 static void parse_kr_declaration_list(declaration_t *declaration)
4498 {
4499         type_t *type = skip_typeref(declaration->type);
4500         if (!is_type_function(type))
4501                 return;
4502
4503         if (!type->function.kr_style_parameters)
4504                 return;
4505
4506         /* push function parameters */
4507         int       top        = environment_top();
4508         scope_t  *last_scope = scope;
4509         set_scope(&declaration->scope);
4510
4511         declaration_t *parameter = declaration->scope.declarations;
4512         for ( ; parameter != NULL; parameter = parameter->next) {
4513                 assert(parameter->parent_scope == NULL);
4514                 parameter->parent_scope = scope;
4515                 environment_push(parameter);
4516         }
4517
4518         /* parse declaration list */
4519         while (is_declaration_specifier(&token, false)) {
4520                 parse_declaration(finished_kr_declaration);
4521         }
4522
4523         /* pop function parameters */
4524         assert(scope == &declaration->scope);
4525         set_scope(last_scope);
4526         environment_pop_to(top);
4527
4528         /* update function type */
4529         type_t *new_type = duplicate_type(type);
4530
4531         function_parameter_t *parameters     = NULL;
4532         function_parameter_t *last_parameter = NULL;
4533
4534         declaration_t *parameter_declaration = declaration->scope.declarations;
4535         for( ; parameter_declaration != NULL;
4536                         parameter_declaration = parameter_declaration->next) {
4537                 type_t *parameter_type = parameter_declaration->type;
4538                 if (parameter_type == NULL) {
4539                         if (strict_mode) {
4540                                 errorf(HERE, "no type specified for function parameter '%Y'",
4541                                        parameter_declaration->symbol);
4542                         } else {
4543                                 if (warning.implicit_int) {
4544                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4545                                                 parameter_declaration->symbol);
4546                                 }
4547                                 parameter_type              = type_int;
4548                                 parameter_declaration->type = parameter_type;
4549                         }
4550                 }
4551
4552                 semantic_parameter(parameter_declaration);
4553                 parameter_type = parameter_declaration->type;
4554
4555                 /*
4556                  * we need the default promoted types for the function type
4557                  */
4558                 parameter_type = get_default_promoted_type(parameter_type);
4559
4560                 function_parameter_t *function_parameter
4561                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4562                 memset(function_parameter, 0, sizeof(function_parameter[0]));
4563
4564                 function_parameter->type = parameter_type;
4565                 if (last_parameter != NULL) {
4566                         last_parameter->next = function_parameter;
4567                 } else {
4568                         parameters = function_parameter;
4569                 }
4570                 last_parameter = function_parameter;
4571         }
4572
4573         /* Â§ 6.9.1.7: A K&R style parameter list does NOT act as a function
4574          * prototype */
4575         new_type->function.parameters             = parameters;
4576         new_type->function.unspecified_parameters = true;
4577
4578         type = typehash_insert(new_type);
4579         if (type != new_type) {
4580                 obstack_free(type_obst, new_type);
4581         }
4582
4583         declaration->type = type;
4584 }
4585
4586 static bool first_err = true;
4587
4588 /**
4589  * When called with first_err set, prints the name of the current function,
4590  * else does noting.
4591  */
4592 static void print_in_function(void)
4593 {
4594         if (first_err) {
4595                 first_err = false;
4596                 diagnosticf("%s: In function '%Y':\n",
4597                         current_function->source_position.input_name,
4598                         current_function->symbol);
4599         }
4600 }
4601
4602 /**
4603  * Check if all labels are defined in the current function.
4604  * Check if all labels are used in the current function.
4605  */
4606 static void check_labels(void)
4607 {
4608         for (const goto_statement_t *goto_statement = goto_first;
4609             goto_statement != NULL;
4610             goto_statement = goto_statement->next) {
4611                 declaration_t *label = goto_statement->label;
4612
4613                 label->used = true;
4614                 if (label->source_position.input_name == NULL) {
4615                         print_in_function();
4616                         errorf(&goto_statement->base.source_position,
4617                                "label '%Y' used but not defined", label->symbol);
4618                  }
4619         }
4620         goto_first = goto_last = NULL;
4621
4622         if (warning.unused_label) {
4623                 for (const label_statement_t *label_statement = label_first;
4624                          label_statement != NULL;
4625                          label_statement = label_statement->next) {
4626                         const declaration_t *label = label_statement->label;
4627
4628                         if (! label->used) {
4629                                 print_in_function();
4630                                 warningf(&label_statement->base.source_position,
4631                                         "label '%Y' defined but not used", label->symbol);
4632                         }
4633                 }
4634         }
4635         label_first = label_last = NULL;
4636 }
4637
4638 /**
4639  * Check declarations of current_function for unused entities.
4640  */
4641 static void check_declarations(void)
4642 {
4643         if (warning.unused_parameter) {
4644                 const scope_t *scope = &current_function->scope;
4645
4646                 const declaration_t *parameter = scope->declarations;
4647                 for (; parameter != NULL; parameter = parameter->next) {
4648                         if (! parameter->used) {
4649                                 print_in_function();
4650                                 warningf(&parameter->source_position,
4651                                          "unused parameter '%Y'", parameter->symbol);
4652                         }
4653                 }
4654         }
4655         if (warning.unused_variable) {
4656         }
4657 }
4658
4659 static int determine_truth(expression_t const* const cond)
4660 {
4661         return
4662                 !is_constant_expression(cond) ? 0 :
4663                 fold_constant(cond) != 0      ? 1 :
4664                 -1;
4665 }
4666
4667 static void check_reachable(statement_t *const stmt)
4668 {
4669         if (stmt->base.reachable)
4670                 return;
4671         if (stmt->kind != STATEMENT_DO_WHILE)
4672                 stmt->base.reachable = true;
4673
4674         statement_t *last = stmt;
4675         statement_t *next;
4676         switch (stmt->kind) {
4677                 case STATEMENT_INVALID:
4678                 case STATEMENT_EMPTY:
4679                 case STATEMENT_DECLARATION:
4680                 case STATEMENT_ASM:
4681                         next = stmt->base.next;
4682                         break;
4683
4684                 case STATEMENT_COMPOUND:
4685                         next = stmt->compound.statements;
4686                         break;
4687
4688                 case STATEMENT_RETURN:
4689                         return;
4690
4691                 case STATEMENT_IF: {
4692                         if_statement_t const* const ifs = &stmt->ifs;
4693                         int            const        val = determine_truth(ifs->condition);
4694
4695                         if (val >= 0)
4696                                 check_reachable(ifs->true_statement);
4697
4698                         if (val > 0)
4699                                 return;
4700
4701                         if (ifs->false_statement != NULL) {
4702                                 check_reachable(ifs->false_statement);
4703                                 return;
4704                         }
4705
4706                         next = stmt->base.next;
4707                         break;
4708                 }
4709
4710                 case STATEMENT_SWITCH: {
4711                         switch_statement_t const *const switchs = &stmt->switchs;
4712                         expression_t       const *const expr    = switchs->expression;
4713
4714                         if (is_constant_expression(expr)) {
4715                                 long                    const val      = fold_constant(expr);
4716                                 case_label_statement_t *      defaults = NULL;
4717                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4718                                         if (i->expression == NULL) {
4719                                                 defaults = i;
4720                                                 continue;
4721                                         }
4722
4723                                         expression_t *const case_expr = i->expression;
4724                                         if (is_constant_expression(case_expr) &&
4725                                             fold_constant(case_expr) == val) {
4726                                                 check_reachable((statement_t*)i);
4727                                                 return;
4728                                         }
4729                                 }
4730
4731                                 if (defaults != NULL) {
4732                                         check_reachable((statement_t*)defaults);
4733                                         return;
4734                                 }
4735                         } else {
4736                                 bool has_default = false;
4737                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4738                                         if (i->expression == NULL)
4739                                                 has_default = true;
4740
4741                                         check_reachable((statement_t*)i);
4742                                 }
4743
4744                                 if (has_default)
4745                                         return;
4746                         }
4747
4748                         next = stmt->base.next;
4749                         break;
4750                 }
4751
4752                 case STATEMENT_EXPRESSION: {
4753                         /* Check for noreturn function call */
4754                         expression_t const *const expr = stmt->expression.expression;
4755                         if (expr->kind == EXPR_CALL) {
4756                                 expression_t const *const func = expr->call.function;
4757                                 if (func->kind == EXPR_REFERENCE) {
4758                                         declaration_t const *const decl = func->reference.declaration;
4759                                         if (decl != NULL && decl->modifiers & DM_NORETURN) {
4760                                                 return;
4761                                         }
4762                                 }
4763                         }
4764
4765                         next = stmt->base.next;
4766                         break;
4767                 }
4768
4769                 case STATEMENT_CONTINUE: {
4770                         statement_t *parent = stmt;
4771                         for (;;) {
4772                                 parent = parent->base.parent;
4773                                 if (parent == NULL) /* continue not within loop */
4774                                         return;
4775
4776                                 next = parent;
4777                                 switch (parent->kind) {
4778                                         case STATEMENT_WHILE:    goto continue_while;
4779                                         case STATEMENT_DO_WHILE: goto continue_do_while;
4780                                         case STATEMENT_FOR:      goto continue_for;
4781
4782                                         default: break;
4783                                 }
4784                         }
4785                 }
4786
4787                 case STATEMENT_BREAK: {
4788                         statement_t *parent = stmt;
4789                         for (;;) {
4790                                 parent = parent->base.parent;
4791                                 if (parent == NULL) /* break not within loop/switch */
4792                                         return;
4793
4794                                 switch (parent->kind) {
4795                                         case STATEMENT_SWITCH:
4796                                         case STATEMENT_WHILE:
4797                                         case STATEMENT_DO_WHILE:
4798                                         case STATEMENT_FOR:
4799                                                 next = parent->base.next;
4800                                                 goto found_break_parent;
4801
4802                                         default: break;
4803                                 }
4804                         }
4805 found_break_parent:
4806                         break;
4807                 }
4808
4809                 case STATEMENT_GOTO:
4810                         next = stmt->gotos.label->init.statement;
4811                         if (next == NULL) /* missing label */
4812                                 return;
4813                         break;
4814
4815                 case STATEMENT_LABEL:
4816                         next = stmt->label.statement;
4817                         break;
4818
4819                 case STATEMENT_CASE_LABEL:
4820                         next = stmt->case_label.statement;
4821                         break;
4822
4823                 case STATEMENT_WHILE: {
4824                         while_statement_t const *const whiles = &stmt->whiles;
4825                         int                      const val    = determine_truth(whiles->condition);
4826
4827                         if (val >= 0)
4828                                 check_reachable(whiles->body);
4829
4830                         if (val > 0)
4831                                 return;
4832
4833                         next = stmt->base.next;
4834                         break;
4835                 }
4836
4837                 case STATEMENT_DO_WHILE:
4838                         next = stmt->do_while.body;
4839                         break;
4840
4841                 case STATEMENT_FOR: {
4842                         for_statement_t *const fors = &stmt->fors;
4843
4844                         if (fors->condition_reachable)
4845                                 return;
4846                         fors->condition_reachable = true;
4847
4848                         expression_t const *const cond = fors->condition;
4849                         int          const        val  =
4850                                 cond == NULL ? 1 : determine_truth(cond);
4851
4852                         if (val >= 0)
4853                                 check_reachable(fors->body);
4854
4855                         if (val > 0)
4856                                 return;
4857
4858                         next = stmt->base.next;
4859                         break;
4860                 }
4861
4862                 case STATEMENT_MS_TRY:
4863                 case STATEMENT_LEAVE:
4864                         panic("unimplemented");
4865         }
4866
4867         while (next == NULL) {
4868                 next = last->base.parent;
4869                 if (next == NULL) {
4870                         type_t *const type = current_function->type;
4871                         assert(is_type_function(type));
4872                         type_t *const ret  = skip_typeref(type->function.return_type);
4873                         if (warning.return_type                    &&
4874                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
4875                             !is_sym_main(current_function->symbol)) {
4876                                 warningf(&stmt->base.source_position,
4877                                          "control reaches end of non-void function");
4878                         }
4879                         return;
4880                 }
4881
4882                 switch (next->kind) {
4883                         case STATEMENT_INVALID:
4884                         case STATEMENT_EMPTY:
4885                         case STATEMENT_DECLARATION:
4886                         case STATEMENT_EXPRESSION:
4887                         case STATEMENT_ASM:
4888                         case STATEMENT_RETURN:
4889                         case STATEMENT_CONTINUE:
4890                         case STATEMENT_BREAK:
4891                         case STATEMENT_GOTO:
4892                         case STATEMENT_LEAVE:
4893                                 panic("invalid control flow in function");
4894
4895                         case STATEMENT_COMPOUND:
4896                         case STATEMENT_IF:
4897                         case STATEMENT_SWITCH:
4898                         case STATEMENT_LABEL:
4899                         case STATEMENT_CASE_LABEL:
4900                                 last = next;
4901                                 next = next->base.next;
4902                                 break;
4903
4904                         case STATEMENT_WHILE: {
4905 continue_while:
4906                                 if (next->base.reachable)
4907                                         return;
4908                                 next->base.reachable = true;
4909
4910                                 while_statement_t const *const whiles = &next->whiles;
4911                                 int                      const val    = determine_truth(whiles->condition);
4912
4913                                 if (val >= 0)
4914                                         check_reachable(whiles->body);
4915
4916                                 if (val > 0)
4917                                         return;
4918
4919                                 last = next;
4920                                 next = next->base.next;
4921                                 break;
4922                         }
4923
4924                         case STATEMENT_DO_WHILE: {
4925 continue_do_while:
4926                                 if (next->base.reachable)
4927                                         return;
4928                                 next->base.reachable = true;
4929
4930                                 do_while_statement_t const *const dw  = &next->do_while;
4931                                 int                  const        val = determine_truth(dw->condition);
4932
4933                                 if (val >= 0)
4934                                         check_reachable(dw->body);
4935
4936                                 if (val > 0)
4937                                         return;
4938
4939                                 last = next;
4940                                 next = next->base.next;
4941                                 break;
4942                         }
4943
4944                         case STATEMENT_FOR: {
4945 continue_for:;
4946                                 for_statement_t *const fors = &next->fors;
4947
4948                                 fors->step_reachable = true;
4949
4950                                 if (fors->condition_reachable)
4951                                         return;
4952                                 fors->condition_reachable = true;
4953
4954                                 expression_t const *const cond = fors->condition;
4955                                 int          const        val  =
4956                                         cond == NULL ? 1 : determine_truth(cond);
4957
4958                                 if (val >= 0)
4959                                         check_reachable(fors->body);
4960
4961                                 if (val > 0)
4962                                         return;
4963
4964                                 last = next;
4965                                 next = next->base.next;
4966                                 break;
4967                         }
4968
4969                         case STATEMENT_MS_TRY:
4970                                 panic("unimplemented");
4971                 }
4972         }
4973
4974         if (next == NULL) {
4975                 next = stmt->base.parent;
4976                 if (next == NULL) {
4977                         warningf(&stmt->base.source_position,
4978                                  "control reaches end of non-void function");
4979                 }
4980         }
4981
4982         check_reachable(next);
4983 }
4984
4985 static void check_unreachable(statement_t const* const stmt)
4986 {
4987         if (!stmt->base.reachable            &&
4988             stmt->kind != STATEMENT_COMPOUND &&
4989             stmt->kind != STATEMENT_DO_WHILE &&
4990             stmt->kind != STATEMENT_FOR) {
4991                 warningf(&stmt->base.source_position,
4992                          "statement is unreachable");
4993         }
4994
4995         switch (stmt->kind) {
4996                 case STATEMENT_INVALID:
4997                 case STATEMENT_EMPTY:
4998                 case STATEMENT_RETURN:
4999                 case STATEMENT_DECLARATION:
5000                 case STATEMENT_EXPRESSION:
5001                 case STATEMENT_CONTINUE:
5002                 case STATEMENT_BREAK:
5003                 case STATEMENT_GOTO:
5004                 case STATEMENT_ASM:
5005                 case STATEMENT_LEAVE:
5006                         break;
5007
5008                 case STATEMENT_COMPOUND:
5009                         if (stmt->compound.statements)
5010                                 check_unreachable(stmt->compound.statements);
5011                         break;
5012
5013                 case STATEMENT_IF:
5014                         check_unreachable(stmt->ifs.true_statement);
5015                         if (stmt->ifs.false_statement != NULL)
5016                                 check_unreachable(stmt->ifs.false_statement);
5017                         break;
5018
5019                 case STATEMENT_SWITCH:
5020                         check_unreachable(stmt->switchs.body);
5021                         break;
5022
5023                 case STATEMENT_LABEL:
5024                         check_unreachable(stmt->label.statement);
5025                         break;
5026
5027                 case STATEMENT_CASE_LABEL:
5028                         check_unreachable(stmt->case_label.statement);
5029                         break;
5030
5031                 case STATEMENT_WHILE:
5032                         check_unreachable(stmt->whiles.body);
5033                         break;
5034
5035                 case STATEMENT_DO_WHILE:
5036                         check_unreachable(stmt->do_while.body);
5037                         if (!stmt->base.reachable) {
5038                                 expression_t const *const cond = stmt->do_while.condition;
5039                                 if (determine_truth(cond) >= 0) {
5040                                         warningf(&cond->base.source_position,
5041                                                  "condition of do-while-loop is unreachable");
5042                                 }
5043                         }
5044                         break;
5045
5046                 case STATEMENT_FOR: {
5047                         for_statement_t const* const fors = &stmt->fors;
5048
5049                         if (!stmt->base.reachable && fors->initialisation != NULL) {
5050                                 warningf(&fors->initialisation->base.source_position,
5051                                          "initialisation of for-statement is unreachable");
5052                         }
5053
5054                         if (!fors->condition_reachable && fors->condition != NULL) {
5055                                 warningf(&fors->condition->base.source_position,
5056                                          "condition of for-statement is unreachable");
5057                         }
5058
5059                         if (!fors->step_reachable && fors->step != NULL) {
5060                                 warningf(&fors->step->base.source_position,
5061                                          "step of for-statement is unreachable");
5062                         }
5063
5064                         check_unreachable(stmt->fors.body);
5065                         break;
5066                 }
5067
5068                 case STATEMENT_MS_TRY:
5069                         panic("unimplemented");
5070         }
5071
5072         if (stmt->base.next)
5073                 check_unreachable(stmt->base.next);
5074 }
5075
5076 static void parse_external_declaration(void)
5077 {
5078         /* function-definitions and declarations both start with declaration
5079          * specifiers */
5080         declaration_specifiers_t specifiers;
5081         memset(&specifiers, 0, sizeof(specifiers));
5082
5083         add_anchor_token(';');
5084         parse_declaration_specifiers(&specifiers);
5085         rem_anchor_token(';');
5086
5087         /* must be a declaration */
5088         if (token.type == ';') {
5089                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
5090                 return;
5091         }
5092
5093         add_anchor_token(',');
5094         add_anchor_token('=');
5095         rem_anchor_token(';');
5096
5097         /* declarator is common to both function-definitions and declarations */
5098         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5099
5100         rem_anchor_token(',');
5101         rem_anchor_token('=');
5102         rem_anchor_token(';');
5103
5104         /* must be a declaration */
5105         switch (token.type) {
5106                 case ',':
5107                 case ';':
5108                         parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5109                         return;
5110
5111                 case '=':
5112                         parse_declaration_rest(ndeclaration, &specifiers, record_definition);
5113                         return;
5114         }
5115
5116         /* must be a function definition */
5117         parse_kr_declaration_list(ndeclaration);
5118
5119         if (token.type != '{') {
5120                 parse_error_expected("while parsing function definition", '{', NULL);
5121                 eat_until_matching_token(';');
5122                 return;
5123         }
5124
5125         type_t *type = ndeclaration->type;
5126
5127         /* note that we don't skip typerefs: the standard doesn't allow them here
5128          * (so we can't use is_type_function here) */
5129         if (type->kind != TYPE_FUNCTION) {
5130                 if (is_type_valid(type)) {
5131                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
5132                                type, ndeclaration->symbol);
5133                 }
5134                 eat_block();
5135                 return;
5136         }
5137
5138         /* Â§ 6.7.5.3 (14) a function definition with () means no
5139          * parameters (and not unspecified parameters) */
5140         if (type->function.unspecified_parameters
5141                         && type->function.parameters == NULL
5142                         && !type->function.kr_style_parameters) {
5143                 type_t *duplicate = duplicate_type(type);
5144                 duplicate->function.unspecified_parameters = false;
5145
5146                 type = typehash_insert(duplicate);
5147                 if (type != duplicate) {
5148                         obstack_free(type_obst, duplicate);
5149                 }
5150                 ndeclaration->type = type;
5151         }
5152
5153         declaration_t *const declaration = record_definition(ndeclaration);
5154         if (ndeclaration != declaration) {
5155                 declaration->scope = ndeclaration->scope;
5156         }
5157         type = skip_typeref(declaration->type);
5158
5159         /* push function parameters and switch scope */
5160         int       top        = environment_top();
5161         scope_t  *last_scope = scope;
5162         set_scope(&declaration->scope);
5163
5164         declaration_t *parameter = declaration->scope.declarations;
5165         for( ; parameter != NULL; parameter = parameter->next) {
5166                 if (parameter->parent_scope == &ndeclaration->scope) {
5167                         parameter->parent_scope = scope;
5168                 }
5169                 assert(parameter->parent_scope == NULL
5170                                 || parameter->parent_scope == scope);
5171                 parameter->parent_scope = scope;
5172                 if (parameter->symbol == NULL) {
5173                         errorf(&ndeclaration->source_position, "parameter name omitted");
5174                         continue;
5175                 }
5176                 environment_push(parameter);
5177         }
5178
5179         if (declaration->init.statement != NULL) {
5180                 parser_error_multiple_definition(declaration, HERE);
5181                 eat_block();
5182         } else {
5183                 /* parse function body */
5184                 int            label_stack_top      = label_top();
5185                 declaration_t *old_current_function = current_function;
5186                 current_function                    = declaration;
5187                 current_parent                      = NULL;
5188
5189                 statement_t *const body = parse_compound_statement(false);
5190                 declaration->init.statement = body;
5191                 first_err = true;
5192                 check_labels();
5193                 check_declarations();
5194                 if (warning.return_type || warning.unreachable_code) {
5195                         check_reachable(body);
5196                         if (warning.unreachable_code)
5197                                 check_unreachable(body);
5198                 }
5199
5200                 assert(current_parent   == NULL);
5201                 assert(current_function == declaration);
5202                 current_function = old_current_function;
5203                 label_pop_to(label_stack_top);
5204         }
5205
5206         assert(scope == &declaration->scope);
5207         set_scope(last_scope);
5208         environment_pop_to(top);
5209 }
5210
5211 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5212                                   source_position_t *source_position)
5213 {
5214         type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5215
5216         type->bitfield.base_type = base_type;
5217         type->bitfield.size      = size;
5218
5219         return type;
5220 }
5221
5222 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5223                                           symbol_t *symbol)
5224 {
5225         declaration_t *iter = compound_declaration->scope.declarations;
5226         for( ; iter != NULL; iter = iter->next) {
5227                 if (iter->namespc != NAMESPACE_NORMAL)
5228                         continue;
5229
5230                 if (iter->symbol == NULL) {
5231                         type_t *type = skip_typeref(iter->type);
5232                         if (is_type_compound(type)) {
5233                                 declaration_t *result
5234                                         = find_compound_entry(type->compound.declaration, symbol);
5235                                 if (result != NULL)
5236                                         return result;
5237                         }
5238                         continue;
5239                 }
5240
5241                 if (iter->symbol == symbol) {
5242                         return iter;
5243                 }
5244         }
5245
5246         return NULL;
5247 }
5248
5249 static void parse_compound_declarators(declaration_t *struct_declaration,
5250                 const declaration_specifiers_t *specifiers)
5251 {
5252         declaration_t *last_declaration = struct_declaration->scope.declarations;
5253         if (last_declaration != NULL) {
5254                 while(last_declaration->next != NULL) {
5255                         last_declaration = last_declaration->next;
5256                 }
5257         }
5258
5259         while(1) {
5260                 declaration_t *declaration;
5261
5262                 if (token.type == ':') {
5263                         source_position_t source_position = *HERE;
5264                         next_token();
5265
5266                         type_t *base_type = specifiers->type;
5267                         expression_t *size = parse_constant_expression();
5268
5269                         if (!is_type_integer(skip_typeref(base_type))) {
5270                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
5271                                        base_type);
5272                         }
5273
5274                         type_t *type = make_bitfield_type(base_type, size, &source_position);
5275
5276                         declaration                         = allocate_declaration_zero();
5277                         declaration->namespc                = NAMESPACE_NORMAL;
5278                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
5279                         declaration->storage_class          = STORAGE_CLASS_NONE;
5280                         declaration->source_position        = source_position;
5281                         declaration->modifiers              = specifiers->modifiers;
5282                         declaration->type                   = type;
5283                 } else {
5284                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5285
5286                         type_t *orig_type = declaration->type;
5287                         type_t *type      = skip_typeref(orig_type);
5288
5289                         if (token.type == ':') {
5290                                 source_position_t source_position = *HERE;
5291                                 next_token();
5292                                 expression_t *size = parse_constant_expression();
5293
5294                                 if (!is_type_integer(type)) {
5295                                         errorf(HERE, "bitfield base type '%T' is not an "
5296                                                "integer type", orig_type);
5297                                 }
5298
5299                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5300                                 declaration->type = bitfield_type;
5301                         } else {
5302                                 /* TODO we ignore arrays for now... what is missing is a check
5303                                  * that they're at the end of the struct */
5304                                 if (is_type_incomplete(type) && !is_type_array(type)) {
5305                                         errorf(HERE,
5306                                                "compound member '%Y' has incomplete type '%T'",
5307                                                declaration->symbol, orig_type);
5308                                 } else if (is_type_function(type)) {
5309                                         errorf(HERE, "compound member '%Y' must not have function "
5310                                                "type '%T'", declaration->symbol, orig_type);
5311                                 }
5312                         }
5313                 }
5314
5315                 /* make sure we don't define a symbol multiple times */
5316                 symbol_t *symbol = declaration->symbol;
5317                 if (symbol != NULL) {
5318                         declaration_t *prev_decl
5319                                 = find_compound_entry(struct_declaration, symbol);
5320
5321                         if (prev_decl != NULL) {
5322                                 assert(prev_decl->symbol == symbol);
5323                                 errorf(&declaration->source_position,
5324                                        "multiple declarations of symbol '%Y' (declared %P)",
5325                                        symbol, &prev_decl->source_position);
5326                         }
5327                 }
5328
5329                 /* append declaration */
5330                 if (last_declaration != NULL) {
5331                         last_declaration->next = declaration;
5332                 } else {
5333                         struct_declaration->scope.declarations = declaration;
5334                 }
5335                 last_declaration = declaration;
5336
5337                 if (token.type != ',')
5338                         break;
5339                 next_token();
5340         }
5341         expect(';');
5342
5343 end_error:
5344         ;
5345 }
5346
5347 static void parse_compound_type_entries(declaration_t *compound_declaration)
5348 {
5349         eat('{');
5350         add_anchor_token('}');
5351
5352         while(token.type != '}' && token.type != T_EOF) {
5353                 declaration_specifiers_t specifiers;
5354                 memset(&specifiers, 0, sizeof(specifiers));
5355                 parse_declaration_specifiers(&specifiers);
5356
5357                 parse_compound_declarators(compound_declaration, &specifiers);
5358         }
5359         rem_anchor_token('}');
5360
5361         if (token.type == T_EOF) {
5362                 errorf(HERE, "EOF while parsing struct");
5363         }
5364         next_token();
5365 }
5366
5367 static type_t *parse_typename(void)
5368 {
5369         declaration_specifiers_t specifiers;
5370         memset(&specifiers, 0, sizeof(specifiers));
5371         parse_declaration_specifiers(&specifiers);
5372         if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5373                 /* TODO: improve error message, user does probably not know what a
5374                  * storage class is...
5375                  */
5376                 errorf(HERE, "typename may not have a storage class");
5377         }
5378
5379         type_t *result = parse_abstract_declarator(specifiers.type);
5380
5381         return result;
5382 }
5383
5384
5385
5386
5387 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5388 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5389                                                           expression_t *left);
5390
5391 typedef struct expression_parser_function_t expression_parser_function_t;
5392 struct expression_parser_function_t {
5393         unsigned                         precedence;
5394         parse_expression_function        parser;
5395         unsigned                         infix_precedence;
5396         parse_expression_infix_function  infix_parser;
5397 };
5398
5399 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5400
5401 /**
5402  * Prints an error message if an expression was expected but not read
5403  */
5404 static expression_t *expected_expression_error(void)
5405 {
5406         /* skip the error message if the error token was read */
5407         if (token.type != T_ERROR) {
5408                 errorf(HERE, "expected expression, got token '%K'", &token);
5409         }
5410         next_token();
5411
5412         return create_invalid_expression();
5413 }
5414
5415 /**
5416  * Parse a string constant.
5417  */
5418 static expression_t *parse_string_const(void)
5419 {
5420         wide_string_t wres;
5421         if (token.type == T_STRING_LITERAL) {
5422                 string_t res = token.v.string;
5423                 next_token();
5424                 while (token.type == T_STRING_LITERAL) {
5425                         res = concat_strings(&res, &token.v.string);
5426                         next_token();
5427                 }
5428                 if (token.type != T_WIDE_STRING_LITERAL) {
5429                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5430                         /* note: that we use type_char_ptr here, which is already the
5431                          * automatic converted type. revert_automatic_type_conversion
5432                          * will construct the array type */
5433                         cnst->base.type    = type_char_ptr;
5434                         cnst->string.value = res;
5435                         return cnst;
5436                 }
5437
5438                 wres = concat_string_wide_string(&res, &token.v.wide_string);
5439         } else {
5440                 wres = token.v.wide_string;
5441         }
5442         next_token();
5443
5444         for (;;) {
5445                 switch (token.type) {
5446                         case T_WIDE_STRING_LITERAL:
5447                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
5448                                 break;
5449
5450                         case T_STRING_LITERAL:
5451                                 wres = concat_wide_string_string(&wres, &token.v.string);
5452                                 break;
5453
5454                         default: {
5455                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5456                                 cnst->base.type         = type_wchar_t_ptr;
5457                                 cnst->wide_string.value = wres;
5458                                 return cnst;
5459                         }
5460                 }
5461                 next_token();
5462         }
5463 }
5464
5465 /**
5466  * Parse an integer constant.
5467  */
5468 static expression_t *parse_int_const(void)
5469 {
5470         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5471         cnst->base.source_position = *HERE;
5472         cnst->base.type            = token.datatype;
5473         cnst->conste.v.int_value   = token.v.intvalue;
5474
5475         next_token();
5476
5477         return cnst;
5478 }
5479
5480 /**
5481  * Parse a character constant.
5482  */
5483 static expression_t *parse_character_constant(void)
5484 {
5485         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5486
5487         cnst->base.source_position = *HERE;
5488         cnst->base.type            = token.datatype;
5489         cnst->conste.v.character   = token.v.string;
5490
5491         if (cnst->conste.v.character.size != 1) {
5492                 if (warning.multichar && (c_mode & _GNUC)) {
5493                         /* TODO */
5494                         warningf(HERE, "multi-character character constant");
5495                 } else {
5496                         errorf(HERE, "more than 1 characters in character constant");
5497                 }
5498         }
5499         next_token();
5500
5501         return cnst;
5502 }
5503
5504 /**
5505  * Parse a wide character constant.
5506  */
5507 static expression_t *parse_wide_character_constant(void)
5508 {
5509         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5510
5511         cnst->base.source_position    = *HERE;
5512         cnst->base.type               = token.datatype;
5513         cnst->conste.v.wide_character = token.v.wide_string;
5514
5515         if (cnst->conste.v.wide_character.size != 1) {
5516                 if (warning.multichar && (c_mode & _GNUC)) {
5517                         /* TODO */
5518                         warningf(HERE, "multi-character character constant");
5519                 } else {
5520                         errorf(HERE, "more than 1 characters in character constant");
5521                 }
5522         }
5523         next_token();
5524
5525         return cnst;
5526 }
5527
5528 /**
5529  * Parse a float constant.
5530  */
5531 static expression_t *parse_float_const(void)
5532 {
5533         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5534         cnst->base.type            = token.datatype;
5535         cnst->conste.v.float_value = token.v.floatvalue;
5536
5537         next_token();
5538
5539         return cnst;
5540 }
5541
5542 static declaration_t *create_implicit_function(symbol_t *symbol,
5543                 const source_position_t *source_position)
5544 {
5545         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
5546         ntype->function.return_type            = type_int;
5547         ntype->function.unspecified_parameters = true;
5548
5549         type_t *type = typehash_insert(ntype);
5550         if (type != ntype) {
5551                 free_type(ntype);
5552         }
5553
5554         declaration_t *const declaration    = allocate_declaration_zero();
5555         declaration->storage_class          = STORAGE_CLASS_EXTERN;
5556         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5557         declaration->type                   = type;
5558         declaration->symbol                 = symbol;
5559         declaration->source_position        = *source_position;
5560
5561         bool strict_prototypes_old = warning.strict_prototypes;
5562         warning.strict_prototypes  = false;
5563         record_declaration(declaration);
5564         warning.strict_prototypes = strict_prototypes_old;
5565
5566         return declaration;
5567 }
5568
5569 /**
5570  * Creates a return_type (func)(argument_type) function type if not
5571  * already exists.
5572  */
5573 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5574                                     type_t *argument_type2)
5575 {
5576         function_parameter_t *parameter2
5577                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5578         memset(parameter2, 0, sizeof(parameter2[0]));
5579         parameter2->type = argument_type2;
5580
5581         function_parameter_t *parameter1
5582                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5583         memset(parameter1, 0, sizeof(parameter1[0]));
5584         parameter1->type = argument_type1;
5585         parameter1->next = parameter2;
5586
5587         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5588         type->function.return_type = return_type;
5589         type->function.parameters  = parameter1;
5590
5591         type_t *result = typehash_insert(type);
5592         if (result != type) {
5593                 free_type(type);
5594         }
5595
5596         return result;
5597 }
5598
5599 /**
5600  * Creates a return_type (func)(argument_type) function type if not
5601  * already exists.
5602  *
5603  * @param return_type    the return type
5604  * @param argument_type  the argument type
5605  */
5606 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5607 {
5608         function_parameter_t *parameter
5609                 = obstack_alloc(type_obst, sizeof(parameter[0]));
5610         memset(parameter, 0, sizeof(parameter[0]));
5611         parameter->type = argument_type;
5612
5613         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5614         type->function.return_type = return_type;
5615         type->function.parameters  = parameter;
5616
5617         type_t *result = typehash_insert(type);
5618         if (result != type) {
5619                 free_type(type);
5620         }
5621
5622         return result;
5623 }
5624
5625 static type_t *make_function_0_type(type_t *return_type)
5626 {
5627         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5628         type->function.return_type = return_type;
5629         type->function.parameters  = NULL;
5630
5631         type_t *result = typehash_insert(type);
5632         if (result != type) {
5633                 free_type(type);
5634         }
5635
5636         return result;
5637 }
5638
5639 /**
5640  * Creates a function type for some function like builtins.
5641  *
5642  * @param symbol   the symbol describing the builtin
5643  */
5644 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5645 {
5646         switch(symbol->ID) {
5647         case T___builtin_alloca:
5648                 return make_function_1_type(type_void_ptr, type_size_t);
5649         case T___builtin_huge_val:
5650                 return make_function_0_type(type_double);
5651         case T___builtin_nan:
5652                 return make_function_1_type(type_double, type_char_ptr);
5653         case T___builtin_nanf:
5654                 return make_function_1_type(type_float, type_char_ptr);
5655         case T___builtin_nand:
5656                 return make_function_1_type(type_long_double, type_char_ptr);
5657         case T___builtin_va_end:
5658                 return make_function_1_type(type_void, type_valist);
5659         case T___builtin_expect:
5660                 return make_function_2_type(type_long, type_long, type_long);
5661         default:
5662                 internal_errorf(HERE, "not implemented builtin symbol found");
5663         }
5664 }
5665
5666 /**
5667  * Performs automatic type cast as described in Â§ 6.3.2.1.
5668  *
5669  * @param orig_type  the original type
5670  */
5671 static type_t *automatic_type_conversion(type_t *orig_type)
5672 {
5673         type_t *type = skip_typeref(orig_type);
5674         if (is_type_array(type)) {
5675                 array_type_t *array_type   = &type->array;
5676                 type_t       *element_type = array_type->element_type;
5677                 unsigned      qualifiers   = array_type->base.qualifiers;
5678
5679                 return make_pointer_type(element_type, qualifiers);
5680         }
5681
5682         if (is_type_function(type)) {
5683                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5684         }
5685
5686         return orig_type;
5687 }
5688
5689 /**
5690  * reverts the automatic casts of array to pointer types and function
5691  * to function-pointer types as defined Â§ 6.3.2.1
5692  */
5693 type_t *revert_automatic_type_conversion(const expression_t *expression)
5694 {
5695         switch (expression->kind) {
5696                 case EXPR_REFERENCE: return expression->reference.declaration->type;
5697                 case EXPR_SELECT:    return expression->select.compound_entry->type;
5698
5699                 case EXPR_UNARY_DEREFERENCE: {
5700                         const expression_t *const value = expression->unary.value;
5701                         type_t             *const type  = skip_typeref(value->base.type);
5702                         assert(is_type_pointer(type));
5703                         return type->pointer.points_to;
5704                 }
5705
5706                 case EXPR_BUILTIN_SYMBOL:
5707                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5708
5709                 case EXPR_ARRAY_ACCESS: {
5710                         const expression_t *array_ref = expression->array_access.array_ref;
5711                         type_t             *type_left = skip_typeref(array_ref->base.type);
5712                         if (!is_type_valid(type_left))
5713                                 return type_left;
5714                         assert(is_type_pointer(type_left));
5715                         return type_left->pointer.points_to;
5716                 }
5717
5718                 case EXPR_STRING_LITERAL: {
5719                         size_t size = expression->string.value.size;
5720                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5721                 }
5722
5723                 case EXPR_WIDE_STRING_LITERAL: {
5724                         size_t size = expression->wide_string.value.size;
5725                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5726                 }
5727
5728                 case EXPR_COMPOUND_LITERAL:
5729                         return expression->compound_literal.type;
5730
5731                 default: break;
5732         }
5733
5734         return expression->base.type;
5735 }
5736
5737 static expression_t *parse_reference(void)
5738 {
5739         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5740
5741         reference_expression_t *ref = &expression->reference;
5742         symbol_t *const symbol = token.v.symbol;
5743
5744         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5745
5746         source_position_t source_position = token.source_position;
5747         next_token();
5748
5749         if (declaration == NULL) {
5750                 if (! strict_mode && token.type == '(') {
5751                         /* an implicitly defined function */
5752                         if (warning.implicit_function_declaration) {
5753                                 warningf(HERE, "implicit declaration of function '%Y'",
5754                                         symbol);
5755                         }
5756
5757                         declaration = create_implicit_function(symbol,
5758                                                                &source_position);
5759                 } else {
5760                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
5761                         return create_invalid_expression();
5762                 }
5763         }
5764
5765         type_t *type         = declaration->type;
5766
5767         /* we always do the auto-type conversions; the & and sizeof parser contains
5768          * code to revert this! */
5769         type = automatic_type_conversion(type);
5770
5771         ref->declaration = declaration;
5772         ref->base.type   = type;
5773
5774         /* this declaration is used */
5775         declaration->used = true;
5776
5777         /* check for deprecated functions */
5778         if (warning.deprecated_declarations &&
5779             declaration->modifiers & DM_DEPRECATED) {
5780                 char const *const prefix = is_type_function(declaration->type) ?
5781                         "function" : "variable";
5782
5783                 if (declaration->deprecated_string != NULL) {
5784                         warningf(&source_position,
5785                                 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
5786                                 declaration->symbol, &declaration->source_position,
5787                                 declaration->deprecated_string);
5788                 } else {
5789                         warningf(&source_position,
5790                                 "%s '%Y' is deprecated (declared %P)", prefix,
5791                                 declaration->symbol, &declaration->source_position);
5792                 }
5793         }
5794
5795         return expression;
5796 }
5797
5798 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5799 {
5800         (void) expression;
5801         (void) dest_type;
5802         /* TODO check if explicit cast is allowed and issue warnings/errors */
5803 }
5804
5805 static expression_t *parse_compound_literal(type_t *type)
5806 {
5807         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5808
5809         parse_initializer_env_t env;
5810         env.type             = type;
5811         env.declaration      = NULL;
5812         env.must_be_constant = false;
5813         initializer_t *initializer = parse_initializer(&env);
5814         type = env.type;
5815
5816         expression->compound_literal.initializer = initializer;
5817         expression->compound_literal.type        = type;
5818         expression->base.type                    = automatic_type_conversion(type);
5819
5820         return expression;
5821 }
5822
5823 /**
5824  * Parse a cast expression.
5825  */
5826 static expression_t *parse_cast(void)
5827 {
5828         source_position_t source_position = token.source_position;
5829
5830         type_t *type  = parse_typename();
5831
5832         /* matching add_anchor_token() is at call site */
5833         rem_anchor_token(')');
5834         expect(')');
5835
5836         if (token.type == '{') {
5837                 return parse_compound_literal(type);
5838         }
5839
5840         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5841         cast->base.source_position = source_position;
5842
5843         expression_t *value = parse_sub_expression(20);
5844
5845         check_cast_allowed(value, type);
5846
5847         cast->base.type   = type;
5848         cast->unary.value = value;
5849
5850         return cast;
5851 end_error:
5852         return create_invalid_expression();
5853 }
5854
5855 /**
5856  * Parse a statement expression.
5857  */
5858 static expression_t *parse_statement_expression(void)
5859 {
5860         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5861
5862         statement_t *statement           = parse_compound_statement(true);
5863         expression->statement.statement  = statement;
5864         expression->base.source_position = statement->base.source_position;
5865
5866         /* find last statement and use its type */
5867         type_t *type = type_void;
5868         const statement_t *stmt = statement->compound.statements;
5869         if (stmt != NULL) {
5870                 while (stmt->base.next != NULL)
5871                         stmt = stmt->base.next;
5872
5873                 if (stmt->kind == STATEMENT_EXPRESSION) {
5874                         type = stmt->expression.expression->base.type;
5875                 }
5876         } else {
5877                 warningf(&expression->base.source_position, "empty statement expression ({})");
5878         }
5879         expression->base.type = type;
5880
5881         expect(')');
5882
5883         return expression;
5884 end_error:
5885         return create_invalid_expression();
5886 }
5887
5888 /**
5889  * Parse a braced expression.
5890  */
5891 static expression_t *parse_brace_expression(void)
5892 {
5893         eat('(');
5894         add_anchor_token(')');
5895
5896         switch(token.type) {
5897         case '{':
5898                 /* gcc extension: a statement expression */
5899                 return parse_statement_expression();
5900
5901         TYPE_QUALIFIERS
5902         TYPE_SPECIFIERS
5903                 return parse_cast();
5904         case T_IDENTIFIER:
5905                 if (is_typedef_symbol(token.v.symbol)) {
5906                         return parse_cast();
5907                 }
5908         }
5909
5910         expression_t *result = parse_expression();
5911         rem_anchor_token(')');
5912         expect(')');
5913
5914         return result;
5915 end_error:
5916         return create_invalid_expression();
5917 }
5918
5919 static expression_t *parse_function_keyword(void)
5920 {
5921         next_token();
5922         /* TODO */
5923
5924         if (current_function == NULL) {
5925                 errorf(HERE, "'__func__' used outside of a function");
5926         }
5927
5928         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5929         expression->base.type     = type_char_ptr;
5930         expression->funcname.kind = FUNCNAME_FUNCTION;
5931
5932         return expression;
5933 }
5934
5935 static expression_t *parse_pretty_function_keyword(void)
5936 {
5937         eat(T___PRETTY_FUNCTION__);
5938
5939         if (current_function == NULL) {
5940                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5941         }
5942
5943         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5944         expression->base.type     = type_char_ptr;
5945         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5946
5947         return expression;
5948 }
5949
5950 static expression_t *parse_funcsig_keyword(void)
5951 {
5952         eat(T___FUNCSIG__);
5953
5954         if (current_function == NULL) {
5955                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5956         }
5957
5958         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5959         expression->base.type     = type_char_ptr;
5960         expression->funcname.kind = FUNCNAME_FUNCSIG;
5961
5962         return expression;
5963 }
5964
5965 static expression_t *parse_funcdname_keyword(void)
5966 {
5967         eat(T___FUNCDNAME__);
5968
5969         if (current_function == NULL) {
5970                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5971         }
5972
5973         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5974         expression->base.type     = type_char_ptr;
5975         expression->funcname.kind = FUNCNAME_FUNCDNAME;
5976
5977         return expression;
5978 }
5979
5980 static designator_t *parse_designator(void)
5981 {
5982         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
5983         result->source_position = *HERE;
5984
5985         if (token.type != T_IDENTIFIER) {
5986                 parse_error_expected("while parsing member designator",
5987                                      T_IDENTIFIER, NULL);
5988                 return NULL;
5989         }
5990         result->symbol = token.v.symbol;
5991         next_token();
5992
5993         designator_t *last_designator = result;
5994         while(true) {
5995                 if (token.type == '.') {
5996                         next_token();
5997                         if (token.type != T_IDENTIFIER) {
5998                                 parse_error_expected("while parsing member designator",
5999                                                      T_IDENTIFIER, NULL);
6000                                 return NULL;
6001                         }
6002                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6003                         designator->source_position = *HERE;
6004                         designator->symbol          = token.v.symbol;
6005                         next_token();
6006
6007                         last_designator->next = designator;
6008                         last_designator       = designator;
6009                         continue;
6010                 }
6011                 if (token.type == '[') {
6012                         next_token();
6013                         add_anchor_token(']');
6014                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6015                         designator->source_position = *HERE;
6016                         designator->array_index     = parse_expression();
6017                         rem_anchor_token(']');
6018                         expect(']');
6019                         if (designator->array_index == NULL) {
6020                                 return NULL;
6021                         }
6022
6023                         last_designator->next = designator;
6024                         last_designator       = designator;
6025                         continue;
6026                 }
6027                 break;
6028         }
6029
6030         return result;
6031 end_error:
6032         return NULL;
6033 }
6034
6035 /**
6036  * Parse the __builtin_offsetof() expression.
6037  */
6038 static expression_t *parse_offsetof(void)
6039 {
6040         eat(T___builtin_offsetof);
6041
6042         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6043         expression->base.type    = type_size_t;
6044
6045         expect('(');
6046         add_anchor_token(',');
6047         type_t *type = parse_typename();
6048         rem_anchor_token(',');
6049         expect(',');
6050         add_anchor_token(')');
6051         designator_t *designator = parse_designator();
6052         rem_anchor_token(')');
6053         expect(')');
6054
6055         expression->offsetofe.type       = type;
6056         expression->offsetofe.designator = designator;
6057
6058         type_path_t path;
6059         memset(&path, 0, sizeof(path));
6060         path.top_type = type;
6061         path.path     = NEW_ARR_F(type_path_entry_t, 0);
6062
6063         descend_into_subtype(&path);
6064
6065         if (!walk_designator(&path, designator, true)) {
6066                 return create_invalid_expression();
6067         }
6068
6069         DEL_ARR_F(path.path);
6070
6071         return expression;
6072 end_error:
6073         return create_invalid_expression();
6074 }
6075
6076 /**
6077  * Parses a _builtin_va_start() expression.
6078  */
6079 static expression_t *parse_va_start(void)
6080 {
6081         eat(T___builtin_va_start);
6082
6083         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6084
6085         expect('(');
6086         add_anchor_token(',');
6087         expression->va_starte.ap = parse_assignment_expression();
6088         rem_anchor_token(',');
6089         expect(',');
6090         expression_t *const expr = parse_assignment_expression();
6091         if (expr->kind == EXPR_REFERENCE) {
6092                 declaration_t *const decl = expr->reference.declaration;
6093                 if (decl == NULL)
6094                         return create_invalid_expression();
6095                 if (decl->parent_scope == &current_function->scope &&
6096                     decl->next == NULL) {
6097                         expression->va_starte.parameter = decl;
6098                         expect(')');
6099                         return expression;
6100                 }
6101         }
6102         errorf(&expr->base.source_position,
6103                "second argument of 'va_start' must be last parameter of the current function");
6104 end_error:
6105         return create_invalid_expression();
6106 }
6107
6108 /**
6109  * Parses a _builtin_va_arg() expression.
6110  */
6111 static expression_t *parse_va_arg(void)
6112 {
6113         eat(T___builtin_va_arg);
6114
6115         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6116
6117         expect('(');
6118         expression->va_arge.ap = parse_assignment_expression();
6119         expect(',');
6120         expression->base.type = parse_typename();
6121         expect(')');
6122
6123         return expression;
6124 end_error:
6125         return create_invalid_expression();
6126 }
6127
6128 static expression_t *parse_builtin_symbol(void)
6129 {
6130         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6131
6132         symbol_t *symbol = token.v.symbol;
6133
6134         expression->builtin_symbol.symbol = symbol;
6135         next_token();
6136
6137         type_t *type = get_builtin_symbol_type(symbol);
6138         type = automatic_type_conversion(type);
6139
6140         expression->base.type = type;
6141         return expression;
6142 }
6143
6144 /**
6145  * Parses a __builtin_constant() expression.
6146  */
6147 static expression_t *parse_builtin_constant(void)
6148 {
6149         eat(T___builtin_constant_p);
6150
6151         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6152
6153         expect('(');
6154         add_anchor_token(')');
6155         expression->builtin_constant.value = parse_assignment_expression();
6156         rem_anchor_token(')');
6157         expect(')');
6158         expression->base.type = type_int;
6159
6160         return expression;
6161 end_error:
6162         return create_invalid_expression();
6163 }
6164
6165 /**
6166  * Parses a __builtin_prefetch() expression.
6167  */
6168 static expression_t *parse_builtin_prefetch(void)
6169 {
6170         eat(T___builtin_prefetch);
6171
6172         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6173
6174         expect('(');
6175         add_anchor_token(')');
6176         expression->builtin_prefetch.adr = parse_assignment_expression();
6177         if (token.type == ',') {
6178                 next_token();
6179                 expression->builtin_prefetch.rw = parse_assignment_expression();
6180         }
6181         if (token.type == ',') {
6182                 next_token();
6183                 expression->builtin_prefetch.locality = parse_assignment_expression();
6184         }
6185         rem_anchor_token(')');
6186         expect(')');
6187         expression->base.type = type_void;
6188
6189         return expression;
6190 end_error:
6191         return create_invalid_expression();
6192 }
6193
6194 /**
6195  * Parses a __builtin_is_*() compare expression.
6196  */
6197 static expression_t *parse_compare_builtin(void)
6198 {
6199         expression_t *expression;
6200
6201         switch(token.type) {
6202         case T___builtin_isgreater:
6203                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6204                 break;
6205         case T___builtin_isgreaterequal:
6206                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6207                 break;
6208         case T___builtin_isless:
6209                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6210                 break;
6211         case T___builtin_islessequal:
6212                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6213                 break;
6214         case T___builtin_islessgreater:
6215                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6216                 break;
6217         case T___builtin_isunordered:
6218                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6219                 break;
6220         default:
6221                 internal_errorf(HERE, "invalid compare builtin found");
6222                 break;
6223         }
6224         expression->base.source_position = *HERE;
6225         next_token();
6226
6227         expect('(');
6228         expression->binary.left = parse_assignment_expression();
6229         expect(',');
6230         expression->binary.right = parse_assignment_expression();
6231         expect(')');
6232
6233         type_t *const orig_type_left  = expression->binary.left->base.type;
6234         type_t *const orig_type_right = expression->binary.right->base.type;
6235
6236         type_t *const type_left  = skip_typeref(orig_type_left);
6237         type_t *const type_right = skip_typeref(orig_type_right);
6238         if (!is_type_float(type_left) && !is_type_float(type_right)) {
6239                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6240                         type_error_incompatible("invalid operands in comparison",
6241                                 &expression->base.source_position, orig_type_left, orig_type_right);
6242                 }
6243         } else {
6244                 semantic_comparison(&expression->binary);
6245         }
6246
6247         return expression;
6248 end_error:
6249         return create_invalid_expression();
6250 }
6251
6252 #if 0
6253 /**
6254  * Parses a __builtin_expect() expression.
6255  */
6256 static expression_t *parse_builtin_expect(void)
6257 {
6258         eat(T___builtin_expect);
6259
6260         expression_t *expression
6261                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6262
6263         expect('(');
6264         expression->binary.left = parse_assignment_expression();
6265         expect(',');
6266         expression->binary.right = parse_constant_expression();
6267         expect(')');
6268
6269         expression->base.type = expression->binary.left->base.type;
6270
6271         return expression;
6272 end_error:
6273         return create_invalid_expression();
6274 }
6275 #endif
6276
6277 /**
6278  * Parses a MS assume() expression.
6279  */
6280 static expression_t *parse_assume(void)
6281 {
6282         eat(T__assume);
6283
6284         expression_t *expression
6285                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6286
6287         expect('(');
6288         add_anchor_token(')');
6289         expression->unary.value = parse_assignment_expression();
6290         rem_anchor_token(')');
6291         expect(')');
6292
6293         expression->base.type = type_void;
6294         return expression;
6295 end_error:
6296         return create_invalid_expression();
6297 }
6298
6299 /**
6300  * Parse a microsoft __noop expression.
6301  */
6302 static expression_t *parse_noop_expression(void)
6303 {
6304         source_position_t source_position = *HERE;
6305         eat(T___noop);
6306
6307         if (token.type == '(') {
6308                 /* parse arguments */
6309                 eat('(');
6310                 add_anchor_token(')');
6311                 add_anchor_token(',');
6312
6313                 if (token.type != ')') {
6314                         while(true) {
6315                                 (void)parse_assignment_expression();
6316                                 if (token.type != ',')
6317                                         break;
6318                                 next_token();
6319                         }
6320                 }
6321         }
6322         rem_anchor_token(',');
6323         rem_anchor_token(')');
6324         expect(')');
6325
6326         /* the result is a (int)0 */
6327         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
6328         cnst->base.source_position = source_position;
6329         cnst->base.type            = type_int;
6330         cnst->conste.v.int_value   = 0;
6331         cnst->conste.is_ms_noop    = true;
6332
6333         return cnst;
6334
6335 end_error:
6336         return create_invalid_expression();
6337 }
6338
6339 /**
6340  * Parses a primary expression.
6341  */
6342 static expression_t *parse_primary_expression(void)
6343 {
6344         switch (token.type) {
6345                 case T_INTEGER:                  return parse_int_const();
6346                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
6347                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
6348                 case T_FLOATINGPOINT:            return parse_float_const();
6349                 case T_STRING_LITERAL:
6350                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
6351                 case T_IDENTIFIER:               return parse_reference();
6352                 case T___FUNCTION__:
6353                 case T___func__:                 return parse_function_keyword();
6354                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
6355                 case T___FUNCSIG__:              return parse_funcsig_keyword();
6356                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
6357                 case T___builtin_offsetof:       return parse_offsetof();
6358                 case T___builtin_va_start:       return parse_va_start();
6359                 case T___builtin_va_arg:         return parse_va_arg();
6360                 case T___builtin_expect:
6361                 case T___builtin_alloca:
6362                 case T___builtin_nan:
6363                 case T___builtin_nand:
6364                 case T___builtin_nanf:
6365                 case T___builtin_huge_val:
6366                 case T___builtin_va_end:         return parse_builtin_symbol();
6367                 case T___builtin_isgreater:
6368                 case T___builtin_isgreaterequal:
6369                 case T___builtin_isless:
6370                 case T___builtin_islessequal:
6371                 case T___builtin_islessgreater:
6372                 case T___builtin_isunordered:    return parse_compare_builtin();
6373                 case T___builtin_constant_p:     return parse_builtin_constant();
6374                 case T___builtin_prefetch:       return parse_builtin_prefetch();
6375                 case T__assume:                  return parse_assume();
6376
6377                 case '(':                        return parse_brace_expression();
6378                 case T___noop:                   return parse_noop_expression();
6379         }
6380
6381         errorf(HERE, "unexpected token %K, expected an expression", &token);
6382         return create_invalid_expression();
6383 }
6384
6385 /**
6386  * Check if the expression has the character type and issue a warning then.
6387  */
6388 static void check_for_char_index_type(const expression_t *expression)
6389 {
6390         type_t       *const type      = expression->base.type;
6391         const type_t *const base_type = skip_typeref(type);
6392
6393         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6394                         warning.char_subscripts) {
6395                 warningf(&expression->base.source_position,
6396                          "array subscript has type '%T'", type);
6397         }
6398 }
6399
6400 static expression_t *parse_array_expression(unsigned precedence,
6401                                             expression_t *left)
6402 {
6403         (void) precedence;
6404
6405         eat('[');
6406         add_anchor_token(']');
6407
6408         expression_t *inside = parse_expression();
6409
6410         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6411
6412         array_access_expression_t *array_access = &expression->array_access;
6413
6414         type_t *const orig_type_left   = left->base.type;
6415         type_t *const orig_type_inside = inside->base.type;
6416
6417         type_t *const type_left   = skip_typeref(orig_type_left);
6418         type_t *const type_inside = skip_typeref(orig_type_inside);
6419
6420         type_t *return_type;
6421         if (is_type_pointer(type_left)) {
6422                 return_type             = type_left->pointer.points_to;
6423                 array_access->array_ref = left;
6424                 array_access->index     = inside;
6425                 check_for_char_index_type(inside);
6426         } else if (is_type_pointer(type_inside)) {
6427                 return_type             = type_inside->pointer.points_to;
6428                 array_access->array_ref = inside;
6429                 array_access->index     = left;
6430                 array_access->flipped   = true;
6431                 check_for_char_index_type(left);
6432         } else {
6433                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6434                         errorf(HERE,
6435                                 "array access on object with non-pointer types '%T', '%T'",
6436                                 orig_type_left, orig_type_inside);
6437                 }
6438                 return_type             = type_error_type;
6439                 array_access->array_ref = create_invalid_expression();
6440         }
6441
6442         rem_anchor_token(']');
6443         if (token.type != ']') {
6444                 parse_error_expected("Problem while parsing array access", ']', NULL);
6445                 return expression;
6446         }
6447         next_token();
6448
6449         return_type           = automatic_type_conversion(return_type);
6450         expression->base.type = return_type;
6451
6452         return expression;
6453 }
6454
6455 static expression_t *parse_typeprop(expression_kind_t const kind,
6456                                     source_position_t const pos,
6457                                     unsigned const precedence)
6458 {
6459         expression_t *tp_expression = allocate_expression_zero(kind);
6460         tp_expression->base.type            = type_size_t;
6461         tp_expression->base.source_position = pos;
6462
6463         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6464
6465         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6466                 next_token();
6467                 add_anchor_token(')');
6468                 type_t* const orig_type = parse_typename();
6469                 tp_expression->typeprop.type = orig_type;
6470
6471                 type_t const* const type = skip_typeref(orig_type);
6472                 char const* const wrong_type =
6473                         is_type_incomplete(type)    ? "incomplete"          :
6474                         type->kind == TYPE_FUNCTION ? "function designator" :
6475                         type->kind == TYPE_BITFIELD ? "bitfield"            :
6476                         NULL;
6477                 if (wrong_type != NULL) {
6478                         errorf(&pos, "operand of %s expression must not be %s type '%T'",
6479                                what, wrong_type, type);
6480                 }
6481
6482                 rem_anchor_token(')');
6483                 expect(')');
6484         } else {
6485                 expression_t *expression = parse_sub_expression(precedence);
6486
6487                 type_t* const orig_type = revert_automatic_type_conversion(expression);
6488                 expression->base.type = orig_type;
6489
6490                 type_t const* const type = skip_typeref(orig_type);
6491                 char const* const wrong_type =
6492                         is_type_incomplete(type)    ? "incomplete"          :
6493                         type->kind == TYPE_FUNCTION ? "function designator" :
6494                         type->kind == TYPE_BITFIELD ? "bitfield"            :
6495                         NULL;
6496                 if (wrong_type != NULL) {
6497                         errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6498                 }
6499
6500                 tp_expression->typeprop.type          = expression->base.type;
6501                 tp_expression->typeprop.tp_expression = expression;
6502         }
6503
6504         return tp_expression;
6505 end_error:
6506         return create_invalid_expression();
6507 }
6508
6509 static expression_t *parse_sizeof(unsigned precedence)
6510 {
6511         source_position_t pos = *HERE;
6512         eat(T_sizeof);
6513         return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6514 }
6515
6516 static expression_t *parse_alignof(unsigned precedence)
6517 {
6518         source_position_t pos = *HERE;
6519         eat(T___alignof__);
6520         return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6521 }
6522
6523 static expression_t *parse_select_expression(unsigned precedence,
6524                                              expression_t *compound)
6525 {
6526         (void) precedence;
6527         assert(token.type == '.' || token.type == T_MINUSGREATER);
6528
6529         bool is_pointer = (token.type == T_MINUSGREATER);
6530         next_token();
6531
6532         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
6533         select->select.compound = compound;
6534
6535         if (token.type != T_IDENTIFIER) {
6536                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6537                 return select;
6538         }
6539         symbol_t *symbol      = token.v.symbol;
6540         select->select.symbol = symbol;
6541         next_token();
6542
6543         type_t *const orig_type = compound->base.type;
6544         type_t *const type      = skip_typeref(orig_type);
6545
6546         type_t *type_left = type;
6547         if (is_pointer) {
6548                 if (!is_type_pointer(type)) {
6549                         if (is_type_valid(type)) {
6550                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6551                         }
6552                         return create_invalid_expression();
6553                 }
6554                 type_left = type->pointer.points_to;
6555         }
6556         type_left = skip_typeref(type_left);
6557
6558         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6559             type_left->kind != TYPE_COMPOUND_UNION) {
6560                 if (is_type_valid(type_left)) {
6561                         errorf(HERE, "request for member '%Y' in something not a struct or "
6562                                "union, but '%T'", symbol, type_left);
6563                 }
6564                 return create_invalid_expression();
6565         }
6566
6567         declaration_t *const declaration = type_left->compound.declaration;
6568
6569         if (!declaration->init.complete) {
6570                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6571                        symbol, type_left);
6572                 return create_invalid_expression();
6573         }
6574
6575         declaration_t *iter = find_compound_entry(declaration, symbol);
6576         if (iter == NULL) {
6577                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6578                 return create_invalid_expression();
6579         }
6580
6581         /* we always do the auto-type conversions; the & and sizeof parser contains
6582          * code to revert this! */
6583         type_t *expression_type = automatic_type_conversion(iter->type);
6584
6585         select->select.compound_entry = iter;
6586         select->base.type             = expression_type;
6587
6588         type_t *skipped = skip_typeref(iter->type);
6589         if (skipped->kind == TYPE_BITFIELD) {
6590                 select->base.type = skipped->bitfield.base_type;
6591         }
6592
6593         return select;
6594 }
6595
6596 static void check_call_argument(const function_parameter_t *parameter,
6597                                 call_argument_t *argument)
6598 {
6599         type_t         *expected_type      = parameter->type;
6600         type_t         *expected_type_skip = skip_typeref(expected_type);
6601         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
6602         expression_t   *arg_expr           = argument->expression;
6603
6604         /* handle transparent union gnu extension */
6605         if (is_type_union(expected_type_skip)
6606                         && (expected_type_skip->base.modifiers
6607                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6608                 declaration_t  *union_decl = expected_type_skip->compound.declaration;
6609
6610                 declaration_t *declaration = union_decl->scope.declarations;
6611                 type_t        *best_type   = NULL;
6612                 for ( ; declaration != NULL; declaration = declaration->next) {
6613                         type_t *decl_type = declaration->type;
6614                         error = semantic_assign(decl_type, arg_expr);
6615                         if (error == ASSIGN_ERROR_INCOMPATIBLE
6616                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6617                                 continue;
6618
6619                         if (error == ASSIGN_SUCCESS) {
6620                                 best_type = decl_type;
6621                         } else if (best_type == NULL) {
6622                                 best_type = decl_type;
6623                         }
6624                 }
6625
6626                 if (best_type != NULL) {
6627                         expected_type = best_type;
6628                 }
6629         }
6630
6631         error                = semantic_assign(expected_type, arg_expr);
6632         argument->expression = create_implicit_cast(argument->expression,
6633                                                     expected_type);
6634
6635         /* TODO report exact scope in error messages (like "in 3rd parameter") */
6636         report_assign_error(error, expected_type, arg_expr,     "function call",
6637                             &arg_expr->base.source_position);
6638 }
6639
6640 /**
6641  * Parse a call expression, ie. expression '( ... )'.
6642  *
6643  * @param expression  the function address
6644  */
6645 static expression_t *parse_call_expression(unsigned precedence,
6646                                            expression_t *expression)
6647 {
6648         (void) precedence;
6649         expression_t *result = allocate_expression_zero(EXPR_CALL);
6650         result->base.source_position = expression->base.source_position;
6651
6652         call_expression_t *call = &result->call;
6653         call->function          = expression;
6654
6655         type_t *const orig_type = expression->base.type;
6656         type_t *const type      = skip_typeref(orig_type);
6657
6658         function_type_t *function_type = NULL;
6659         if (is_type_pointer(type)) {
6660                 type_t *const to_type = skip_typeref(type->pointer.points_to);
6661
6662                 if (is_type_function(to_type)) {
6663                         function_type   = &to_type->function;
6664                         call->base.type = function_type->return_type;
6665                 }
6666         }
6667
6668         if (function_type == NULL && is_type_valid(type)) {
6669                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6670         }
6671
6672         /* parse arguments */
6673         eat('(');
6674         add_anchor_token(')');
6675         add_anchor_token(',');
6676
6677         if (token.type != ')') {
6678                 call_argument_t *last_argument = NULL;
6679
6680                 while(true) {
6681                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6682
6683                         argument->expression = parse_assignment_expression();
6684                         if (last_argument == NULL) {
6685                                 call->arguments = argument;
6686                         } else {
6687                                 last_argument->next = argument;
6688                         }
6689                         last_argument = argument;
6690
6691                         if (token.type != ',')
6692                                 break;
6693                         next_token();
6694                 }
6695         }
6696         rem_anchor_token(',');
6697         rem_anchor_token(')');
6698         expect(')');
6699
6700         if (function_type == NULL)
6701                 return result;
6702
6703         function_parameter_t *parameter = function_type->parameters;
6704         call_argument_t      *argument  = call->arguments;
6705         if (!function_type->unspecified_parameters) {
6706                 for( ; parameter != NULL && argument != NULL;
6707                                 parameter = parameter->next, argument = argument->next) {
6708                         check_call_argument(parameter, argument);
6709                 }
6710
6711                 if (parameter != NULL) {
6712                         errorf(HERE, "too few arguments to function '%E'", expression);
6713                 } else if (argument != NULL && !function_type->variadic) {
6714                         errorf(HERE, "too many arguments to function '%E'", expression);
6715                 }
6716         }
6717
6718         /* do default promotion */
6719         for( ; argument != NULL; argument = argument->next) {
6720                 type_t *type = argument->expression->base.type;
6721
6722                 type = get_default_promoted_type(type);
6723
6724                 argument->expression
6725                         = create_implicit_cast(argument->expression, type);
6726         }
6727
6728         check_format(&result->call);
6729
6730         return result;
6731 end_error:
6732         return create_invalid_expression();
6733 }
6734
6735 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6736
6737 static bool same_compound_type(const type_t *type1, const type_t *type2)
6738 {
6739         return
6740                 is_type_compound(type1) &&
6741                 type1->kind == type2->kind &&
6742                 type1->compound.declaration == type2->compound.declaration;
6743 }
6744
6745 /**
6746  * Parse a conditional expression, ie. 'expression ? ... : ...'.
6747  *
6748  * @param expression  the conditional expression
6749  */
6750 static expression_t *parse_conditional_expression(unsigned precedence,
6751                                                   expression_t *expression)
6752 {
6753         eat('?');
6754         add_anchor_token(':');
6755
6756         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6757
6758         conditional_expression_t *conditional = &result->conditional;
6759         conditional->condition = expression;
6760
6761         /* 6.5.15.2 */
6762         type_t *const condition_type_orig = expression->base.type;
6763         type_t *const condition_type      = skip_typeref(condition_type_orig);
6764         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6765                 type_error("expected a scalar type in conditional condition",
6766                            &expression->base.source_position, condition_type_orig);
6767         }
6768
6769         expression_t *true_expression = parse_expression();
6770         rem_anchor_token(':');
6771         expect(':');
6772         expression_t *false_expression = parse_sub_expression(precedence);
6773
6774         type_t *const orig_true_type  = true_expression->base.type;
6775         type_t *const orig_false_type = false_expression->base.type;
6776         type_t *const true_type       = skip_typeref(orig_true_type);
6777         type_t *const false_type      = skip_typeref(orig_false_type);
6778
6779         /* 6.5.15.3 */
6780         type_t *result_type;
6781         if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6782                 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6783                 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6784                     || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6785                         warningf(&expression->base.source_position,
6786                                         "ISO C forbids conditional expression with only one void side");
6787                 }
6788                 result_type = type_void;
6789         } else if (is_type_arithmetic(true_type)
6790                    && is_type_arithmetic(false_type)) {
6791                 result_type = semantic_arithmetic(true_type, false_type);
6792
6793                 true_expression  = create_implicit_cast(true_expression, result_type);
6794                 false_expression = create_implicit_cast(false_expression, result_type);
6795
6796                 conditional->true_expression  = true_expression;
6797                 conditional->false_expression = false_expression;
6798                 conditional->base.type        = result_type;
6799         } else if (same_compound_type(true_type, false_type)) {
6800                 /* just take 1 of the 2 types */
6801                 result_type = true_type;
6802         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6803                 type_t *pointer_type;
6804                 type_t *other_type;
6805                 expression_t *other_expression;
6806                 if (is_type_pointer(true_type) &&
6807                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6808                         pointer_type     = true_type;
6809                         other_type       = false_type;
6810                         other_expression = false_expression;
6811                 } else {
6812                         pointer_type     = false_type;
6813                         other_type       = true_type;
6814                         other_expression = true_expression;
6815                 }
6816
6817                 if (is_null_pointer_constant(other_expression)) {
6818                         result_type = pointer_type;
6819                 } else if (is_type_pointer(other_type)) {
6820                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6821                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
6822
6823                         type_t *to;
6824                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6825                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6826                                 to = type_void;
6827                         } else if (types_compatible(get_unqualified_type(to1),
6828                                                     get_unqualified_type(to2))) {
6829                                 to = to1;
6830                         } else {
6831                                 warningf(&expression->base.source_position,
6832                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
6833                                         true_type, false_type);
6834                                 to = type_void;
6835                         }
6836
6837                         type_t *const copy = duplicate_type(to);
6838                         copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6839
6840                         type_t *const type = typehash_insert(copy);
6841                         if (type != copy)
6842                                 free_type(copy);
6843
6844                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6845                 } else if (is_type_integer(other_type)) {
6846                         warningf(&expression->base.source_position,
6847                                         "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6848                         result_type = pointer_type;
6849                 } else {
6850                         type_error_incompatible("while parsing conditional",
6851                                         &expression->base.source_position, true_type, false_type);
6852                         result_type = type_error_type;
6853                 }
6854         } else {
6855                 /* TODO: one pointer to void*, other some pointer */
6856
6857                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6858                         type_error_incompatible("while parsing conditional",
6859                                                 &expression->base.source_position, true_type,
6860                                                 false_type);
6861                 }
6862                 result_type = type_error_type;
6863         }
6864
6865         conditional->true_expression
6866                 = create_implicit_cast(true_expression, result_type);
6867         conditional->false_expression
6868                 = create_implicit_cast(false_expression, result_type);
6869         conditional->base.type = result_type;
6870         return result;
6871 end_error:
6872         return create_invalid_expression();
6873 }
6874
6875 /**
6876  * Parse an extension expression.
6877  */
6878 static expression_t *parse_extension(unsigned precedence)
6879 {
6880         eat(T___extension__);
6881
6882         /* TODO enable extensions */
6883         expression_t *expression = parse_sub_expression(precedence);
6884         /* TODO disable extensions */
6885         return expression;
6886 }
6887
6888 /**
6889  * Parse a __builtin_classify_type() expression.
6890  */
6891 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6892 {
6893         eat(T___builtin_classify_type);
6894
6895         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6896         result->base.type    = type_int;
6897
6898         expect('(');
6899         add_anchor_token(')');
6900         expression_t *expression = parse_sub_expression(precedence);
6901         rem_anchor_token(')');
6902         expect(')');
6903         result->classify_type.type_expression = expression;
6904
6905         return result;
6906 end_error:
6907         return create_invalid_expression();
6908 }
6909
6910 static void check_pointer_arithmetic(const source_position_t *source_position,
6911                                      type_t *pointer_type,
6912                                      type_t *orig_pointer_type)
6913 {
6914         type_t *points_to = pointer_type->pointer.points_to;
6915         points_to = skip_typeref(points_to);
6916
6917         if (is_type_incomplete(points_to) &&
6918                         (! (c_mode & _GNUC)
6919                          || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6920                 errorf(source_position,
6921                            "arithmetic with pointer to incomplete type '%T' not allowed",
6922                            orig_pointer_type);
6923         } else if (is_type_function(points_to)) {
6924                 errorf(source_position,
6925                            "arithmetic with pointer to function type '%T' not allowed",
6926                            orig_pointer_type);
6927         }
6928 }
6929
6930 static void semantic_incdec(unary_expression_t *expression)
6931 {
6932         type_t *const orig_type = expression->value->base.type;
6933         type_t *const type      = skip_typeref(orig_type);
6934         if (is_type_pointer(type)) {
6935                 check_pointer_arithmetic(&expression->base.source_position,
6936                                          type, orig_type);
6937         } else if (!is_type_real(type) && is_type_valid(type)) {
6938                 /* TODO: improve error message */
6939                 errorf(HERE, "operation needs an arithmetic or pointer type");
6940         }
6941         expression->base.type = orig_type;
6942 }
6943
6944 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6945 {
6946         type_t *const orig_type = expression->value->base.type;
6947         type_t *const type      = skip_typeref(orig_type);
6948         if (!is_type_arithmetic(type)) {
6949                 if (is_type_valid(type)) {
6950                         /* TODO: improve error message */
6951                         errorf(HERE, "operation needs an arithmetic type");
6952                 }
6953                 return;
6954         }
6955
6956         expression->base.type = orig_type;
6957 }
6958
6959 static void semantic_unexpr_scalar(unary_expression_t *expression)
6960 {
6961         type_t *const orig_type = expression->value->base.type;
6962         type_t *const type      = skip_typeref(orig_type);
6963         if (!is_type_scalar(type)) {
6964                 if (is_type_valid(type)) {
6965                         errorf(HERE, "operand of ! must be of scalar type");
6966                 }
6967                 return;
6968         }
6969
6970         expression->base.type = orig_type;
6971 }
6972
6973 static void semantic_unexpr_integer(unary_expression_t *expression)
6974 {
6975         type_t *const orig_type = expression->value->base.type;
6976         type_t *const type      = skip_typeref(orig_type);
6977         if (!is_type_integer(type)) {
6978                 if (is_type_valid(type)) {
6979                         errorf(HERE, "operand of ~ must be of integer type");
6980                 }
6981                 return;
6982         }
6983
6984         expression->base.type = orig_type;
6985 }
6986
6987 static void semantic_dereference(unary_expression_t *expression)
6988 {
6989         type_t *const orig_type = expression->value->base.type;
6990         type_t *const type      = skip_typeref(orig_type);
6991         if (!is_type_pointer(type)) {
6992                 if (is_type_valid(type)) {
6993                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6994                 }
6995                 return;
6996         }
6997
6998         type_t *result_type   = type->pointer.points_to;
6999         result_type           = automatic_type_conversion(result_type);
7000         expression->base.type = result_type;
7001 }
7002
7003 static void set_address_taken(expression_t *expression, bool may_be_register)
7004 {
7005         if (expression->kind != EXPR_REFERENCE)
7006                 return;
7007
7008         declaration_t *const declaration = expression->reference.declaration;
7009         /* happens for parse errors */
7010         if (declaration == NULL)
7011                 return;
7012
7013         if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7014                 errorf(&expression->base.source_position,
7015                                 "address of register variable '%Y' requested",
7016                                 declaration->symbol);
7017         } else {
7018                 declaration->address_taken = 1;
7019         }
7020 }
7021
7022 /**
7023  * Check the semantic of the address taken expression.
7024  */
7025 static void semantic_take_addr(unary_expression_t *expression)
7026 {
7027         expression_t *value = expression->value;
7028         value->base.type    = revert_automatic_type_conversion(value);
7029
7030         type_t *orig_type = value->base.type;
7031         if (!is_type_valid(orig_type))
7032                 return;
7033
7034         set_address_taken(value, false);
7035
7036         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7037 }
7038
7039 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
7040 static expression_t *parse_##unexpression_type(unsigned precedence)            \
7041 {                                                                              \
7042         eat(token_type);                                                           \
7043                                                                                    \
7044         expression_t *unary_expression                                             \
7045                 = allocate_expression_zero(unexpression_type);                         \
7046         unary_expression->base.source_position = *HERE;                            \
7047         unary_expression->unary.value = parse_sub_expression(precedence);          \
7048                                                                                    \
7049         sfunc(&unary_expression->unary);                                           \
7050                                                                                    \
7051         return unary_expression;                                                   \
7052 }
7053
7054 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7055                                semantic_unexpr_arithmetic)
7056 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7057                                semantic_unexpr_arithmetic)
7058 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7059                                semantic_unexpr_scalar)
7060 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7061                                semantic_dereference)
7062 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7063                                semantic_take_addr)
7064 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7065                                semantic_unexpr_integer)
7066 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
7067                                semantic_incdec)
7068 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7069                                semantic_incdec)
7070
7071 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7072                                                sfunc)                         \
7073 static expression_t *parse_##unexpression_type(unsigned precedence,           \
7074                                                expression_t *left)            \
7075 {                                                                             \
7076         (void) precedence;                                                        \
7077         eat(token_type);                                                          \
7078                                                                               \
7079         expression_t *unary_expression                                            \
7080                 = allocate_expression_zero(unexpression_type);                        \
7081         unary_expression->unary.value = left;                                     \
7082                                                                                   \
7083         sfunc(&unary_expression->unary);                                          \
7084                                                                               \
7085         return unary_expression;                                                  \
7086 }
7087
7088 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7089                                        EXPR_UNARY_POSTFIX_INCREMENT,
7090                                        semantic_incdec)
7091 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7092                                        EXPR_UNARY_POSTFIX_DECREMENT,
7093                                        semantic_incdec)
7094
7095 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7096 {
7097         /* TODO: handle complex + imaginary types */
7098
7099         /* Â§ 6.3.1.8 Usual arithmetic conversions */
7100         if (type_left == type_long_double || type_right == type_long_double) {
7101                 return type_long_double;
7102         } else if (type_left == type_double || type_right == type_double) {
7103                 return type_double;
7104         } else if (type_left == type_float || type_right == type_float) {
7105                 return type_float;
7106         }
7107
7108         type_left  = promote_integer(type_left);
7109         type_right = promote_integer(type_right);
7110
7111         if (type_left == type_right)
7112                 return type_left;
7113
7114         bool const signed_left  = is_type_signed(type_left);
7115         bool const signed_right = is_type_signed(type_right);
7116         int  const rank_left    = get_rank(type_left);
7117         int  const rank_right   = get_rank(type_right);
7118
7119         if (signed_left == signed_right)
7120                 return rank_left >= rank_right ? type_left : type_right;
7121
7122         int     s_rank;
7123         int     u_rank;
7124         type_t *s_type;
7125         type_t *u_type;
7126         if (signed_left) {
7127                 s_rank = rank_left;
7128                 s_type = type_left;
7129                 u_rank = rank_right;
7130                 u_type = type_right;
7131         } else {
7132                 s_rank = rank_right;
7133                 s_type = type_right;
7134                 u_rank = rank_left;
7135                 u_type = type_left;
7136         }
7137
7138         if (u_rank >= s_rank)
7139                 return u_type;
7140
7141         if (get_atomic_type_size(s_rank) > get_atomic_type_size(u_rank))
7142                 return s_type;
7143
7144         /* FIXME ugly */
7145         type_t *const type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
7146         switch (s_rank) {
7147                 case ATOMIC_TYPE_INT:      type->atomic.akind = ATOMIC_TYPE_UINT;      break;
7148                 case ATOMIC_TYPE_LONG:     type->atomic.akind = ATOMIC_TYPE_ULONG;     break;
7149                 case ATOMIC_TYPE_LONGLONG: type->atomic.akind = ATOMIC_TYPE_ULONGLONG; break;
7150
7151                 default: panic("invalid atomic type");
7152         }
7153
7154         type_t* const result = typehash_insert(type);
7155         if (result != type)
7156                 free_type(type);
7157
7158         return result;
7159 }
7160
7161 /**
7162  * Check the semantic restrictions for a binary expression.
7163  */
7164 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7165 {
7166         expression_t *const left            = expression->left;
7167         expression_t *const right           = expression->right;
7168         type_t       *const orig_type_left  = left->base.type;
7169         type_t       *const orig_type_right = right->base.type;
7170         type_t       *const type_left       = skip_typeref(orig_type_left);
7171         type_t       *const type_right      = skip_typeref(orig_type_right);
7172
7173         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7174                 /* TODO: improve error message */
7175                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7176                         errorf(HERE, "operation needs arithmetic types");
7177                 }
7178                 return;
7179         }
7180
7181         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7182         expression->left      = create_implicit_cast(left, arithmetic_type);
7183         expression->right     = create_implicit_cast(right, arithmetic_type);
7184         expression->base.type = arithmetic_type;
7185 }
7186
7187 static void semantic_shift_op(binary_expression_t *expression)
7188 {
7189         expression_t *const left            = expression->left;
7190         expression_t *const right           = expression->right;
7191         type_t       *const orig_type_left  = left->base.type;
7192         type_t       *const orig_type_right = right->base.type;
7193         type_t       *      type_left       = skip_typeref(orig_type_left);
7194         type_t       *      type_right      = skip_typeref(orig_type_right);
7195
7196         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7197                 /* TODO: improve error message */
7198                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7199                         errorf(HERE, "operation needs integer types");
7200                 }
7201                 return;
7202         }
7203
7204         type_left  = promote_integer(type_left);
7205         type_right = promote_integer(type_right);
7206
7207         expression->left      = create_implicit_cast(left, type_left);
7208         expression->right     = create_implicit_cast(right, type_right);
7209         expression->base.type = type_left;
7210 }
7211
7212 static void semantic_add(binary_expression_t *expression)
7213 {
7214         expression_t *const left            = expression->left;
7215         expression_t *const right           = expression->right;
7216         type_t       *const orig_type_left  = left->base.type;
7217         type_t       *const orig_type_right = right->base.type;
7218         type_t       *const type_left       = skip_typeref(orig_type_left);
7219         type_t       *const type_right      = skip_typeref(orig_type_right);
7220
7221         /* Â§ 6.5.6 */
7222         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
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                 return;
7228         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7229                 check_pointer_arithmetic(&expression->base.source_position,
7230                                          type_left, orig_type_left);
7231                 expression->base.type = type_left;
7232         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7233                 check_pointer_arithmetic(&expression->base.source_position,
7234                                          type_right, orig_type_right);
7235                 expression->base.type = type_right;
7236         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7237                 errorf(&expression->base.source_position,
7238                        "invalid operands to binary + ('%T', '%T')",
7239                        orig_type_left, orig_type_right);
7240         }
7241 }
7242
7243 static void semantic_sub(binary_expression_t *expression)
7244 {
7245         expression_t *const left            = expression->left;
7246         expression_t *const right           = expression->right;
7247         type_t       *const orig_type_left  = left->base.type;
7248         type_t       *const orig_type_right = right->base.type;
7249         type_t       *const type_left       = skip_typeref(orig_type_left);
7250         type_t       *const type_right      = skip_typeref(orig_type_right);
7251
7252         /* Â§ 5.6.5 */
7253         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7254                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7255                 expression->left        = create_implicit_cast(left, arithmetic_type);
7256                 expression->right       = create_implicit_cast(right, arithmetic_type);
7257                 expression->base.type =  arithmetic_type;
7258                 return;
7259         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7260                 check_pointer_arithmetic(&expression->base.source_position,
7261                                          type_left, orig_type_left);
7262                 expression->base.type = type_left;
7263         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7264                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7265                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7266                 if (!types_compatible(unqual_left, unqual_right)) {
7267                         errorf(&expression->base.source_position,
7268                                "subtracting pointers to incompatible types '%T' and '%T'",
7269                                orig_type_left, orig_type_right);
7270                 } else if (!is_type_object(unqual_left)) {
7271                         if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7272                                 warningf(&expression->base.source_position,
7273                                          "subtracting pointers to void");
7274                         } else {
7275                                 errorf(&expression->base.source_position,
7276                                        "subtracting pointers to non-object types '%T'",
7277                                        orig_type_left);
7278                         }
7279                 }
7280                 expression->base.type = type_ptrdiff_t;
7281         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7282                 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
7283                        orig_type_left, orig_type_right);
7284         }
7285 }
7286
7287 /**
7288  * Check the semantics of comparison expressions.
7289  *
7290  * @param expression   The expression to check.
7291  */
7292 static void semantic_comparison(binary_expression_t *expression)
7293 {
7294         expression_t *left            = expression->left;
7295         expression_t *right           = expression->right;
7296         type_t       *orig_type_left  = left->base.type;
7297         type_t       *orig_type_right = right->base.type;
7298
7299         type_t *type_left  = skip_typeref(orig_type_left);
7300         type_t *type_right = skip_typeref(orig_type_right);
7301
7302         /* TODO non-arithmetic types */
7303         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7304                 /* test for signed vs unsigned compares */
7305                 if (warning.sign_compare &&
7306                     (expression->base.kind != EXPR_BINARY_EQUAL &&
7307                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7308                     (is_type_signed(type_left) != is_type_signed(type_right))) {
7309
7310                         /* check if 1 of the operands is a constant, in this case we just
7311                          * check wether we can safely represent the resulting constant in
7312                          * the type of the other operand. */
7313                         expression_t *const_expr = NULL;
7314                         expression_t *other_expr = NULL;
7315
7316                         if (is_constant_expression(left)) {
7317                                 const_expr = left;
7318                                 other_expr = right;
7319                         } else if (is_constant_expression(right)) {
7320                                 const_expr = right;
7321                                 other_expr = left;
7322                         }
7323
7324                         if (const_expr != NULL) {
7325                                 type_t *other_type = skip_typeref(other_expr->base.type);
7326                                 long    val        = fold_constant(const_expr);
7327                                 /* TODO: check if val can be represented by other_type */
7328                                 (void) other_type;
7329                                 (void) val;
7330                         }
7331                         warningf(&expression->base.source_position,
7332                                  "comparison between signed and unsigned");
7333                 }
7334                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7335                 expression->left        = create_implicit_cast(left, arithmetic_type);
7336                 expression->right       = create_implicit_cast(right, arithmetic_type);
7337                 expression->base.type   = arithmetic_type;
7338                 if (warning.float_equal &&
7339                     (expression->base.kind == EXPR_BINARY_EQUAL ||
7340                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7341                     is_type_float(arithmetic_type)) {
7342                         warningf(&expression->base.source_position,
7343                                  "comparing floating point with == or != is unsafe");
7344                 }
7345         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7346                 /* TODO check compatibility */
7347         } else if (is_type_pointer(type_left)) {
7348                 expression->right = create_implicit_cast(right, type_left);
7349         } else if (is_type_pointer(type_right)) {
7350                 expression->left = create_implicit_cast(left, type_right);
7351         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7352                 type_error_incompatible("invalid operands in comparison",
7353                                         &expression->base.source_position,
7354                                         type_left, type_right);
7355         }
7356         expression->base.type = type_int;
7357 }
7358
7359 /**
7360  * Checks if a compound type has constant fields.
7361  */
7362 static bool has_const_fields(const compound_type_t *type)
7363 {
7364         const scope_t       *scope       = &type->declaration->scope;
7365         const declaration_t *declaration = scope->declarations;
7366
7367         for (; declaration != NULL; declaration = declaration->next) {
7368                 if (declaration->namespc != NAMESPACE_NORMAL)
7369                         continue;
7370
7371                 const type_t *decl_type = skip_typeref(declaration->type);
7372                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7373                         return true;
7374         }
7375         /* TODO */
7376         return false;
7377 }
7378
7379 static bool is_lvalue(const expression_t *expression)
7380 {
7381         switch (expression->kind) {
7382         case EXPR_REFERENCE:
7383         case EXPR_ARRAY_ACCESS:
7384         case EXPR_SELECT:
7385         case EXPR_UNARY_DEREFERENCE:
7386                 return true;
7387
7388         default:
7389                 return false;
7390         }
7391 }
7392
7393 static bool is_valid_assignment_lhs(expression_t const* const left)
7394 {
7395         type_t *const orig_type_left = revert_automatic_type_conversion(left);
7396         type_t *const type_left      = skip_typeref(orig_type_left);
7397
7398         if (!is_lvalue(left)) {
7399                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7400                        left);
7401                 return false;
7402         }
7403
7404         if (is_type_array(type_left)) {
7405                 errorf(HERE, "cannot assign to arrays ('%E')", left);
7406                 return false;
7407         }
7408         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7409                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7410                        orig_type_left);
7411                 return false;
7412         }
7413         if (is_type_incomplete(type_left)) {
7414                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7415                        left, orig_type_left);
7416                 return false;
7417         }
7418         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7419                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7420                        left, orig_type_left);
7421                 return false;
7422         }
7423
7424         return true;
7425 }
7426
7427 static void semantic_arithmetic_assign(binary_expression_t *expression)
7428 {
7429         expression_t *left            = expression->left;
7430         expression_t *right           = expression->right;
7431         type_t       *orig_type_left  = left->base.type;
7432         type_t       *orig_type_right = right->base.type;
7433
7434         if (!is_valid_assignment_lhs(left))
7435                 return;
7436
7437         type_t *type_left  = skip_typeref(orig_type_left);
7438         type_t *type_right = skip_typeref(orig_type_right);
7439
7440         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7441                 /* TODO: improve error message */
7442                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7443                         errorf(HERE, "operation needs arithmetic types");
7444                 }
7445                 return;
7446         }
7447
7448         /* combined instructions are tricky. We can't create an implicit cast on
7449          * the left side, because we need the uncasted form for the store.
7450          * The ast2firm pass has to know that left_type must be right_type
7451          * for the arithmetic operation and create a cast by itself */
7452         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7453         expression->right       = create_implicit_cast(right, arithmetic_type);
7454         expression->base.type   = type_left;
7455 }
7456
7457 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7458 {
7459         expression_t *const left            = expression->left;
7460         expression_t *const right           = expression->right;
7461         type_t       *const orig_type_left  = left->base.type;
7462         type_t       *const orig_type_right = right->base.type;
7463         type_t       *const type_left       = skip_typeref(orig_type_left);
7464         type_t       *const type_right      = skip_typeref(orig_type_right);
7465
7466         if (!is_valid_assignment_lhs(left))
7467                 return;
7468
7469         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7470                 /* combined instructions are tricky. We can't create an implicit cast on
7471                  * the left side, because we need the uncasted form for the store.
7472                  * The ast2firm pass has to know that left_type must be right_type
7473                  * for the arithmetic operation and create a cast by itself */
7474                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7475                 expression->right     = create_implicit_cast(right, arithmetic_type);
7476                 expression->base.type = type_left;
7477         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7478                 check_pointer_arithmetic(&expression->base.source_position,
7479                                          type_left, orig_type_left);
7480                 expression->base.type = type_left;
7481         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7482                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
7483         }
7484 }
7485
7486 /**
7487  * Check the semantic restrictions of a logical expression.
7488  */
7489 static void semantic_logical_op(binary_expression_t *expression)
7490 {
7491         expression_t *const left            = expression->left;
7492         expression_t *const right           = expression->right;
7493         type_t       *const orig_type_left  = left->base.type;
7494         type_t       *const orig_type_right = right->base.type;
7495         type_t       *const type_left       = skip_typeref(orig_type_left);
7496         type_t       *const type_right      = skip_typeref(orig_type_right);
7497
7498         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7499                 /* TODO: improve error message */
7500                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7501                         errorf(HERE, "operation needs scalar types");
7502                 }
7503                 return;
7504         }
7505
7506         expression->base.type = type_int;
7507 }
7508
7509 /**
7510  * Check the semantic restrictions of a binary assign expression.
7511  */
7512 static void semantic_binexpr_assign(binary_expression_t *expression)
7513 {
7514         expression_t *left           = expression->left;
7515         type_t       *orig_type_left = left->base.type;
7516
7517         type_t *type_left = revert_automatic_type_conversion(left);
7518         type_left         = skip_typeref(orig_type_left);
7519
7520         if (!is_valid_assignment_lhs(left))
7521                 return;
7522
7523         assign_error_t error = semantic_assign(orig_type_left, expression->right);
7524         report_assign_error(error, orig_type_left, expression->right,
7525                         "assignment", &left->base.source_position);
7526         expression->right = create_implicit_cast(expression->right, orig_type_left);
7527         expression->base.type = orig_type_left;
7528 }
7529
7530 /**
7531  * Determine if the outermost operation (or parts thereof) of the given
7532  * expression has no effect in order to generate a warning about this fact.
7533  * Therefore in some cases this only examines some of the operands of the
7534  * expression (see comments in the function and examples below).
7535  * Examples:
7536  *   f() + 23;    // warning, because + has no effect
7537  *   x || f();    // no warning, because x controls execution of f()
7538  *   x ? y : f(); // warning, because y has no effect
7539  *   (void)x;     // no warning to be able to suppress the warning
7540  * This function can NOT be used for an "expression has definitely no effect"-
7541  * analysis. */
7542 static bool expression_has_effect(const expression_t *const expr)
7543 {
7544         switch (expr->kind) {
7545                 case EXPR_UNKNOWN:                   break;
7546                 case EXPR_INVALID:                   return true; /* do NOT warn */
7547                 case EXPR_REFERENCE:                 return false;
7548                 /* suppress the warning for microsoft __noop operations */
7549                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
7550                 case EXPR_CHARACTER_CONSTANT:        return false;
7551                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
7552                 case EXPR_STRING_LITERAL:            return false;
7553                 case EXPR_WIDE_STRING_LITERAL:       return false;
7554
7555                 case EXPR_CALL: {
7556                         const call_expression_t *const call = &expr->call;
7557                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7558                                 return true;
7559
7560                         switch (call->function->builtin_symbol.symbol->ID) {
7561                                 case T___builtin_va_end: return true;
7562                                 default:                 return false;
7563                         }
7564                 }
7565
7566                 /* Generate the warning if either the left or right hand side of a
7567                  * conditional expression has no effect */
7568                 case EXPR_CONDITIONAL: {
7569                         const conditional_expression_t *const cond = &expr->conditional;
7570                         return
7571                                 expression_has_effect(cond->true_expression) &&
7572                                 expression_has_effect(cond->false_expression);
7573                 }
7574
7575                 case EXPR_SELECT:                    return false;
7576                 case EXPR_ARRAY_ACCESS:              return false;
7577                 case EXPR_SIZEOF:                    return false;
7578                 case EXPR_CLASSIFY_TYPE:             return false;
7579                 case EXPR_ALIGNOF:                   return false;
7580
7581                 case EXPR_FUNCNAME:                  return false;
7582                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
7583                 case EXPR_BUILTIN_CONSTANT_P:        return false;
7584                 case EXPR_BUILTIN_PREFETCH:          return true;
7585                 case EXPR_OFFSETOF:                  return false;
7586                 case EXPR_VA_START:                  return true;
7587                 case EXPR_VA_ARG:                    return true;
7588                 case EXPR_STATEMENT:                 return true; // TODO
7589                 case EXPR_COMPOUND_LITERAL:          return false;
7590
7591                 case EXPR_UNARY_NEGATE:              return false;
7592                 case EXPR_UNARY_PLUS:                return false;
7593                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
7594                 case EXPR_UNARY_NOT:                 return false;
7595                 case EXPR_UNARY_DEREFERENCE:         return false;
7596                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
7597                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
7598                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
7599                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
7600                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
7601
7602                 /* Treat void casts as if they have an effect in order to being able to
7603                  * suppress the warning */
7604                 case EXPR_UNARY_CAST: {
7605                         type_t *const type = skip_typeref(expr->base.type);
7606                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
7607                 }
7608
7609                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
7610                 case EXPR_UNARY_ASSUME:              return true;
7611
7612                 case EXPR_BINARY_ADD:                return false;
7613                 case EXPR_BINARY_SUB:                return false;
7614                 case EXPR_BINARY_MUL:                return false;
7615                 case EXPR_BINARY_DIV:                return false;
7616                 case EXPR_BINARY_MOD:                return false;
7617                 case EXPR_BINARY_EQUAL:              return false;
7618                 case EXPR_BINARY_NOTEQUAL:           return false;
7619                 case EXPR_BINARY_LESS:               return false;
7620                 case EXPR_BINARY_LESSEQUAL:          return false;
7621                 case EXPR_BINARY_GREATER:            return false;
7622                 case EXPR_BINARY_GREATEREQUAL:       return false;
7623                 case EXPR_BINARY_BITWISE_AND:        return false;
7624                 case EXPR_BINARY_BITWISE_OR:         return false;
7625                 case EXPR_BINARY_BITWISE_XOR:        return false;
7626                 case EXPR_BINARY_SHIFTLEFT:          return false;
7627                 case EXPR_BINARY_SHIFTRIGHT:         return false;
7628                 case EXPR_BINARY_ASSIGN:             return true;
7629                 case EXPR_BINARY_MUL_ASSIGN:         return true;
7630                 case EXPR_BINARY_DIV_ASSIGN:         return true;
7631                 case EXPR_BINARY_MOD_ASSIGN:         return true;
7632                 case EXPR_BINARY_ADD_ASSIGN:         return true;
7633                 case EXPR_BINARY_SUB_ASSIGN:         return true;
7634                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
7635                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
7636                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7637                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7638                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
7639
7640                 /* Only examine the right hand side of && and ||, because the left hand
7641                  * side already has the effect of controlling the execution of the right
7642                  * hand side */
7643                 case EXPR_BINARY_LOGICAL_AND:
7644                 case EXPR_BINARY_LOGICAL_OR:
7645                 /* Only examine the right hand side of a comma expression, because the left
7646                  * hand side has a separate warning */
7647                 case EXPR_BINARY_COMMA:
7648                         return expression_has_effect(expr->binary.right);
7649
7650                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
7651                 case EXPR_BINARY_ISGREATER:          return false;
7652                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
7653                 case EXPR_BINARY_ISLESS:             return false;
7654                 case EXPR_BINARY_ISLESSEQUAL:        return false;
7655                 case EXPR_BINARY_ISLESSGREATER:      return false;
7656                 case EXPR_BINARY_ISUNORDERED:        return false;
7657         }
7658
7659         internal_errorf(HERE, "unexpected expression");
7660 }
7661
7662 static void semantic_comma(binary_expression_t *expression)
7663 {
7664         if (warning.unused_value) {
7665                 const expression_t *const left = expression->left;
7666                 if (!expression_has_effect(left)) {
7667                         warningf(&left->base.source_position,
7668                                  "left-hand operand of comma expression has no effect");
7669                 }
7670         }
7671         expression->base.type = expression->right->base.type;
7672 }
7673
7674 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
7675 static expression_t *parse_##binexpression_type(unsigned precedence,      \
7676                                                 expression_t *left)       \
7677 {                                                                         \
7678         eat(token_type);                                                      \
7679         source_position_t pos = *HERE;                                        \
7680                                                                           \
7681         expression_t *right = parse_sub_expression(precedence + lr);          \
7682                                                                           \
7683         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7684         binexpr->base.source_position = pos;                                  \
7685         binexpr->binary.left  = left;                                         \
7686         binexpr->binary.right = right;                                        \
7687         sfunc(&binexpr->binary);                                              \
7688                                                                           \
7689         return binexpr;                                                       \
7690 }
7691
7692 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
7693 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
7694 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
7695 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
7696 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
7697 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
7698 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
7699 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
7700 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
7701
7702 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
7703                       semantic_comparison, 1)
7704 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7705                       semantic_comparison, 1)
7706 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
7707                       semantic_comparison, 1)
7708 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
7709                       semantic_comparison, 1)
7710
7711 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7712                       semantic_binexpr_arithmetic, 1)
7713 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7714                       semantic_binexpr_arithmetic, 1)
7715 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7716                       semantic_binexpr_arithmetic, 1)
7717 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7718                       semantic_logical_op, 1)
7719 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7720                       semantic_logical_op, 1)
7721 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7722                       semantic_shift_op, 1)
7723 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7724                       semantic_shift_op, 1)
7725 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7726                       semantic_arithmetic_addsubb_assign, 0)
7727 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7728                       semantic_arithmetic_addsubb_assign, 0)
7729 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7730                       semantic_arithmetic_assign, 0)
7731 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7732                       semantic_arithmetic_assign, 0)
7733 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7734                       semantic_arithmetic_assign, 0)
7735 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7736                       semantic_arithmetic_assign, 0)
7737 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7738                       semantic_arithmetic_assign, 0)
7739 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7740                       semantic_arithmetic_assign, 0)
7741 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7742                       semantic_arithmetic_assign, 0)
7743 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7744                       semantic_arithmetic_assign, 0)
7745
7746 static expression_t *parse_sub_expression(unsigned precedence)
7747 {
7748         if (token.type < 0) {
7749                 return expected_expression_error();
7750         }
7751
7752         expression_parser_function_t *parser
7753                 = &expression_parsers[token.type];
7754         source_position_t             source_position = token.source_position;
7755         expression_t                 *left;
7756
7757         if (parser->parser != NULL) {
7758                 left = parser->parser(parser->precedence);
7759         } else {
7760                 left = parse_primary_expression();
7761         }
7762         assert(left != NULL);
7763         left->base.source_position = source_position;
7764
7765         while(true) {
7766                 if (token.type < 0) {
7767                         return expected_expression_error();
7768                 }
7769
7770                 parser = &expression_parsers[token.type];
7771                 if (parser->infix_parser == NULL)
7772                         break;
7773                 if (parser->infix_precedence < precedence)
7774                         break;
7775
7776                 left = parser->infix_parser(parser->infix_precedence, left);
7777
7778                 assert(left != NULL);
7779                 assert(left->kind != EXPR_UNKNOWN);
7780                 left->base.source_position = source_position;
7781         }
7782
7783         return left;
7784 }
7785
7786 /**
7787  * Parse an expression.
7788  */
7789 static expression_t *parse_expression(void)
7790 {
7791         return parse_sub_expression(1);
7792 }
7793
7794 /**
7795  * Register a parser for a prefix-like operator with given precedence.
7796  *
7797  * @param parser      the parser function
7798  * @param token_type  the token type of the prefix token
7799  * @param precedence  the precedence of the operator
7800  */
7801 static void register_expression_parser(parse_expression_function parser,
7802                                        int token_type, unsigned precedence)
7803 {
7804         expression_parser_function_t *entry = &expression_parsers[token_type];
7805
7806         if (entry->parser != NULL) {
7807                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7808                 panic("trying to register multiple expression parsers for a token");
7809         }
7810         entry->parser     = parser;
7811         entry->precedence = precedence;
7812 }
7813
7814 /**
7815  * Register a parser for an infix operator with given precedence.
7816  *
7817  * @param parser      the parser function
7818  * @param token_type  the token type of the infix operator
7819  * @param precedence  the precedence of the operator
7820  */
7821 static void register_infix_parser(parse_expression_infix_function parser,
7822                 int token_type, unsigned precedence)
7823 {
7824         expression_parser_function_t *entry = &expression_parsers[token_type];
7825
7826         if (entry->infix_parser != NULL) {
7827                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7828                 panic("trying to register multiple infix expression parsers for a "
7829                       "token");
7830         }
7831         entry->infix_parser     = parser;
7832         entry->infix_precedence = precedence;
7833 }
7834
7835 /**
7836  * Initialize the expression parsers.
7837  */
7838 static void init_expression_parsers(void)
7839 {
7840         memset(&expression_parsers, 0, sizeof(expression_parsers));
7841
7842         register_infix_parser(parse_array_expression,         '[',              30);
7843         register_infix_parser(parse_call_expression,          '(',              30);
7844         register_infix_parser(parse_select_expression,        '.',              30);
7845         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
7846         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7847                                                               T_PLUSPLUS,       30);
7848         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7849                                                               T_MINUSMINUS,     30);
7850
7851         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              17);
7852         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              17);
7853         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              17);
7854         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              16);
7855         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              16);
7856         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       15);
7857         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 15);
7858         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
7859         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
7860         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
7861         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
7862         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
7863         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7864                                                     T_EXCLAMATIONMARKEQUAL, 13);
7865         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
7866         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
7867         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
7868         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
7869         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
7870         register_infix_parser(parse_conditional_expression,   '?',               7);
7871         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
7872         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
7873         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
7874         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
7875         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
7876         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
7877         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7878                                                                 T_LESSLESSEQUAL, 2);
7879         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7880                                                           T_GREATERGREATEREQUAL, 2);
7881         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7882                                                                      T_ANDEQUAL, 2);
7883         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7884                                                                     T_PIPEEQUAL, 2);
7885         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7886                                                                    T_CARETEQUAL, 2);
7887
7888         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
7889
7890         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
7891         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
7892         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
7893         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
7894         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
7895         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
7896         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7897                                                                   T_PLUSPLUS,   25);
7898         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7899                                                                   T_MINUSMINUS, 25);
7900         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
7901         register_expression_parser(parse_alignof,                T___alignof__, 25);
7902         register_expression_parser(parse_extension,            T___extension__, 25);
7903         register_expression_parser(parse_builtin_classify_type,
7904                                                      T___builtin_classify_type, 25);
7905 }
7906
7907 /**
7908  * Parse a asm statement arguments specification.
7909  */
7910 static asm_argument_t *parse_asm_arguments(bool is_out)
7911 {
7912         asm_argument_t *result = NULL;
7913         asm_argument_t *last   = NULL;
7914
7915         while (token.type == T_STRING_LITERAL || token.type == '[') {
7916                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7917                 memset(argument, 0, sizeof(argument[0]));
7918
7919                 if (token.type == '[') {
7920                         eat('[');
7921                         if (token.type != T_IDENTIFIER) {
7922                                 parse_error_expected("while parsing asm argument",
7923                                                      T_IDENTIFIER, NULL);
7924                                 return NULL;
7925                         }
7926                         argument->symbol = token.v.symbol;
7927
7928                         expect(']');
7929                 }
7930
7931                 argument->constraints = parse_string_literals();
7932                 expect('(');
7933                 add_anchor_token(')');
7934                 expression_t *expression = parse_expression();
7935                 rem_anchor_token(')');
7936                 if (is_out) {
7937                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
7938                          * change size or type representation (e.g. int -> long is ok, but
7939                          * int -> float is not) */
7940                         if (expression->kind == EXPR_UNARY_CAST) {
7941                                 type_t      *const type = expression->base.type;
7942                                 type_kind_t  const kind = type->kind;
7943                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
7944                                         unsigned flags;
7945                                         unsigned size;
7946                                         if (kind == TYPE_ATOMIC) {
7947                                                 atomic_type_kind_t const akind = type->atomic.akind;
7948                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
7949                                                 size  = get_atomic_type_size(akind);
7950                                         } else {
7951                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
7952                                                 size  = get_atomic_type_size(get_intptr_kind());
7953                                         }
7954
7955                                         do {
7956                                                 expression_t *const value      = expression->unary.value;
7957                                                 type_t       *const value_type = value->base.type;
7958                                                 type_kind_t   const value_kind = value_type->kind;
7959
7960                                                 unsigned value_flags;
7961                                                 unsigned value_size;
7962                                                 if (value_kind == TYPE_ATOMIC) {
7963                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
7964                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
7965                                                         value_size  = get_atomic_type_size(value_akind);
7966                                                 } else if (value_kind == TYPE_POINTER) {
7967                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
7968                                                         value_size  = get_atomic_type_size(get_intptr_kind());
7969                                                 } else {
7970                                                         break;
7971                                                 }
7972
7973                                                 if (value_flags != flags || value_size != size)
7974                                                         break;
7975
7976                                                 expression = value;
7977                                         } while (expression->kind == EXPR_UNARY_CAST);
7978                                 }
7979                         }
7980
7981                         if (!is_lvalue(expression)) {
7982                                 errorf(&expression->base.source_position,
7983                                        "asm output argument is not an lvalue");
7984                         }
7985                 }
7986                 argument->expression = expression;
7987                 expect(')');
7988
7989                 set_address_taken(expression, true);
7990
7991                 if (last != NULL) {
7992                         last->next = argument;
7993                 } else {
7994                         result = argument;
7995                 }
7996                 last = argument;
7997
7998                 if (token.type != ',')
7999                         break;
8000                 eat(',');
8001         }
8002
8003         return result;
8004 end_error:
8005         return NULL;
8006 }
8007
8008 /**
8009  * Parse a asm statement clobber specification.
8010  */
8011 static asm_clobber_t *parse_asm_clobbers(void)
8012 {
8013         asm_clobber_t *result = NULL;
8014         asm_clobber_t *last   = NULL;
8015
8016         while(token.type == T_STRING_LITERAL) {
8017                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8018                 clobber->clobber       = parse_string_literals();
8019
8020                 if (last != NULL) {
8021                         last->next = clobber;
8022                 } else {
8023                         result = clobber;
8024                 }
8025                 last = clobber;
8026
8027                 if (token.type != ',')
8028                         break;
8029                 eat(',');
8030         }
8031
8032         return result;
8033 }
8034
8035 /**
8036  * Parse an asm statement.
8037  */
8038 static statement_t *parse_asm_statement(void)
8039 {
8040         eat(T_asm);
8041
8042         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
8043         statement->base.source_position = token.source_position;
8044
8045         asm_statement_t *asm_statement = &statement->asms;
8046
8047         if (token.type == T_volatile) {
8048                 next_token();
8049                 asm_statement->is_volatile = true;
8050         }
8051
8052         expect('(');
8053         add_anchor_token(')');
8054         add_anchor_token(':');
8055         asm_statement->asm_text = parse_string_literals();
8056
8057         if (token.type != ':') {
8058                 rem_anchor_token(':');
8059                 goto end_of_asm;
8060         }
8061         eat(':');
8062
8063         asm_statement->outputs = parse_asm_arguments(true);
8064         if (token.type != ':') {
8065                 rem_anchor_token(':');
8066                 goto end_of_asm;
8067         }
8068         eat(':');
8069
8070         asm_statement->inputs = parse_asm_arguments(false);
8071         if (token.type != ':') {
8072                 rem_anchor_token(':');
8073                 goto end_of_asm;
8074         }
8075         rem_anchor_token(':');
8076         eat(':');
8077
8078         asm_statement->clobbers = parse_asm_clobbers();
8079
8080 end_of_asm:
8081         rem_anchor_token(')');
8082         expect(')');
8083         expect(';');
8084
8085         if (asm_statement->outputs == NULL) {
8086                 /* GCC: An 'asm' instruction without any output operands will be treated
8087                  * identically to a volatile 'asm' instruction. */
8088                 asm_statement->is_volatile = true;
8089         }
8090
8091         return statement;
8092 end_error:
8093         return create_invalid_statement();
8094 }
8095
8096 /**
8097  * Parse a case statement.
8098  */
8099 static statement_t *parse_case_statement(void)
8100 {
8101         eat(T_case);
8102
8103         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8104         source_position_t *const pos       = &statement->base.source_position;
8105
8106         *pos                             = token.source_position;
8107         statement->case_label.expression = parse_expression();
8108
8109         PUSH_PARENT(statement);
8110
8111         if (c_mode & _GNUC) {
8112                 if (token.type == T_DOTDOTDOT) {
8113                         next_token();
8114                         statement->case_label.end_range = parse_expression();
8115                 }
8116         }
8117
8118         expect(':');
8119
8120         if (! is_constant_expression(statement->case_label.expression)) {
8121                 errorf(pos, "case label does not reduce to an integer constant");
8122         } else if (current_switch != NULL) {
8123                 /* Check for duplicate case values */
8124                 /* FIXME slow */
8125                 long const val = fold_constant(statement->case_label.expression);
8126                 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8127                         expression_t const* const e = l->expression;
8128                         if (e == NULL || !is_constant_expression(e) || fold_constant(e) != val)
8129                                 continue;
8130
8131                         errorf(pos, "duplicate case value");
8132                         errorf(&l->base.source_position, "previously used here");
8133                         break;
8134                 }
8135
8136                 /* link all cases into the switch statement */
8137                 if (current_switch->last_case == NULL) {
8138                         current_switch->first_case      = &statement->case_label;
8139                 } else {
8140                         current_switch->last_case->next = &statement->case_label;
8141                 }
8142                 current_switch->last_case = &statement->case_label;
8143         } else {
8144                 errorf(pos, "case label not within a switch statement");
8145         }
8146
8147         statement_t *const inner_stmt = parse_statement();
8148         statement->case_label.statement = inner_stmt;
8149         if (inner_stmt->kind == STATEMENT_DECLARATION) {
8150                 errorf(&inner_stmt->base.source_position, "declaration after case label");
8151         }
8152
8153         POP_PARENT;
8154         return statement;
8155 end_error:
8156         POP_PARENT;
8157         return create_invalid_statement();
8158 }
8159
8160 /**
8161  * Finds an existing default label of a switch statement.
8162  */
8163 static case_label_statement_t *
8164 find_default_label(const switch_statement_t *statement)
8165 {
8166         case_label_statement_t *label = statement->first_case;
8167         for ( ; label != NULL; label = label->next) {
8168                 if (label->expression == NULL)
8169                         return label;
8170         }
8171         return NULL;
8172 }
8173
8174 /**
8175  * Parse a default statement.
8176  */
8177 static statement_t *parse_default_statement(void)
8178 {
8179         eat(T_default);
8180
8181         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8182         statement->base.source_position = token.source_position;
8183
8184         PUSH_PARENT(statement);
8185
8186         expect(':');
8187         if (current_switch != NULL) {
8188                 const case_label_statement_t *def_label = find_default_label(current_switch);
8189                 if (def_label != NULL) {
8190                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8191                                &def_label->base.source_position);
8192                 } else {
8193                         /* link all cases into the switch statement */
8194                         if (current_switch->last_case == NULL) {
8195                                 current_switch->first_case      = &statement->case_label;
8196                         } else {
8197                                 current_switch->last_case->next = &statement->case_label;
8198                         }
8199                         current_switch->last_case = &statement->case_label;
8200                 }
8201         } else {
8202                 errorf(&statement->base.source_position,
8203                         "'default' label not within a switch statement");
8204         }
8205
8206         statement_t *const inner_stmt = parse_statement();
8207         statement->case_label.statement = inner_stmt;
8208         if (inner_stmt->kind == STATEMENT_DECLARATION) {
8209                 errorf(&inner_stmt->base.source_position, "declaration after default label");
8210         }
8211
8212         POP_PARENT;
8213         return statement;
8214 end_error:
8215         POP_PARENT;
8216         return create_invalid_statement();
8217 }
8218
8219 /**
8220  * Return the declaration for a given label symbol or create a new one.
8221  *
8222  * @param symbol  the symbol of the label
8223  */
8224 static declaration_t *get_label(symbol_t *symbol)
8225 {
8226         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
8227         assert(current_function != NULL);
8228         /* if we found a label in the same function, then we already created the
8229          * declaration */
8230         if (candidate != NULL
8231                         && candidate->parent_scope == &current_function->scope) {
8232                 return candidate;
8233         }
8234
8235         /* otherwise we need to create a new one */
8236         declaration_t *const declaration = allocate_declaration_zero();
8237         declaration->namespc       = NAMESPACE_LABEL;
8238         declaration->symbol        = symbol;
8239
8240         label_push(declaration);
8241
8242         return declaration;
8243 }
8244
8245 /**
8246  * Parse a label statement.
8247  */
8248 static statement_t *parse_label_statement(void)
8249 {
8250         assert(token.type == T_IDENTIFIER);
8251         symbol_t *symbol = token.v.symbol;
8252         next_token();
8253
8254         declaration_t *label = get_label(symbol);
8255
8256         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8257         statement->base.source_position = token.source_position;
8258         statement->label.label          = label;
8259
8260         PUSH_PARENT(statement);
8261
8262         /* if source position is already set then the label is defined twice,
8263          * otherwise it was just mentioned in a goto so far */
8264         if (label->source_position.input_name != NULL) {
8265                 errorf(HERE, "duplicate label '%Y' (declared %P)",
8266                        symbol, &label->source_position);
8267         } else {
8268                 label->source_position = token.source_position;
8269                 label->init.statement  = statement;
8270         }
8271
8272         eat(':');
8273
8274         if (token.type == '}') {
8275                 /* TODO only warn? */
8276                 if (false) {
8277                         warningf(HERE, "label at end of compound statement");
8278                         statement->label.statement = create_empty_statement();
8279                 } else {
8280                         errorf(HERE, "label at end of compound statement");
8281                         statement->label.statement = create_invalid_statement();
8282                 }
8283         } else if (token.type == ';') {
8284                 /* Eat an empty statement here, to avoid the warning about an empty
8285                  * statement after a label.  label:; is commonly used to have a label
8286                  * before a closing brace. */
8287                 statement->label.statement = create_empty_statement();
8288                 next_token();
8289         } else {
8290                 statement_t *const inner_stmt = parse_statement();
8291                 statement->label.statement = inner_stmt;
8292                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8293                         errorf(&inner_stmt->base.source_position, "declaration after label");
8294                 }
8295         }
8296
8297         /* remember the labels in a list for later checking */
8298         if (label_last == NULL) {
8299                 label_first = &statement->label;
8300         } else {
8301                 label_last->next = &statement->label;
8302         }
8303         label_last = &statement->label;
8304
8305         POP_PARENT;
8306         return statement;
8307 }
8308
8309 /**
8310  * Parse an if statement.
8311  */
8312 static statement_t *parse_if(void)
8313 {
8314         eat(T_if);
8315
8316         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
8317         statement->base.source_position = token.source_position;
8318
8319         PUSH_PARENT(statement);
8320
8321         expect('(');
8322         add_anchor_token(')');
8323         statement->ifs.condition = parse_expression();
8324         rem_anchor_token(')');
8325         expect(')');
8326
8327         add_anchor_token(T_else);
8328         statement->ifs.true_statement = parse_statement();
8329         rem_anchor_token(T_else);
8330
8331         if (token.type == T_else) {
8332                 next_token();
8333                 statement->ifs.false_statement = parse_statement();
8334         }
8335
8336         POP_PARENT;
8337         return statement;
8338 end_error:
8339         POP_PARENT;
8340         return create_invalid_statement();
8341 }
8342
8343 /**
8344  * Parse a switch statement.
8345  */
8346 static statement_t *parse_switch(void)
8347 {
8348         eat(T_switch);
8349
8350         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
8351         statement->base.source_position = token.source_position;
8352
8353         PUSH_PARENT(statement);
8354
8355         expect('(');
8356         expression_t *const expr = parse_expression();
8357         type_t       *      type = skip_typeref(expr->base.type);
8358         if (is_type_integer(type)) {
8359                 type = promote_integer(type);
8360         } else if (is_type_valid(type)) {
8361                 errorf(&expr->base.source_position,
8362                        "switch quantity is not an integer, but '%T'", type);
8363                 type = type_error_type;
8364         }
8365         statement->switchs.expression = create_implicit_cast(expr, type);
8366         expect(')');
8367
8368         switch_statement_t *rem = current_switch;
8369         current_switch          = &statement->switchs;
8370         statement->switchs.body = parse_statement();
8371         current_switch          = rem;
8372
8373         if (warning.switch_default &&
8374            find_default_label(&statement->switchs) == NULL) {
8375                 warningf(&statement->base.source_position, "switch has no default case");
8376         }
8377
8378         POP_PARENT;
8379         return statement;
8380 end_error:
8381         POP_PARENT;
8382         return create_invalid_statement();
8383 }
8384
8385 static statement_t *parse_loop_body(statement_t *const loop)
8386 {
8387         statement_t *const rem = current_loop;
8388         current_loop = loop;
8389
8390         statement_t *const body = parse_statement();
8391
8392         current_loop = rem;
8393         return body;
8394 }
8395
8396 /**
8397  * Parse a while statement.
8398  */
8399 static statement_t *parse_while(void)
8400 {
8401         eat(T_while);
8402
8403         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
8404         statement->base.source_position = token.source_position;
8405
8406         PUSH_PARENT(statement);
8407
8408         expect('(');
8409         add_anchor_token(')');
8410         statement->whiles.condition = parse_expression();
8411         rem_anchor_token(')');
8412         expect(')');
8413
8414         statement->whiles.body = parse_loop_body(statement);
8415
8416         POP_PARENT;
8417         return statement;
8418 end_error:
8419         POP_PARENT;
8420         return create_invalid_statement();
8421 }
8422
8423 /**
8424  * Parse a do statement.
8425  */
8426 static statement_t *parse_do(void)
8427 {
8428         eat(T_do);
8429
8430         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8431         statement->base.source_position = token.source_position;
8432
8433         PUSH_PARENT(statement)
8434
8435         add_anchor_token(T_while);
8436         statement->do_while.body = parse_loop_body(statement);
8437         rem_anchor_token(T_while);
8438
8439         expect(T_while);
8440         expect('(');
8441         add_anchor_token(')');
8442         statement->do_while.condition = parse_expression();
8443         rem_anchor_token(')');
8444         expect(')');
8445         expect(';');
8446
8447         POP_PARENT;
8448         return statement;
8449 end_error:
8450         POP_PARENT;
8451         return create_invalid_statement();
8452 }
8453
8454 /**
8455  * Parse a for statement.
8456  */
8457 static statement_t *parse_for(void)
8458 {
8459         eat(T_for);
8460
8461         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
8462         statement->base.source_position = token.source_position;
8463
8464         PUSH_PARENT(statement);
8465
8466         int      top        = environment_top();
8467         scope_t *last_scope = scope;
8468         set_scope(&statement->fors.scope);
8469
8470         expect('(');
8471         add_anchor_token(')');
8472
8473         if (token.type != ';') {
8474                 if (is_declaration_specifier(&token, false)) {
8475                         parse_declaration(record_declaration);
8476                 } else {
8477                         add_anchor_token(';');
8478                         expression_t *const init = parse_expression();
8479                         statement->fors.initialisation = init;
8480                         if (warning.unused_value && !expression_has_effect(init)) {
8481                                 warningf(&init->base.source_position,
8482                                          "initialisation of 'for'-statement has no effect");
8483                         }
8484                         rem_anchor_token(';');
8485                         expect(';');
8486                 }
8487         } else {
8488                 expect(';');
8489         }
8490
8491         if (token.type != ';') {
8492                 add_anchor_token(';');
8493                 statement->fors.condition = parse_expression();
8494                 rem_anchor_token(';');
8495         }
8496         expect(';');
8497         if (token.type != ')') {
8498                 expression_t *const step = parse_expression();
8499                 statement->fors.step = step;
8500                 if (warning.unused_value && !expression_has_effect(step)) {
8501                         warningf(&step->base.source_position,
8502                                  "step of 'for'-statement has no effect");
8503                 }
8504         }
8505         rem_anchor_token(')');
8506         expect(')');
8507         statement->fors.body = parse_loop_body(statement);
8508
8509         assert(scope == &statement->fors.scope);
8510         set_scope(last_scope);
8511         environment_pop_to(top);
8512
8513         POP_PARENT;
8514         return statement;
8515
8516 end_error:
8517         POP_PARENT;
8518         rem_anchor_token(')');
8519         assert(scope == &statement->fors.scope);
8520         set_scope(last_scope);
8521         environment_pop_to(top);
8522
8523         return create_invalid_statement();
8524 }
8525
8526 /**
8527  * Parse a goto statement.
8528  */
8529 static statement_t *parse_goto(void)
8530 {
8531         eat(T_goto);
8532
8533         if (token.type != T_IDENTIFIER) {
8534                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8535                 eat_statement();
8536                 goto end_error;
8537         }
8538         symbol_t *symbol = token.v.symbol;
8539         next_token();
8540
8541         declaration_t *label = get_label(symbol);
8542
8543         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
8544         statement->base.source_position = token.source_position;
8545
8546         statement->gotos.label = label;
8547
8548         /* remember the goto's in a list for later checking */
8549         if (goto_last == NULL) {
8550                 goto_first = &statement->gotos;
8551         } else {
8552                 goto_last->next = &statement->gotos;
8553         }
8554         goto_last = &statement->gotos;
8555
8556         expect(';');
8557
8558         return statement;
8559 end_error:
8560         return create_invalid_statement();
8561 }
8562
8563 /**
8564  * Parse a continue statement.
8565  */
8566 static statement_t *parse_continue(void)
8567 {
8568         statement_t *statement;
8569         if (current_loop == NULL) {
8570                 errorf(HERE, "continue statement not within loop");
8571                 statement = create_invalid_statement();
8572         } else {
8573                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
8574
8575                 statement->base.source_position = token.source_position;
8576         }
8577
8578         eat(T_continue);
8579         expect(';');
8580
8581         return statement;
8582 end_error:
8583         return create_invalid_statement();
8584 }
8585
8586 /**
8587  * Parse a break statement.
8588  */
8589 static statement_t *parse_break(void)
8590 {
8591         statement_t *statement;
8592         if (current_switch == NULL && current_loop == NULL) {
8593                 errorf(HERE, "break statement not within loop or switch");
8594                 statement = create_invalid_statement();
8595         } else {
8596                 statement = allocate_statement_zero(STATEMENT_BREAK);
8597
8598                 statement->base.source_position = token.source_position;
8599         }
8600
8601         eat(T_break);
8602         expect(';');
8603
8604         return statement;
8605 end_error:
8606         return create_invalid_statement();
8607 }
8608
8609 /**
8610  * Parse a __leave statement.
8611  */
8612 static statement_t *parse_leave(void)
8613 {
8614         statement_t *statement;
8615         if (current_try == NULL) {
8616                 errorf(HERE, "__leave statement not within __try");
8617                 statement = create_invalid_statement();
8618         } else {
8619                 statement = allocate_statement_zero(STATEMENT_LEAVE);
8620
8621                 statement->base.source_position = token.source_position;
8622         }
8623
8624         eat(T___leave);
8625         expect(';');
8626
8627         return statement;
8628 end_error:
8629         return create_invalid_statement();
8630 }
8631
8632 /**
8633  * Check if a given declaration represents a local variable.
8634  */
8635 static bool is_local_var_declaration(const declaration_t *declaration)
8636 {
8637         switch ((storage_class_tag_t) declaration->storage_class) {
8638         case STORAGE_CLASS_AUTO:
8639         case STORAGE_CLASS_REGISTER: {
8640                 const type_t *type = skip_typeref(declaration->type);
8641                 if (is_type_function(type)) {
8642                         return false;
8643                 } else {
8644                         return true;
8645                 }
8646         }
8647         default:
8648                 return false;
8649         }
8650 }
8651
8652 /**
8653  * Check if a given declaration represents a variable.
8654  */
8655 static bool is_var_declaration(const declaration_t *declaration)
8656 {
8657         if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
8658                 return false;
8659
8660         const type_t *type = skip_typeref(declaration->type);
8661         return !is_type_function(type);
8662 }
8663
8664 /**
8665  * Check if a given expression represents a local variable.
8666  */
8667 static bool is_local_variable(const expression_t *expression)
8668 {
8669         if (expression->base.kind != EXPR_REFERENCE) {
8670                 return false;
8671         }
8672         const declaration_t *declaration = expression->reference.declaration;
8673         return is_local_var_declaration(declaration);
8674 }
8675
8676 /**
8677  * Check if a given expression represents a local variable and
8678  * return its declaration then, else return NULL.
8679  */
8680 declaration_t *expr_is_variable(const expression_t *expression)
8681 {
8682         if (expression->base.kind != EXPR_REFERENCE) {
8683                 return NULL;
8684         }
8685         declaration_t *declaration = expression->reference.declaration;
8686         if (is_var_declaration(declaration))
8687                 return declaration;
8688         return NULL;
8689 }
8690
8691 /**
8692  * Parse a return statement.
8693  */
8694 static statement_t *parse_return(void)
8695 {
8696         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
8697         statement->base.source_position = token.source_position;
8698
8699         eat(T_return);
8700
8701         expression_t *return_value = NULL;
8702         if (token.type != ';') {
8703                 return_value = parse_expression();
8704         }
8705         expect(';');
8706
8707         const type_t *const func_type = current_function->type;
8708         assert(is_type_function(func_type));
8709         type_t *const return_type = skip_typeref(func_type->function.return_type);
8710
8711         if (return_value != NULL) {
8712                 type_t *return_value_type = skip_typeref(return_value->base.type);
8713
8714                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8715                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8716                         warningf(&statement->base.source_position,
8717                                  "'return' with a value, in function returning void");
8718                         return_value = NULL;
8719                 } else {
8720                         assign_error_t error = semantic_assign(return_type, return_value);
8721                         report_assign_error(error, return_type, return_value, "'return'",
8722                                             &statement->base.source_position);
8723                         return_value = create_implicit_cast(return_value, return_type);
8724                 }
8725                 /* check for returning address of a local var */
8726                 if (return_value != NULL &&
8727                                 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8728                         const expression_t *expression = return_value->unary.value;
8729                         if (is_local_variable(expression)) {
8730                                 warningf(&statement->base.source_position,
8731                                          "function returns address of local variable");
8732                         }
8733                 }
8734         } else {
8735                 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8736                         warningf(&statement->base.source_position,
8737                                  "'return' without value, in function returning non-void");
8738                 }
8739         }
8740         statement->returns.value = return_value;
8741
8742         return statement;
8743 end_error:
8744         return create_invalid_statement();
8745 }
8746
8747 /**
8748  * Parse a declaration statement.
8749  */
8750 static statement_t *parse_declaration_statement(void)
8751 {
8752         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8753
8754         statement->base.source_position = token.source_position;
8755
8756         declaration_t *before = last_declaration;
8757         parse_declaration(record_declaration);
8758
8759         if (before == NULL) {
8760                 statement->declaration.declarations_begin = scope->declarations;
8761         } else {
8762                 statement->declaration.declarations_begin = before->next;
8763         }
8764         statement->declaration.declarations_end = last_declaration;
8765
8766         return statement;
8767 }
8768
8769 /**
8770  * Parse an expression statement, ie. expr ';'.
8771  */
8772 static statement_t *parse_expression_statement(void)
8773 {
8774         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8775
8776         statement->base.source_position  = token.source_position;
8777         expression_t *const expr         = parse_expression();
8778         statement->expression.expression = expr;
8779
8780         expect(';');
8781
8782         return statement;
8783 end_error:
8784         return create_invalid_statement();
8785 }
8786
8787 /**
8788  * Parse a microsoft __try { } __finally { } or
8789  * __try{ } __except() { }
8790  */
8791 static statement_t *parse_ms_try_statment(void)
8792 {
8793         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8794
8795         statement->base.source_position  = token.source_position;
8796         eat(T___try);
8797
8798         ms_try_statement_t *rem = current_try;
8799         current_try = &statement->ms_try;
8800         statement->ms_try.try_statement = parse_compound_statement(false);
8801         current_try = rem;
8802
8803         if (token.type == T___except) {
8804                 eat(T___except);
8805                 expect('(');
8806                 add_anchor_token(')');
8807                 expression_t *const expr = parse_expression();
8808                 type_t       *      type = skip_typeref(expr->base.type);
8809                 if (is_type_integer(type)) {
8810                         type = promote_integer(type);
8811                 } else if (is_type_valid(type)) {
8812                         errorf(&expr->base.source_position,
8813                                "__expect expression is not an integer, but '%T'", type);
8814                         type = type_error_type;
8815                 }
8816                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8817                 rem_anchor_token(')');
8818                 expect(')');
8819                 statement->ms_try.final_statement = parse_compound_statement(false);
8820         } else if (token.type == T__finally) {
8821                 eat(T___finally);
8822                 statement->ms_try.final_statement = parse_compound_statement(false);
8823         } else {
8824                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8825                 return create_invalid_statement();
8826         }
8827         return statement;
8828 end_error:
8829         return create_invalid_statement();
8830 }
8831
8832 static statement_t *parse_empty_statement(void)
8833 {
8834         if (warning.empty_statement) {
8835                 warningf(HERE, "statement is empty");
8836         }
8837         eat(';');
8838         return create_empty_statement();
8839 }
8840
8841 /**
8842  * Parse a statement.
8843  * There's also parse_statement() which additionally checks for
8844  * "statement has no effect" warnings
8845  */
8846 static statement_t *intern_parse_statement(void)
8847 {
8848         statement_t *statement = NULL;
8849
8850         /* declaration or statement */
8851         add_anchor_token(';');
8852         switch (token.type) {
8853         case T_IDENTIFIER:
8854                 if (look_ahead(1)->type == ':') {
8855                         statement = parse_label_statement();
8856                 } else if (is_typedef_symbol(token.v.symbol)) {
8857                         statement = parse_declaration_statement();
8858                 } else {
8859                         statement = parse_expression_statement();
8860                 }
8861                 break;
8862
8863         case T___extension__:
8864                 /* This can be a prefix to a declaration or an expression statement.
8865                  * We simply eat it now and parse the rest with tail recursion. */
8866                 do {
8867                         next_token();
8868                 } while (token.type == T___extension__);
8869                 statement = parse_statement();
8870                 break;
8871
8872         DECLARATION_START
8873                 statement = parse_declaration_statement();
8874                 break;
8875
8876         case ';':        statement = parse_empty_statement();         break;
8877         case '{':        statement = parse_compound_statement(false); break;
8878         case T___leave:  statement = parse_leave();                   break;
8879         case T___try:    statement = parse_ms_try_statment();         break;
8880         case T_asm:      statement = parse_asm_statement();           break;
8881         case T_break:    statement = parse_break();                   break;
8882         case T_case:     statement = parse_case_statement();          break;
8883         case T_continue: statement = parse_continue();                break;
8884         case T_default:  statement = parse_default_statement();       break;
8885         case T_do:       statement = parse_do();                      break;
8886         case T_for:      statement = parse_for();                     break;
8887         case T_goto:     statement = parse_goto();                    break;
8888         case T_if:       statement = parse_if ();                     break;
8889         case T_return:   statement = parse_return();                  break;
8890         case T_switch:   statement = parse_switch();                  break;
8891         case T_while:    statement = parse_while();                   break;
8892         default:         statement = parse_expression_statement();    break;
8893         }
8894         rem_anchor_token(';');
8895
8896         assert(statement != NULL
8897                         && statement->base.source_position.input_name != NULL);
8898
8899         return statement;
8900 }
8901
8902 /**
8903  * parse a statement and emits "statement has no effect" warning if needed
8904  * (This is really a wrapper around intern_parse_statement with check for 1
8905  *  single warning. It is needed, because for statement expressions we have
8906  *  to avoid the warning on the last statement)
8907  */
8908 static statement_t *parse_statement(void)
8909 {
8910         statement_t *statement = intern_parse_statement();
8911
8912         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8913                 expression_t *expression = statement->expression.expression;
8914                 if (!expression_has_effect(expression)) {
8915                         warningf(&expression->base.source_position,
8916                                         "statement has no effect");
8917                 }
8918         }
8919
8920         return statement;
8921 }
8922
8923 /**
8924  * Parse a compound statement.
8925  */
8926 static statement_t *parse_compound_statement(bool inside_expression_statement)
8927 {
8928         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8929         statement->base.source_position = token.source_position;
8930
8931         PUSH_PARENT(statement);
8932
8933         eat('{');
8934         add_anchor_token('}');
8935
8936         int      top        = environment_top();
8937         scope_t *last_scope = scope;
8938         set_scope(&statement->compound.scope);
8939
8940         statement_t *last_statement = NULL;
8941
8942         bool only_decls_so_far = true;
8943         while (token.type != '}' && token.type != T_EOF) {
8944                 statement_t *sub_statement = intern_parse_statement();
8945                 if (is_invalid_statement(sub_statement)) {
8946                         /* an error occurred. if we are at an anchor, return */
8947                         if (at_anchor())
8948                                 goto end_error;
8949                         continue;
8950                 }
8951
8952                 if (warning.declaration_after_statement) {
8953                         if (sub_statement->kind != STATEMENT_DECLARATION) {
8954                                 only_decls_so_far = false;
8955                         } else if (!only_decls_so_far) {
8956                                 warningf(&sub_statement->base.source_position,
8957                                          "ISO C90 forbids mixed declarations and code");
8958                         }
8959                 }
8960
8961                 if (last_statement != NULL) {
8962                         last_statement->base.next = sub_statement;
8963                 } else {
8964                         statement->compound.statements = sub_statement;
8965                 }
8966
8967                 while (sub_statement->base.next != NULL)
8968                         sub_statement = sub_statement->base.next;
8969
8970                 last_statement = sub_statement;
8971         }
8972
8973         if (token.type == '}') {
8974                 next_token();
8975         } else {
8976                 errorf(&statement->base.source_position,
8977                        "end of file while looking for closing '}'");
8978         }
8979
8980         /* look over all statements again to produce no effect warnings */
8981         if (warning.unused_value) {
8982                 statement_t *sub_statement = statement->compound.statements;
8983                 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8984                         if (sub_statement->kind != STATEMENT_EXPRESSION)
8985                                 continue;
8986                         /* don't emit a warning for the last expression in an expression
8987                          * statement as it has always an effect */
8988                         if (inside_expression_statement && sub_statement->base.next == NULL)
8989                                 continue;
8990
8991                         expression_t *expression = sub_statement->expression.expression;
8992                         if (!expression_has_effect(expression)) {
8993                                 warningf(&expression->base.source_position,
8994                                          "statement has no effect");
8995                         }
8996                 }
8997         }
8998
8999 end_error:
9000         rem_anchor_token('}');
9001         assert(scope == &statement->compound.scope);
9002         set_scope(last_scope);
9003         environment_pop_to(top);
9004
9005         POP_PARENT;
9006         return statement;
9007 }
9008
9009 /**
9010  * Initialize builtin types.
9011  */
9012 static void initialize_builtin_types(void)
9013 {
9014         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
9015         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
9016         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
9017         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
9018         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
9019         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9020         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
9021         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
9022
9023         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
9024         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9025         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
9026         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
9027 }
9028
9029 /**
9030  * Check for unused global static functions and variables
9031  */
9032 static void check_unused_globals(void)
9033 {
9034         if (!warning.unused_function && !warning.unused_variable)
9035                 return;
9036
9037         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9038                 if (decl->used                  ||
9039                     decl->modifiers & DM_UNUSED ||
9040                     decl->modifiers & DM_USED   ||
9041                     decl->storage_class != STORAGE_CLASS_STATIC)
9042                         continue;
9043
9044                 type_t *const type = decl->type;
9045                 const char *s;
9046                 if (is_type_function(skip_typeref(type))) {
9047                         if (!warning.unused_function || decl->is_inline)
9048                                 continue;
9049
9050                         s = (decl->init.statement != NULL ? "defined" : "declared");
9051                 } else {
9052                         if (!warning.unused_variable)
9053                                 continue;
9054
9055                         s = "defined";
9056                 }
9057
9058                 warningf(&decl->source_position, "'%#T' %s but not used",
9059                         type, decl->symbol, s);
9060         }
9061 }
9062
9063 static void parse_global_asm(void)
9064 {
9065         eat(T_asm);
9066         expect('(');
9067
9068         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
9069         statement->base.source_position = token.source_position;
9070         statement->asms.asm_text        = parse_string_literals();
9071         statement->base.next            = unit->global_asm;
9072         unit->global_asm                = statement;
9073
9074         expect(')');
9075         expect(';');
9076
9077 end_error:;
9078 }
9079
9080 /**
9081  * Parse a translation unit.
9082  */
9083 static void parse_translation_unit(void)
9084 {
9085         for (;;) switch (token.type) {
9086                 DECLARATION_START
9087                 case T_IDENTIFIER:
9088                 case T___extension__:
9089                         parse_external_declaration();
9090                         break;
9091
9092                 case T_asm:
9093                         parse_global_asm();
9094                         break;
9095
9096                 case T_EOF:
9097                         return;
9098
9099                 case ';':
9100                         /* TODO error in strict mode */
9101                         warningf(HERE, "stray ';' outside of function");
9102                         next_token();
9103                         break;
9104
9105                 default:
9106                         errorf(HERE, "stray %K outside of function", &token);
9107                         if (token.type == '(' || token.type == '{' || token.type == '[')
9108                                 eat_until_matching_token(token.type);
9109                         next_token();
9110                         break;
9111         }
9112 }
9113
9114 /**
9115  * Parse the input.
9116  *
9117  * @return  the translation unit or NULL if errors occurred.
9118  */
9119 void start_parsing(void)
9120 {
9121         environment_stack = NEW_ARR_F(stack_entry_t, 0);
9122         label_stack       = NEW_ARR_F(stack_entry_t, 0);
9123         diagnostic_count  = 0;
9124         error_count       = 0;
9125         warning_count     = 0;
9126
9127         type_set_output(stderr);
9128         ast_set_output(stderr);
9129
9130         assert(unit == NULL);
9131         unit = allocate_ast_zero(sizeof(unit[0]));
9132
9133         assert(global_scope == NULL);
9134         global_scope = &unit->scope;
9135
9136         assert(scope == NULL);
9137         set_scope(&unit->scope);
9138
9139         initialize_builtin_types();
9140 }
9141
9142 translation_unit_t *finish_parsing(void)
9143 {
9144         assert(scope == &unit->scope);
9145         scope          = NULL;
9146         last_declaration = NULL;
9147
9148         assert(global_scope == &unit->scope);
9149         check_unused_globals();
9150         global_scope = NULL;
9151
9152         DEL_ARR_F(environment_stack);
9153         DEL_ARR_F(label_stack);
9154
9155         translation_unit_t *result = unit;
9156         unit = NULL;
9157         return result;
9158 }
9159
9160 void parse(void)
9161 {
9162         lookahead_bufpos = 0;
9163         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9164                 next_token();
9165         }
9166         parse_translation_unit();
9167 }
9168
9169 /**
9170  * Initialize the parser.
9171  */
9172 void init_parser(void)
9173 {
9174         if (c_mode & _MS) {
9175                 /* add predefined symbols for extended-decl-modifier */
9176                 sym_align      = symbol_table_insert("align");
9177                 sym_allocate   = symbol_table_insert("allocate");
9178                 sym_dllimport  = symbol_table_insert("dllimport");
9179                 sym_dllexport  = symbol_table_insert("dllexport");
9180                 sym_naked      = symbol_table_insert("naked");
9181                 sym_noinline   = symbol_table_insert("noinline");
9182                 sym_noreturn   = symbol_table_insert("noreturn");
9183                 sym_nothrow    = symbol_table_insert("nothrow");
9184                 sym_novtable   = symbol_table_insert("novtable");
9185                 sym_property   = symbol_table_insert("property");
9186                 sym_get        = symbol_table_insert("get");
9187                 sym_put        = symbol_table_insert("put");
9188                 sym_selectany  = symbol_table_insert("selectany");
9189                 sym_thread     = symbol_table_insert("thread");
9190                 sym_uuid       = symbol_table_insert("uuid");
9191                 sym_deprecated = symbol_table_insert("deprecated");
9192                 sym_restrict   = symbol_table_insert("restrict");
9193                 sym_noalias    = symbol_table_insert("noalias");
9194         }
9195         memset(token_anchor_set, 0, sizeof(token_anchor_set));
9196
9197         init_expression_parsers();
9198         obstack_init(&temp_obst);
9199
9200         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9201         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9202 }
9203
9204 /**
9205  * Terminate the parser.
9206  */
9207 void exit_parser(void)
9208 {
9209         obstack_free(&temp_obst, NULL);
9210 }