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