3830c686ed1e224c424a6e46af68352a6b85cead
[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_function_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 (is_function_definition && warning.main && 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_function_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_function_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_function_definition) {
4188                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4189                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
4190                                 warningf(&declaration->source_position,
4191                                          "no previous prototype for '%#T'", orig_type, symbol);
4192                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4193                                 warningf(&declaration->source_position,
4194                                          "no previous declaration for '%#T'", orig_type,
4195                                          symbol);
4196                         }
4197                 }
4198         } else if (warning.missing_declarations &&
4199             scope == global_scope &&
4200             !is_type_function(type) && (
4201               declaration->storage_class == STORAGE_CLASS_NONE ||
4202               declaration->storage_class == STORAGE_CLASS_THREAD
4203             )) {
4204                 warningf(&declaration->source_position,
4205                          "no previous declaration for '%#T'", orig_type, symbol);
4206         }
4207
4208         assert(declaration->parent_scope == NULL);
4209         assert(scope != NULL);
4210
4211         declaration->parent_scope = scope;
4212
4213         environment_push(declaration);
4214         return append_declaration(declaration);
4215 }
4216
4217 static declaration_t *record_declaration(declaration_t *declaration)
4218 {
4219         return internal_record_declaration(declaration, false);
4220 }
4221
4222 static declaration_t *record_function_definition(declaration_t *declaration)
4223 {
4224         return internal_record_declaration(declaration, true);
4225 }
4226
4227 static void parser_error_multiple_definition(declaration_t *declaration,
4228                 const source_position_t *source_position)
4229 {
4230         errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4231                declaration->symbol, &declaration->source_position);
4232 }
4233
4234 static bool is_declaration_specifier(const token_t *token,
4235                                      bool only_specifiers_qualifiers)
4236 {
4237         switch(token->type) {
4238                 TYPE_SPECIFIERS
4239                 TYPE_QUALIFIERS
4240                         return true;
4241                 case T_IDENTIFIER:
4242                         return is_typedef_symbol(token->v.symbol);
4243
4244                 case T___extension__:
4245                 STORAGE_CLASSES
4246                         return !only_specifiers_qualifiers;
4247
4248                 default:
4249                         return false;
4250         }
4251 }
4252
4253 static void parse_init_declarator_rest(declaration_t *declaration)
4254 {
4255         eat('=');
4256
4257         type_t *orig_type = declaration->type;
4258         type_t *type      = skip_typeref(orig_type);
4259
4260         if (declaration->init.initializer != NULL) {
4261                 parser_error_multiple_definition(declaration, HERE);
4262         }
4263
4264         bool must_be_constant = false;
4265         if (declaration->storage_class == STORAGE_CLASS_STATIC
4266                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4267                         || declaration->parent_scope == global_scope) {
4268                 must_be_constant = true;
4269         }
4270
4271         parse_initializer_env_t env;
4272         env.type             = orig_type;
4273         env.must_be_constant = must_be_constant;
4274         env.declaration      = declaration;
4275
4276         initializer_t *initializer = parse_initializer(&env);
4277
4278         if (env.type != orig_type) {
4279                 orig_type         = env.type;
4280                 type              = skip_typeref(orig_type);
4281                 declaration->type = env.type;
4282         }
4283
4284         if (is_type_function(type)) {
4285                 errorf(&declaration->source_position,
4286                        "initializers not allowed for function types at declator '%Y' (type '%T')",
4287                        declaration->symbol, orig_type);
4288         } else {
4289                 declaration->init.initializer = initializer;
4290         }
4291 }
4292
4293 /* parse rest of a declaration without any declarator */
4294 static void parse_anonymous_declaration_rest(
4295                 const declaration_specifiers_t *specifiers,
4296                 parsed_declaration_func finished_declaration)
4297 {
4298         eat(';');
4299
4300         declaration_t *const declaration    = allocate_declaration_zero();
4301         declaration->type                   = specifiers->type;
4302         declaration->declared_storage_class = specifiers->declared_storage_class;
4303         declaration->source_position        = specifiers->source_position;
4304         declaration->modifiers              = specifiers->modifiers;
4305
4306         if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4307                 warningf(&declaration->source_position,
4308                          "useless storage class in empty declaration");
4309         }
4310         declaration->storage_class = STORAGE_CLASS_NONE;
4311
4312         type_t *type = declaration->type;
4313         switch (type->kind) {
4314                 case TYPE_COMPOUND_STRUCT:
4315                 case TYPE_COMPOUND_UNION: {
4316                         if (type->compound.declaration->symbol == NULL) {
4317                                 warningf(&declaration->source_position,
4318                                          "unnamed struct/union that defines no instances");
4319                         }
4320                         break;
4321                 }
4322
4323                 case TYPE_ENUM:
4324                         break;
4325
4326                 default:
4327                         warningf(&declaration->source_position, "empty declaration");
4328                         break;
4329         }
4330
4331         finished_declaration(declaration);
4332 }
4333
4334 static void parse_declaration_rest(declaration_t *ndeclaration,
4335                 const declaration_specifiers_t *specifiers,
4336                 parsed_declaration_func finished_declaration)
4337 {
4338         add_anchor_token(';');
4339         add_anchor_token('=');
4340         add_anchor_token(',');
4341         while(true) {
4342                 declaration_t *declaration = finished_declaration(ndeclaration);
4343
4344                 type_t *orig_type = declaration->type;
4345                 type_t *type      = skip_typeref(orig_type);
4346
4347                 if (type->kind != TYPE_FUNCTION &&
4348                     declaration->is_inline &&
4349                     is_type_valid(type)) {
4350                         warningf(&declaration->source_position,
4351                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
4352                 }
4353
4354                 if (token.type == '=') {
4355                         parse_init_declarator_rest(declaration);
4356                 }
4357
4358                 if (token.type != ',')
4359                         break;
4360                 eat(',');
4361
4362                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4363         }
4364         expect(';');
4365
4366 end_error:
4367         rem_anchor_token(';');
4368         rem_anchor_token('=');
4369         rem_anchor_token(',');
4370 }
4371
4372 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4373 {
4374         symbol_t *symbol  = declaration->symbol;
4375         if (symbol == NULL) {
4376                 errorf(HERE, "anonymous declaration not valid as function parameter");
4377                 return declaration;
4378         }
4379         namespace_t namespc = (namespace_t) declaration->namespc;
4380         if (namespc != NAMESPACE_NORMAL) {
4381                 return record_declaration(declaration);
4382         }
4383
4384         declaration_t *previous_declaration = get_declaration(symbol, namespc);
4385         if (previous_declaration == NULL ||
4386                         previous_declaration->parent_scope != scope) {
4387                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4388                        symbol);
4389                 return declaration;
4390         }
4391
4392         if (previous_declaration->type == NULL) {
4393                 previous_declaration->type          = declaration->type;
4394                 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4395                 previous_declaration->storage_class = declaration->storage_class;
4396                 previous_declaration->parent_scope  = scope;
4397                 return previous_declaration;
4398         } else {
4399                 return record_declaration(declaration);
4400         }
4401 }
4402
4403 static void parse_declaration(parsed_declaration_func finished_declaration)
4404 {
4405         declaration_specifiers_t specifiers;
4406         memset(&specifiers, 0, sizeof(specifiers));
4407         parse_declaration_specifiers(&specifiers);
4408
4409         if (token.type == ';') {
4410                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4411         } else {
4412                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4413                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4414         }
4415 }
4416
4417 static type_t *get_default_promoted_type(type_t *orig_type)
4418 {
4419         type_t *result = orig_type;
4420
4421         type_t *type = skip_typeref(orig_type);
4422         if (is_type_integer(type)) {
4423                 result = promote_integer(type);
4424         } else if (type == type_float) {
4425                 result = type_double;
4426         }
4427
4428         return result;
4429 }
4430
4431 static void parse_kr_declaration_list(declaration_t *declaration)
4432 {
4433         type_t *type = skip_typeref(declaration->type);
4434         if (!is_type_function(type))
4435                 return;
4436
4437         if (!type->function.kr_style_parameters)
4438                 return;
4439
4440         /* push function parameters */
4441         int       top        = environment_top();
4442         scope_t  *last_scope = scope;
4443         set_scope(&declaration->scope);
4444
4445         declaration_t *parameter = declaration->scope.declarations;
4446         for ( ; parameter != NULL; parameter = parameter->next) {
4447                 assert(parameter->parent_scope == NULL);
4448                 parameter->parent_scope = scope;
4449                 environment_push(parameter);
4450         }
4451
4452         /* parse declaration list */
4453         while (is_declaration_specifier(&token, false)) {
4454                 parse_declaration(finished_kr_declaration);
4455         }
4456
4457         /* pop function parameters */
4458         assert(scope == &declaration->scope);
4459         set_scope(last_scope);
4460         environment_pop_to(top);
4461
4462         /* update function type */
4463         type_t *new_type = duplicate_type(type);
4464
4465         function_parameter_t *parameters     = NULL;
4466         function_parameter_t *last_parameter = NULL;
4467
4468         declaration_t *parameter_declaration = declaration->scope.declarations;
4469         for( ; parameter_declaration != NULL;
4470                         parameter_declaration = parameter_declaration->next) {
4471                 type_t *parameter_type = parameter_declaration->type;
4472                 if (parameter_type == NULL) {
4473                         if (strict_mode) {
4474                                 errorf(HERE, "no type specified for function parameter '%Y'",
4475                                        parameter_declaration->symbol);
4476                         } else {
4477                                 if (warning.implicit_int) {
4478                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4479                                                 parameter_declaration->symbol);
4480                                 }
4481                                 parameter_type              = type_int;
4482                                 parameter_declaration->type = parameter_type;
4483                         }
4484                 }
4485
4486                 semantic_parameter(parameter_declaration);
4487                 parameter_type = parameter_declaration->type;
4488
4489                 /*
4490                  * we need the default promoted types for the function type
4491                  */
4492                 parameter_type = get_default_promoted_type(parameter_type);
4493
4494                 function_parameter_t *function_parameter
4495                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4496                 memset(function_parameter, 0, sizeof(function_parameter[0]));
4497
4498                 function_parameter->type = parameter_type;
4499                 if (last_parameter != NULL) {
4500                         last_parameter->next = function_parameter;
4501                 } else {
4502                         parameters = function_parameter;
4503                 }
4504                 last_parameter = function_parameter;
4505         }
4506
4507         /* Â§ 6.9.1.7: A K&R style parameter list does NOT act as a function
4508          * prototype */
4509         new_type->function.parameters             = parameters;
4510         new_type->function.unspecified_parameters = true;
4511
4512         type = typehash_insert(new_type);
4513         if (type != new_type) {
4514                 obstack_free(type_obst, new_type);
4515         }
4516
4517         declaration->type = type;
4518 }
4519
4520 static bool first_err = true;
4521
4522 /**
4523  * When called with first_err set, prints the name of the current function,
4524  * else does noting.
4525  */
4526 static void print_in_function(void) {
4527         if (first_err) {
4528                 first_err = false;
4529                 diagnosticf("%s: In function '%Y':\n",
4530                         current_function->source_position.input_name,
4531                         current_function->symbol);
4532         }
4533 }
4534
4535 /**
4536  * Check if all labels are defined in the current function.
4537  * Check if all labels are used in the current function.
4538  */
4539 static void check_labels(void)
4540 {
4541         for (const goto_statement_t *goto_statement = goto_first;
4542             goto_statement != NULL;
4543             goto_statement = goto_statement->next) {
4544                 declaration_t *label = goto_statement->label;
4545
4546                 label->used = true;
4547                 if (label->source_position.input_name == NULL) {
4548                         print_in_function();
4549                         errorf(&goto_statement->base.source_position,
4550                                "label '%Y' used but not defined", label->symbol);
4551                  }
4552         }
4553         goto_first = goto_last = NULL;
4554
4555         if (warning.unused_label) {
4556                 for (const label_statement_t *label_statement = label_first;
4557                          label_statement != NULL;
4558                          label_statement = label_statement->next) {
4559                         const declaration_t *label = label_statement->label;
4560
4561                         if (! label->used) {
4562                                 print_in_function();
4563                                 warningf(&label_statement->base.source_position,
4564                                         "label '%Y' defined but not used", label->symbol);
4565                         }
4566                 }
4567         }
4568         label_first = label_last = NULL;
4569 }
4570
4571 /**
4572  * Check declarations of current_function for unused entities.
4573  */
4574 static void check_declarations(void)
4575 {
4576         if (warning.unused_parameter) {
4577                 const scope_t *scope = &current_function->scope;
4578
4579                 const declaration_t *parameter = scope->declarations;
4580                 for (; parameter != NULL; parameter = parameter->next) {
4581                         if (! parameter->used) {
4582                                 print_in_function();
4583                                 warningf(&parameter->source_position,
4584                                          "unused parameter '%Y'", parameter->symbol);
4585                         }
4586                 }
4587         }
4588         if (warning.unused_variable) {
4589         }
4590 }
4591
4592 static void parse_external_declaration(void)
4593 {
4594         /* function-definitions and declarations both start with declaration
4595          * specifiers */
4596         declaration_specifiers_t specifiers;
4597         memset(&specifiers, 0, sizeof(specifiers));
4598
4599         add_anchor_token(';');
4600         parse_declaration_specifiers(&specifiers);
4601         rem_anchor_token(';');
4602
4603         /* must be a declaration */
4604         if (token.type == ';') {
4605                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4606                 return;
4607         }
4608
4609         add_anchor_token(',');
4610         add_anchor_token('=');
4611         rem_anchor_token(';');
4612
4613         /* declarator is common to both function-definitions and declarations */
4614         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4615
4616         rem_anchor_token(',');
4617         rem_anchor_token('=');
4618         rem_anchor_token(';');
4619
4620         /* must be a declaration */
4621         if (token.type == ',' || token.type == '=' || token.type == ';') {
4622                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4623                 return;
4624         }
4625
4626         /* must be a function definition */
4627         parse_kr_declaration_list(ndeclaration);
4628
4629         if (token.type != '{') {
4630                 parse_error_expected("while parsing function definition", '{', NULL);
4631                 eat_until_matching_token(';');
4632                 return;
4633         }
4634
4635         type_t *type = ndeclaration->type;
4636
4637         /* note that we don't skip typerefs: the standard doesn't allow them here
4638          * (so we can't use is_type_function here) */
4639         if (type->kind != TYPE_FUNCTION) {
4640                 if (is_type_valid(type)) {
4641                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
4642                                type, ndeclaration->symbol);
4643                 }
4644                 eat_block();
4645                 return;
4646         }
4647
4648         /* Â§ 6.7.5.3 (14) a function definition with () means no
4649          * parameters (and not unspecified parameters) */
4650         if (type->function.unspecified_parameters
4651                         && type->function.parameters == NULL
4652                         && !type->function.kr_style_parameters) {
4653                 type_t *duplicate = duplicate_type(type);
4654                 duplicate->function.unspecified_parameters = false;
4655
4656                 type = typehash_insert(duplicate);
4657                 if (type != duplicate) {
4658                         obstack_free(type_obst, duplicate);
4659                 }
4660                 ndeclaration->type = type;
4661         }
4662
4663         declaration_t *const declaration = record_function_definition(ndeclaration);
4664         if (ndeclaration != declaration) {
4665                 declaration->scope = ndeclaration->scope;
4666         }
4667         type = skip_typeref(declaration->type);
4668
4669         /* push function parameters and switch scope */
4670         int       top        = environment_top();
4671         scope_t  *last_scope = scope;
4672         set_scope(&declaration->scope);
4673
4674         declaration_t *parameter = declaration->scope.declarations;
4675         for( ; parameter != NULL; parameter = parameter->next) {
4676                 if (parameter->parent_scope == &ndeclaration->scope) {
4677                         parameter->parent_scope = scope;
4678                 }
4679                 assert(parameter->parent_scope == NULL
4680                                 || parameter->parent_scope == scope);
4681                 parameter->parent_scope = scope;
4682                 if (parameter->symbol == NULL) {
4683                         errorf(&ndeclaration->source_position, "parameter name omitted");
4684                         continue;
4685                 }
4686                 environment_push(parameter);
4687         }
4688
4689         if (declaration->init.statement != NULL) {
4690                 parser_error_multiple_definition(declaration, HERE);
4691                 eat_block();
4692         } else {
4693                 /* parse function body */
4694                 int            label_stack_top      = label_top();
4695                 declaration_t *old_current_function = current_function;
4696                 current_function                    = declaration;
4697
4698                 declaration->init.statement = parse_compound_statement(false);
4699                 first_err = true;
4700                 check_labels();
4701                 check_declarations();
4702
4703                 assert(current_function == declaration);
4704                 current_function = old_current_function;
4705                 label_pop_to(label_stack_top);
4706         }
4707
4708         assert(scope == &declaration->scope);
4709         set_scope(last_scope);
4710         environment_pop_to(top);
4711 }
4712
4713 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4714                                   source_position_t *source_position)
4715 {
4716         type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4717
4718         type->bitfield.base_type = base_type;
4719         type->bitfield.size      = size;
4720
4721         return type;
4722 }
4723
4724 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4725                                           symbol_t *symbol)
4726 {
4727         declaration_t *iter = compound_declaration->scope.declarations;
4728         for( ; iter != NULL; iter = iter->next) {
4729                 if (iter->namespc != NAMESPACE_NORMAL)
4730                         continue;
4731
4732                 if (iter->symbol == NULL) {
4733                         type_t *type = skip_typeref(iter->type);
4734                         if (is_type_compound(type)) {
4735                                 declaration_t *result
4736                                         = find_compound_entry(type->compound.declaration, symbol);
4737                                 if (result != NULL)
4738                                         return result;
4739                         }
4740                         continue;
4741                 }
4742
4743                 if (iter->symbol == symbol) {
4744                         return iter;
4745                 }
4746         }
4747
4748         return NULL;
4749 }
4750
4751 static void parse_compound_declarators(declaration_t *struct_declaration,
4752                 const declaration_specifiers_t *specifiers)
4753 {
4754         declaration_t *last_declaration = struct_declaration->scope.declarations;
4755         if (last_declaration != NULL) {
4756                 while(last_declaration->next != NULL) {
4757                         last_declaration = last_declaration->next;
4758                 }
4759         }
4760
4761         while(1) {
4762                 declaration_t *declaration;
4763
4764                 if (token.type == ':') {
4765                         source_position_t source_position = *HERE;
4766                         next_token();
4767
4768                         type_t *base_type = specifiers->type;
4769                         expression_t *size = parse_constant_expression();
4770
4771                         if (!is_type_integer(skip_typeref(base_type))) {
4772                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
4773                                        base_type);
4774                         }
4775
4776                         type_t *type = make_bitfield_type(base_type, size, &source_position);
4777
4778                         declaration                         = allocate_declaration_zero();
4779                         declaration->namespc                = NAMESPACE_NORMAL;
4780                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
4781                         declaration->storage_class          = STORAGE_CLASS_NONE;
4782                         declaration->source_position        = source_position;
4783                         declaration->modifiers              = specifiers->modifiers;
4784                         declaration->type                   = type;
4785                 } else {
4786                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4787
4788                         type_t *orig_type = declaration->type;
4789                         type_t *type      = skip_typeref(orig_type);
4790
4791                         if (token.type == ':') {
4792                                 source_position_t source_position = *HERE;
4793                                 next_token();
4794                                 expression_t *size = parse_constant_expression();
4795
4796                                 if (!is_type_integer(type)) {
4797                                         errorf(HERE, "bitfield base type '%T' is not an "
4798                                                "integer type", orig_type);
4799                                 }
4800
4801                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4802                                 declaration->type = bitfield_type;
4803                         } else {
4804                                 /* TODO we ignore arrays for now... what is missing is a check
4805                                  * that they're at the end of the struct */
4806                                 if (is_type_incomplete(type) && !is_type_array(type)) {
4807                                         errorf(HERE,
4808                                                "compound member '%Y' has incomplete type '%T'",
4809                                                declaration->symbol, orig_type);
4810                                 } else if (is_type_function(type)) {
4811                                         errorf(HERE, "compound member '%Y' must not have function "
4812                                                "type '%T'", declaration->symbol, orig_type);
4813                                 }
4814                         }
4815                 }
4816
4817                 /* make sure we don't define a symbol multiple times */
4818                 symbol_t *symbol = declaration->symbol;
4819                 if (symbol != NULL) {
4820                         declaration_t *prev_decl
4821                                 = find_compound_entry(struct_declaration, symbol);
4822
4823                         if (prev_decl != NULL) {
4824                                 assert(prev_decl->symbol == symbol);
4825                                 errorf(&declaration->source_position,
4826                                        "multiple declarations of symbol '%Y' (declared %P)",
4827                                        symbol, &prev_decl->source_position);
4828                         }
4829                 }
4830
4831                 /* append declaration */
4832                 if (last_declaration != NULL) {
4833                         last_declaration->next = declaration;
4834                 } else {
4835                         struct_declaration->scope.declarations = declaration;
4836                 }
4837                 last_declaration = declaration;
4838
4839                 if (token.type != ',')
4840                         break;
4841                 next_token();
4842         }
4843         expect(';');
4844
4845 end_error:
4846         ;
4847 }
4848
4849 static void parse_compound_type_entries(declaration_t *compound_declaration)
4850 {
4851         eat('{');
4852         add_anchor_token('}');
4853
4854         while(token.type != '}' && token.type != T_EOF) {
4855                 declaration_specifiers_t specifiers;
4856                 memset(&specifiers, 0, sizeof(specifiers));
4857                 parse_declaration_specifiers(&specifiers);
4858
4859                 parse_compound_declarators(compound_declaration, &specifiers);
4860         }
4861         rem_anchor_token('}');
4862
4863         if (token.type == T_EOF) {
4864                 errorf(HERE, "EOF while parsing struct");
4865         }
4866         next_token();
4867 }
4868
4869 static type_t *parse_typename(void)
4870 {
4871         declaration_specifiers_t specifiers;
4872         memset(&specifiers, 0, sizeof(specifiers));
4873         parse_declaration_specifiers(&specifiers);
4874         if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4875                 /* TODO: improve error message, user does probably not know what a
4876                  * storage class is...
4877                  */
4878                 errorf(HERE, "typename may not have a storage class");
4879         }
4880
4881         type_t *result = parse_abstract_declarator(specifiers.type);
4882
4883         return result;
4884 }
4885
4886
4887
4888
4889 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4890 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4891                                                           expression_t *left);
4892
4893 typedef struct expression_parser_function_t expression_parser_function_t;
4894 struct expression_parser_function_t {
4895         unsigned                         precedence;
4896         parse_expression_function        parser;
4897         unsigned                         infix_precedence;
4898         parse_expression_infix_function  infix_parser;
4899 };
4900
4901 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4902
4903 /**
4904  * Prints an error message if an expression was expected but not read
4905  */
4906 static expression_t *expected_expression_error(void)
4907 {
4908         /* skip the error message if the error token was read */
4909         if (token.type != T_ERROR) {
4910                 errorf(HERE, "expected expression, got token '%K'", &token);
4911         }
4912         next_token();
4913
4914         return create_invalid_expression();
4915 }
4916
4917 /**
4918  * Parse a string constant.
4919  */
4920 static expression_t *parse_string_const(void)
4921 {
4922         wide_string_t wres;
4923         if (token.type == T_STRING_LITERAL) {
4924                 string_t res = token.v.string;
4925                 next_token();
4926                 while (token.type == T_STRING_LITERAL) {
4927                         res = concat_strings(&res, &token.v.string);
4928                         next_token();
4929                 }
4930                 if (token.type != T_WIDE_STRING_LITERAL) {
4931                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4932                         /* note: that we use type_char_ptr here, which is already the
4933                          * automatic converted type. revert_automatic_type_conversion
4934                          * will construct the array type */
4935                         cnst->base.type    = type_char_ptr;
4936                         cnst->string.value = res;
4937                         return cnst;
4938                 }
4939
4940                 wres = concat_string_wide_string(&res, &token.v.wide_string);
4941         } else {
4942                 wres = token.v.wide_string;
4943         }
4944         next_token();
4945
4946         for (;;) {
4947                 switch (token.type) {
4948                         case T_WIDE_STRING_LITERAL:
4949                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
4950                                 break;
4951
4952                         case T_STRING_LITERAL:
4953                                 wres = concat_wide_string_string(&wres, &token.v.string);
4954                                 break;
4955
4956                         default: {
4957                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4958                                 cnst->base.type         = type_wchar_t_ptr;
4959                                 cnst->wide_string.value = wres;
4960                                 return cnst;
4961                         }
4962                 }
4963                 next_token();
4964         }
4965 }
4966
4967 /**
4968  * Parse an integer constant.
4969  */
4970 static expression_t *parse_int_const(void)
4971 {
4972         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
4973         cnst->base.source_position = *HERE;
4974         cnst->base.type            = token.datatype;
4975         cnst->conste.v.int_value   = token.v.intvalue;
4976
4977         next_token();
4978
4979         return cnst;
4980 }
4981
4982 /**
4983  * Parse a character constant.
4984  */
4985 static expression_t *parse_character_constant(void)
4986 {
4987         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4988
4989         cnst->base.source_position = *HERE;
4990         cnst->base.type            = token.datatype;
4991         cnst->conste.v.character   = token.v.string;
4992
4993         if (cnst->conste.v.character.size != 1) {
4994                 if (warning.multichar && (c_mode & _GNUC)) {
4995                         /* TODO */
4996                         warningf(HERE, "multi-character character constant");
4997                 } else {
4998                         errorf(HERE, "more than 1 characters in character constant");
4999                 }
5000         }
5001         next_token();
5002
5003         return cnst;
5004 }
5005
5006 /**
5007  * Parse a wide character constant.
5008  */
5009 static expression_t *parse_wide_character_constant(void)
5010 {
5011         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5012
5013         cnst->base.source_position    = *HERE;
5014         cnst->base.type               = token.datatype;
5015         cnst->conste.v.wide_character = token.v.wide_string;
5016
5017         if (cnst->conste.v.wide_character.size != 1) {
5018                 if (warning.multichar && (c_mode & _GNUC)) {
5019                         /* TODO */
5020                         warningf(HERE, "multi-character character constant");
5021                 } else {
5022                         errorf(HERE, "more than 1 characters in character constant");
5023                 }
5024         }
5025         next_token();
5026
5027         return cnst;
5028 }
5029
5030 /**
5031  * Parse a float constant.
5032  */
5033 static expression_t *parse_float_const(void)
5034 {
5035         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5036         cnst->base.type            = token.datatype;
5037         cnst->conste.v.float_value = token.v.floatvalue;
5038
5039         next_token();
5040
5041         return cnst;
5042 }
5043
5044 static declaration_t *create_implicit_function(symbol_t *symbol,
5045                 const source_position_t *source_position)
5046 {
5047         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
5048         ntype->function.return_type            = type_int;
5049         ntype->function.unspecified_parameters = true;
5050
5051         type_t *type = typehash_insert(ntype);
5052         if (type != ntype) {
5053                 free_type(ntype);
5054         }
5055
5056         declaration_t *const declaration    = allocate_declaration_zero();
5057         declaration->storage_class          = STORAGE_CLASS_EXTERN;
5058         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5059         declaration->type                   = type;
5060         declaration->symbol                 = symbol;
5061         declaration->source_position        = *source_position;
5062
5063         bool strict_prototypes_old = warning.strict_prototypes;
5064         warning.strict_prototypes  = false;
5065         record_declaration(declaration);
5066         warning.strict_prototypes = strict_prototypes_old;
5067
5068         return declaration;
5069 }
5070
5071 /**
5072  * Creates a return_type (func)(argument_type) function type if not
5073  * already exists.
5074  */
5075 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5076                                     type_t *argument_type2)
5077 {
5078         function_parameter_t *parameter2
5079                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5080         memset(parameter2, 0, sizeof(parameter2[0]));
5081         parameter2->type = argument_type2;
5082
5083         function_parameter_t *parameter1
5084                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5085         memset(parameter1, 0, sizeof(parameter1[0]));
5086         parameter1->type = argument_type1;
5087         parameter1->next = parameter2;
5088
5089         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5090         type->function.return_type = return_type;
5091         type->function.parameters  = parameter1;
5092
5093         type_t *result = typehash_insert(type);
5094         if (result != type) {
5095                 free_type(type);
5096         }
5097
5098         return result;
5099 }
5100
5101 /**
5102  * Creates a return_type (func)(argument_type) function type if not
5103  * already exists.
5104  *
5105  * @param return_type    the return type
5106  * @param argument_type  the argument type
5107  */
5108 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5109 {
5110         function_parameter_t *parameter
5111                 = obstack_alloc(type_obst, sizeof(parameter[0]));
5112         memset(parameter, 0, sizeof(parameter[0]));
5113         parameter->type = argument_type;
5114
5115         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5116         type->function.return_type = return_type;
5117         type->function.parameters  = parameter;
5118
5119         type_t *result = typehash_insert(type);
5120         if (result != type) {
5121                 free_type(type);
5122         }
5123
5124         return result;
5125 }
5126
5127 static type_t *make_function_0_type(type_t *return_type)
5128 {
5129         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5130         type->function.return_type = return_type;
5131         type->function.parameters  = NULL;
5132
5133         type_t *result = typehash_insert(type);
5134         if (result != type) {
5135                 free_type(type);
5136         }
5137
5138         return result;
5139 }
5140
5141 /**
5142  * Creates a function type for some function like builtins.
5143  *
5144  * @param symbol   the symbol describing the builtin
5145  */
5146 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5147 {
5148         switch(symbol->ID) {
5149         case T___builtin_alloca:
5150                 return make_function_1_type(type_void_ptr, type_size_t);
5151         case T___builtin_huge_val:
5152                 return make_function_0_type(type_double);
5153         case T___builtin_nan:
5154                 return make_function_1_type(type_double, type_char_ptr);
5155         case T___builtin_nanf:
5156                 return make_function_1_type(type_float, type_char_ptr);
5157         case T___builtin_nand:
5158                 return make_function_1_type(type_long_double, type_char_ptr);
5159         case T___builtin_va_end:
5160                 return make_function_1_type(type_void, type_valist);
5161         case T___builtin_expect:
5162                 return make_function_2_type(type_long, type_long, type_long);
5163         default:
5164                 internal_errorf(HERE, "not implemented builtin symbol found");
5165         }
5166 }
5167
5168 /**
5169  * Performs automatic type cast as described in Â§ 6.3.2.1.
5170  *
5171  * @param orig_type  the original type
5172  */
5173 static type_t *automatic_type_conversion(type_t *orig_type)
5174 {
5175         type_t *type = skip_typeref(orig_type);
5176         if (is_type_array(type)) {
5177                 array_type_t *array_type   = &type->array;
5178                 type_t       *element_type = array_type->element_type;
5179                 unsigned      qualifiers   = array_type->base.qualifiers;
5180
5181                 return make_pointer_type(element_type, qualifiers);
5182         }
5183
5184         if (is_type_function(type)) {
5185                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5186         }
5187
5188         return orig_type;
5189 }
5190
5191 /**
5192  * reverts the automatic casts of array to pointer types and function
5193  * to function-pointer types as defined Â§ 6.3.2.1
5194  */
5195 type_t *revert_automatic_type_conversion(const expression_t *expression)
5196 {
5197         switch (expression->kind) {
5198                 case EXPR_REFERENCE: return expression->reference.declaration->type;
5199                 case EXPR_SELECT:    return expression->select.compound_entry->type;
5200
5201                 case EXPR_UNARY_DEREFERENCE: {
5202                         const expression_t *const value = expression->unary.value;
5203                         type_t             *const type  = skip_typeref(value->base.type);
5204                         assert(is_type_pointer(type));
5205                         return type->pointer.points_to;
5206                 }
5207
5208                 case EXPR_BUILTIN_SYMBOL:
5209                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5210
5211                 case EXPR_ARRAY_ACCESS: {
5212                         const expression_t *array_ref = expression->array_access.array_ref;
5213                         type_t             *type_left = skip_typeref(array_ref->base.type);
5214                         if (!is_type_valid(type_left))
5215                                 return type_left;
5216                         assert(is_type_pointer(type_left));
5217                         return type_left->pointer.points_to;
5218                 }
5219
5220                 case EXPR_STRING_LITERAL: {
5221                         size_t size = expression->string.value.size;
5222                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5223                 }
5224
5225                 case EXPR_WIDE_STRING_LITERAL: {
5226                         size_t size = expression->wide_string.value.size;
5227                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5228                 }
5229
5230                 case EXPR_COMPOUND_LITERAL:
5231                         return expression->compound_literal.type;
5232
5233                 default: break;
5234         }
5235
5236         return expression->base.type;
5237 }
5238
5239 static expression_t *parse_reference(void)
5240 {
5241         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5242
5243         reference_expression_t *ref = &expression->reference;
5244         symbol_t *const symbol = token.v.symbol;
5245
5246         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5247
5248         source_position_t source_position = token.source_position;
5249         next_token();
5250
5251         if (declaration == NULL) {
5252                 if (! strict_mode && token.type == '(') {
5253                         /* an implicitly defined function */
5254                         if (warning.implicit_function_declaration) {
5255                                 warningf(HERE, "implicit declaration of function '%Y'",
5256                                         symbol);
5257                         }
5258
5259                         declaration = create_implicit_function(symbol,
5260                                                                &source_position);
5261                 } else {
5262                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
5263                         return create_invalid_expression();
5264                 }
5265         }
5266
5267         type_t *type         = declaration->type;
5268
5269         /* we always do the auto-type conversions; the & and sizeof parser contains
5270          * code to revert this! */
5271         type = automatic_type_conversion(type);
5272
5273         ref->declaration = declaration;
5274         ref->base.type   = type;
5275
5276         /* this declaration is used */
5277         declaration->used = true;
5278
5279         /* check for deprecated functions */
5280         if (declaration->deprecated != 0) {
5281                 const char *prefix = "";
5282                 if (is_type_function(declaration->type))
5283                         prefix = "function ";
5284
5285                 if (declaration->deprecated_string != NULL) {
5286                         warningf(&source_position,
5287                                 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5288                                 declaration->deprecated_string);
5289                 } else {
5290                         warningf(&source_position,
5291                                 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5292                 }
5293         }
5294
5295         return expression;
5296 }
5297
5298 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5299 {
5300         (void) expression;
5301         (void) dest_type;
5302         /* TODO check if explicit cast is allowed and issue warnings/errors */
5303 }
5304
5305 static expression_t *parse_compound_literal(type_t *type)
5306 {
5307         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5308
5309         parse_initializer_env_t env;
5310         env.type             = type;
5311         env.declaration      = NULL;
5312         env.must_be_constant = false;
5313         initializer_t *initializer = parse_initializer(&env);
5314         type = env.type;
5315
5316         expression->compound_literal.initializer = initializer;
5317         expression->compound_literal.type        = type;
5318         expression->base.type                    = automatic_type_conversion(type);
5319
5320         return expression;
5321 }
5322
5323 /**
5324  * Parse a cast expression.
5325  */
5326 static expression_t *parse_cast(void)
5327 {
5328         source_position_t source_position = token.source_position;
5329
5330         type_t *type  = parse_typename();
5331
5332         /* matching add_anchor_token() is at call site */
5333         rem_anchor_token(')');
5334         expect(')');
5335
5336         if (token.type == '{') {
5337                 return parse_compound_literal(type);
5338         }
5339
5340         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5341         cast->base.source_position = source_position;
5342
5343         expression_t *value = parse_sub_expression(20);
5344
5345         check_cast_allowed(value, type);
5346
5347         cast->base.type   = type;
5348         cast->unary.value = value;
5349
5350         return cast;
5351 end_error:
5352         return create_invalid_expression();
5353 }
5354
5355 /**
5356  * Parse a statement expression.
5357  */
5358 static expression_t *parse_statement_expression(void)
5359 {
5360         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5361
5362         statement_t *statement           = parse_compound_statement(true);
5363         expression->statement.statement  = statement;
5364         expression->base.source_position = statement->base.source_position;
5365
5366         /* find last statement and use its type */
5367         type_t *type = type_void;
5368         const statement_t *stmt = statement->compound.statements;
5369         if (stmt != NULL) {
5370                 while (stmt->base.next != NULL)
5371                         stmt = stmt->base.next;
5372
5373                 if (stmt->kind == STATEMENT_EXPRESSION) {
5374                         type = stmt->expression.expression->base.type;
5375                 }
5376         } else {
5377                 warningf(&expression->base.source_position, "empty statement expression ({})");
5378         }
5379         expression->base.type = type;
5380
5381         expect(')');
5382
5383         return expression;
5384 end_error:
5385         return create_invalid_expression();
5386 }
5387
5388 /**
5389  * Parse a braced expression.
5390  */
5391 static expression_t *parse_brace_expression(void)
5392 {
5393         eat('(');
5394         add_anchor_token(')');
5395
5396         switch(token.type) {
5397         case '{':
5398                 /* gcc extension: a statement expression */
5399                 return parse_statement_expression();
5400
5401         TYPE_QUALIFIERS
5402         TYPE_SPECIFIERS
5403                 return parse_cast();
5404         case T_IDENTIFIER:
5405                 if (is_typedef_symbol(token.v.symbol)) {
5406                         return parse_cast();
5407                 }
5408         }
5409
5410         expression_t *result = parse_expression();
5411         rem_anchor_token(')');
5412         expect(')');
5413
5414         return result;
5415 end_error:
5416         return create_invalid_expression();
5417 }
5418
5419 static expression_t *parse_function_keyword(void)
5420 {
5421         next_token();
5422         /* TODO */
5423
5424         if (current_function == NULL) {
5425                 errorf(HERE, "'__func__' used outside of a function");
5426         }
5427
5428         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5429         expression->base.type     = type_char_ptr;
5430         expression->funcname.kind = FUNCNAME_FUNCTION;
5431
5432         return expression;
5433 }
5434
5435 static expression_t *parse_pretty_function_keyword(void)
5436 {
5437         eat(T___PRETTY_FUNCTION__);
5438
5439         if (current_function == NULL) {
5440                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5441         }
5442
5443         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5444         expression->base.type     = type_char_ptr;
5445         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5446
5447         return expression;
5448 }
5449
5450 static expression_t *parse_funcsig_keyword(void)
5451 {
5452         eat(T___FUNCSIG__);
5453
5454         if (current_function == NULL) {
5455                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5456         }
5457
5458         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5459         expression->base.type     = type_char_ptr;
5460         expression->funcname.kind = FUNCNAME_FUNCSIG;
5461
5462         return expression;
5463 }
5464
5465 static expression_t *parse_funcdname_keyword(void)
5466 {
5467         eat(T___FUNCDNAME__);
5468
5469         if (current_function == NULL) {
5470                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5471         }
5472
5473         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5474         expression->base.type     = type_char_ptr;
5475         expression->funcname.kind = FUNCNAME_FUNCDNAME;
5476
5477         return expression;
5478 }
5479
5480 static designator_t *parse_designator(void)
5481 {
5482         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
5483         result->source_position = *HERE;
5484
5485         if (token.type != T_IDENTIFIER) {
5486                 parse_error_expected("while parsing member designator",
5487                                      T_IDENTIFIER, NULL);
5488                 return NULL;
5489         }
5490         result->symbol = token.v.symbol;
5491         next_token();
5492
5493         designator_t *last_designator = result;
5494         while(true) {
5495                 if (token.type == '.') {
5496                         next_token();
5497                         if (token.type != T_IDENTIFIER) {
5498                                 parse_error_expected("while parsing member designator",
5499                                                      T_IDENTIFIER, NULL);
5500                                 return NULL;
5501                         }
5502                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5503                         designator->source_position = *HERE;
5504                         designator->symbol          = token.v.symbol;
5505                         next_token();
5506
5507                         last_designator->next = designator;
5508                         last_designator       = designator;
5509                         continue;
5510                 }
5511                 if (token.type == '[') {
5512                         next_token();
5513                         add_anchor_token(']');
5514                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5515                         designator->source_position = *HERE;
5516                         designator->array_index     = parse_expression();
5517                         rem_anchor_token(']');
5518                         expect(']');
5519                         if (designator->array_index == NULL) {
5520                                 return NULL;
5521                         }
5522
5523                         last_designator->next = designator;
5524                         last_designator       = designator;
5525                         continue;
5526                 }
5527                 break;
5528         }
5529
5530         return result;
5531 end_error:
5532         return NULL;
5533 }
5534
5535 /**
5536  * Parse the __builtin_offsetof() expression.
5537  */
5538 static expression_t *parse_offsetof(void)
5539 {
5540         eat(T___builtin_offsetof);
5541
5542         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5543         expression->base.type    = type_size_t;
5544
5545         expect('(');
5546         add_anchor_token(',');
5547         type_t *type = parse_typename();
5548         rem_anchor_token(',');
5549         expect(',');
5550         add_anchor_token(')');
5551         designator_t *designator = parse_designator();
5552         rem_anchor_token(')');
5553         expect(')');
5554
5555         expression->offsetofe.type       = type;
5556         expression->offsetofe.designator = designator;
5557
5558         type_path_t path;
5559         memset(&path, 0, sizeof(path));
5560         path.top_type = type;
5561         path.path     = NEW_ARR_F(type_path_entry_t, 0);
5562
5563         descend_into_subtype(&path);
5564
5565         if (!walk_designator(&path, designator, true)) {
5566                 return create_invalid_expression();
5567         }
5568
5569         DEL_ARR_F(path.path);
5570
5571         return expression;
5572 end_error:
5573         return create_invalid_expression();
5574 }
5575
5576 /**
5577  * Parses a _builtin_va_start() expression.
5578  */
5579 static expression_t *parse_va_start(void)
5580 {
5581         eat(T___builtin_va_start);
5582
5583         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5584
5585         expect('(');
5586         add_anchor_token(',');
5587         expression->va_starte.ap = parse_assignment_expression();
5588         rem_anchor_token(',');
5589         expect(',');
5590         expression_t *const expr = parse_assignment_expression();
5591         if (expr->kind == EXPR_REFERENCE) {
5592                 declaration_t *const decl = expr->reference.declaration;
5593                 if (decl == NULL)
5594                         return create_invalid_expression();
5595                 if (decl->parent_scope == &current_function->scope &&
5596                     decl->next == NULL) {
5597                         expression->va_starte.parameter = decl;
5598                         expect(')');
5599                         return expression;
5600                 }
5601         }
5602         errorf(&expr->base.source_position,
5603                "second argument of 'va_start' must be last parameter of the current function");
5604 end_error:
5605         return create_invalid_expression();
5606 }
5607
5608 /**
5609  * Parses a _builtin_va_arg() expression.
5610  */
5611 static expression_t *parse_va_arg(void)
5612 {
5613         eat(T___builtin_va_arg);
5614
5615         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5616
5617         expect('(');
5618         expression->va_arge.ap = parse_assignment_expression();
5619         expect(',');
5620         expression->base.type = parse_typename();
5621         expect(')');
5622
5623         return expression;
5624 end_error:
5625         return create_invalid_expression();
5626 }
5627
5628 static expression_t *parse_builtin_symbol(void)
5629 {
5630         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5631
5632         symbol_t *symbol = token.v.symbol;
5633
5634         expression->builtin_symbol.symbol = symbol;
5635         next_token();
5636
5637         type_t *type = get_builtin_symbol_type(symbol);
5638         type = automatic_type_conversion(type);
5639
5640         expression->base.type = type;
5641         return expression;
5642 }
5643
5644 /**
5645  * Parses a __builtin_constant() expression.
5646  */
5647 static expression_t *parse_builtin_constant(void)
5648 {
5649         eat(T___builtin_constant_p);
5650
5651         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5652
5653         expect('(');
5654         add_anchor_token(')');
5655         expression->builtin_constant.value = parse_assignment_expression();
5656         rem_anchor_token(')');
5657         expect(')');
5658         expression->base.type = type_int;
5659
5660         return expression;
5661 end_error:
5662         return create_invalid_expression();
5663 }
5664
5665 /**
5666  * Parses a __builtin_prefetch() expression.
5667  */
5668 static expression_t *parse_builtin_prefetch(void)
5669 {
5670         eat(T___builtin_prefetch);
5671
5672         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5673
5674         expect('(');
5675         add_anchor_token(')');
5676         expression->builtin_prefetch.adr = parse_assignment_expression();
5677         if (token.type == ',') {
5678                 next_token();
5679                 expression->builtin_prefetch.rw = parse_assignment_expression();
5680         }
5681         if (token.type == ',') {
5682                 next_token();
5683                 expression->builtin_prefetch.locality = parse_assignment_expression();
5684         }
5685         rem_anchor_token(')');
5686         expect(')');
5687         expression->base.type = type_void;
5688
5689         return expression;
5690 end_error:
5691         return create_invalid_expression();
5692 }
5693
5694 /**
5695  * Parses a __builtin_is_*() compare expression.
5696  */
5697 static expression_t *parse_compare_builtin(void)
5698 {
5699         expression_t *expression;
5700
5701         switch(token.type) {
5702         case T___builtin_isgreater:
5703                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5704                 break;
5705         case T___builtin_isgreaterequal:
5706                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5707                 break;
5708         case T___builtin_isless:
5709                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5710                 break;
5711         case T___builtin_islessequal:
5712                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5713                 break;
5714         case T___builtin_islessgreater:
5715                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5716                 break;
5717         case T___builtin_isunordered:
5718                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5719                 break;
5720         default:
5721                 internal_errorf(HERE, "invalid compare builtin found");
5722                 break;
5723         }
5724         expression->base.source_position = *HERE;
5725         next_token();
5726
5727         expect('(');
5728         expression->binary.left = parse_assignment_expression();
5729         expect(',');
5730         expression->binary.right = parse_assignment_expression();
5731         expect(')');
5732
5733         type_t *const orig_type_left  = expression->binary.left->base.type;
5734         type_t *const orig_type_right = expression->binary.right->base.type;
5735
5736         type_t *const type_left  = skip_typeref(orig_type_left);
5737         type_t *const type_right = skip_typeref(orig_type_right);
5738         if (!is_type_float(type_left) && !is_type_float(type_right)) {
5739                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5740                         type_error_incompatible("invalid operands in comparison",
5741                                 &expression->base.source_position, orig_type_left, orig_type_right);
5742                 }
5743         } else {
5744                 semantic_comparison(&expression->binary);
5745         }
5746
5747         return expression;
5748 end_error:
5749         return create_invalid_expression();
5750 }
5751
5752 #if 0
5753 /**
5754  * Parses a __builtin_expect() expression.
5755  */
5756 static expression_t *parse_builtin_expect(void)
5757 {
5758         eat(T___builtin_expect);
5759
5760         expression_t *expression
5761                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5762
5763         expect('(');
5764         expression->binary.left = parse_assignment_expression();
5765         expect(',');
5766         expression->binary.right = parse_constant_expression();
5767         expect(')');
5768
5769         expression->base.type = expression->binary.left->base.type;
5770
5771         return expression;
5772 end_error:
5773         return create_invalid_expression();
5774 }
5775 #endif
5776
5777 /**
5778  * Parses a MS assume() expression.
5779  */
5780 static expression_t *parse_assume(void) {
5781         eat(T__assume);
5782
5783         expression_t *expression
5784                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5785
5786         expect('(');
5787         add_anchor_token(')');
5788         expression->unary.value = parse_assignment_expression();
5789         rem_anchor_token(')');
5790         expect(')');
5791
5792         expression->base.type = type_void;
5793         return expression;
5794 end_error:
5795         return create_invalid_expression();
5796 }
5797
5798 /**
5799  * Parse a microsoft __noop expression.
5800  */
5801 static expression_t *parse_noop_expression(void) {
5802         source_position_t source_position = *HERE;
5803         eat(T___noop);
5804
5805         if (token.type == '(') {
5806                 /* parse arguments */
5807                 eat('(');
5808                 add_anchor_token(')');
5809                 add_anchor_token(',');
5810
5811                 if (token.type != ')') {
5812                         while(true) {
5813                                 (void)parse_assignment_expression();
5814                                 if (token.type != ',')
5815                                         break;
5816                                 next_token();
5817                         }
5818                 }
5819         }
5820         rem_anchor_token(',');
5821         rem_anchor_token(')');
5822         expect(')');
5823
5824         /* the result is a (int)0 */
5825         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5826         cnst->base.source_position = source_position;
5827         cnst->base.type            = type_int;
5828         cnst->conste.v.int_value   = 0;
5829         cnst->conste.is_ms_noop    = true;
5830
5831         return cnst;
5832
5833 end_error:
5834         return create_invalid_expression();
5835 }
5836
5837 /**
5838  * Parses a primary expression.
5839  */
5840 static expression_t *parse_primary_expression(void)
5841 {
5842         switch (token.type) {
5843                 case T_INTEGER:                  return parse_int_const();
5844                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
5845                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
5846                 case T_FLOATINGPOINT:            return parse_float_const();
5847                 case T_STRING_LITERAL:
5848                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
5849                 case T_IDENTIFIER:               return parse_reference();
5850                 case T___FUNCTION__:
5851                 case T___func__:                 return parse_function_keyword();
5852                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
5853                 case T___FUNCSIG__:              return parse_funcsig_keyword();
5854                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
5855                 case T___builtin_offsetof:       return parse_offsetof();
5856                 case T___builtin_va_start:       return parse_va_start();
5857                 case T___builtin_va_arg:         return parse_va_arg();
5858                 case T___builtin_expect:
5859                 case T___builtin_alloca:
5860                 case T___builtin_nan:
5861                 case T___builtin_nand:
5862                 case T___builtin_nanf:
5863                 case T___builtin_huge_val:
5864                 case T___builtin_va_end:         return parse_builtin_symbol();
5865                 case T___builtin_isgreater:
5866                 case T___builtin_isgreaterequal:
5867                 case T___builtin_isless:
5868                 case T___builtin_islessequal:
5869                 case T___builtin_islessgreater:
5870                 case T___builtin_isunordered:    return parse_compare_builtin();
5871                 case T___builtin_constant_p:     return parse_builtin_constant();
5872                 case T___builtin_prefetch:       return parse_builtin_prefetch();
5873                 case T__assume:                  return parse_assume();
5874
5875                 case '(':                        return parse_brace_expression();
5876                 case T___noop:                   return parse_noop_expression();
5877         }
5878
5879         errorf(HERE, "unexpected token %K, expected an expression", &token);
5880         return create_invalid_expression();
5881 }
5882
5883 /**
5884  * Check if the expression has the character type and issue a warning then.
5885  */
5886 static void check_for_char_index_type(const expression_t *expression) {
5887         type_t       *const type      = expression->base.type;
5888         const type_t *const base_type = skip_typeref(type);
5889
5890         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5891                         warning.char_subscripts) {
5892                 warningf(&expression->base.source_position,
5893                          "array subscript has type '%T'", type);
5894         }
5895 }
5896
5897 static expression_t *parse_array_expression(unsigned precedence,
5898                                             expression_t *left)
5899 {
5900         (void) precedence;
5901
5902         eat('[');
5903         add_anchor_token(']');
5904
5905         expression_t *inside = parse_expression();
5906
5907         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5908
5909         array_access_expression_t *array_access = &expression->array_access;
5910
5911         type_t *const orig_type_left   = left->base.type;
5912         type_t *const orig_type_inside = inside->base.type;
5913
5914         type_t *const type_left   = skip_typeref(orig_type_left);
5915         type_t *const type_inside = skip_typeref(orig_type_inside);
5916
5917         type_t *return_type;
5918         if (is_type_pointer(type_left)) {
5919                 return_type             = type_left->pointer.points_to;
5920                 array_access->array_ref = left;
5921                 array_access->index     = inside;
5922                 check_for_char_index_type(inside);
5923         } else if (is_type_pointer(type_inside)) {
5924                 return_type             = type_inside->pointer.points_to;
5925                 array_access->array_ref = inside;
5926                 array_access->index     = left;
5927                 array_access->flipped   = true;
5928                 check_for_char_index_type(left);
5929         } else {
5930                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5931                         errorf(HERE,
5932                                 "array access on object with non-pointer types '%T', '%T'",
5933                                 orig_type_left, orig_type_inside);
5934                 }
5935                 return_type             = type_error_type;
5936                 array_access->array_ref = create_invalid_expression();
5937         }
5938
5939         rem_anchor_token(']');
5940         if (token.type != ']') {
5941                 parse_error_expected("Problem while parsing array access", ']', NULL);
5942                 return expression;
5943         }
5944         next_token();
5945
5946         return_type           = automatic_type_conversion(return_type);
5947         expression->base.type = return_type;
5948
5949         return expression;
5950 }
5951
5952 static expression_t *parse_typeprop(expression_kind_t const kind,
5953                                     source_position_t const pos,
5954                                     unsigned const precedence)
5955 {
5956         expression_t *tp_expression = allocate_expression_zero(kind);
5957         tp_expression->base.type            = type_size_t;
5958         tp_expression->base.source_position = pos;
5959
5960         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5961
5962         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5963                 next_token();
5964                 add_anchor_token(')');
5965                 type_t* const orig_type = parse_typename();
5966                 tp_expression->typeprop.type = orig_type;
5967
5968                 type_t const* const type = skip_typeref(orig_type);
5969                 char const* const wrong_type =
5970                         is_type_incomplete(type)    ? "incomplete"          :
5971                         type->kind == TYPE_FUNCTION ? "function designator" :
5972                         type->kind == TYPE_BITFIELD ? "bitfield"            :
5973                         NULL;
5974                 if (wrong_type != NULL) {
5975                         errorf(&pos, "operand of %s expression must not be %s type '%T'",
5976                                what, wrong_type, type);
5977                 }
5978
5979                 rem_anchor_token(')');
5980                 expect(')');
5981         } else {
5982                 expression_t *expression = parse_sub_expression(precedence);
5983
5984                 type_t* const orig_type = revert_automatic_type_conversion(expression);
5985                 expression->base.type = orig_type;
5986
5987                 type_t const* const type = skip_typeref(orig_type);
5988                 char const* const wrong_type =
5989                         is_type_incomplete(type)    ? "incomplete"          :
5990                         type->kind == TYPE_FUNCTION ? "function designator" :
5991                         type->kind == TYPE_BITFIELD ? "bitfield"            :
5992                         NULL;
5993                 if (wrong_type != NULL) {
5994                         errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5995                 }
5996
5997                 tp_expression->typeprop.type          = expression->base.type;
5998                 tp_expression->typeprop.tp_expression = expression;
5999         }
6000
6001         return tp_expression;
6002 end_error:
6003         return create_invalid_expression();
6004 }
6005
6006 static expression_t *parse_sizeof(unsigned precedence)
6007 {
6008         source_position_t pos = *HERE;
6009         eat(T_sizeof);
6010         return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6011 }
6012
6013 static expression_t *parse_alignof(unsigned precedence)
6014 {
6015         source_position_t pos = *HERE;
6016         eat(T___alignof__);
6017         return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6018 }
6019
6020 static expression_t *parse_select_expression(unsigned precedence,
6021                                              expression_t *compound)
6022 {
6023         (void) precedence;
6024         assert(token.type == '.' || token.type == T_MINUSGREATER);
6025
6026         bool is_pointer = (token.type == T_MINUSGREATER);
6027         next_token();
6028
6029         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
6030         select->select.compound = compound;
6031
6032         if (token.type != T_IDENTIFIER) {
6033                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6034                 return select;
6035         }
6036         symbol_t *symbol      = token.v.symbol;
6037         select->select.symbol = symbol;
6038         next_token();
6039
6040         type_t *const orig_type = compound->base.type;
6041         type_t *const type      = skip_typeref(orig_type);
6042
6043         type_t *type_left = type;
6044         if (is_pointer) {
6045                 if (!is_type_pointer(type)) {
6046                         if (is_type_valid(type)) {
6047                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6048                         }
6049                         return create_invalid_expression();
6050                 }
6051                 type_left = type->pointer.points_to;
6052         }
6053         type_left = skip_typeref(type_left);
6054
6055         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6056             type_left->kind != TYPE_COMPOUND_UNION) {
6057                 if (is_type_valid(type_left)) {
6058                         errorf(HERE, "request for member '%Y' in something not a struct or "
6059                                "union, but '%T'", symbol, type_left);
6060                 }
6061                 return create_invalid_expression();
6062         }
6063
6064         declaration_t *const declaration = type_left->compound.declaration;
6065
6066         if (!declaration->init.complete) {
6067                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6068                        symbol, type_left);
6069                 return create_invalid_expression();
6070         }
6071
6072         declaration_t *iter = find_compound_entry(declaration, symbol);
6073         if (iter == NULL) {
6074                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6075                 return create_invalid_expression();
6076         }
6077
6078         /* we always do the auto-type conversions; the & and sizeof parser contains
6079          * code to revert this! */
6080         type_t *expression_type = automatic_type_conversion(iter->type);
6081
6082         select->select.compound_entry = iter;
6083         select->base.type             = expression_type;
6084
6085         type_t *skipped = skip_typeref(iter->type);
6086         if (skipped->kind == TYPE_BITFIELD) {
6087                 select->base.type = skipped->bitfield.base_type;
6088         }
6089
6090         return select;
6091 }
6092
6093 static void check_call_argument(const function_parameter_t *parameter,
6094                                 call_argument_t *argument)
6095 {
6096         type_t         *expected_type      = parameter->type;
6097         type_t         *expected_type_skip = skip_typeref(expected_type);
6098         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
6099         expression_t   *arg_expr           = argument->expression;
6100
6101         /* handle transparent union gnu extension */
6102         if (is_type_union(expected_type_skip)
6103                         && (expected_type_skip->base.modifiers
6104                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6105                 declaration_t  *union_decl = expected_type_skip->compound.declaration;
6106
6107                 declaration_t *declaration = union_decl->scope.declarations;
6108                 type_t        *best_type   = NULL;
6109                 for ( ; declaration != NULL; declaration = declaration->next) {
6110                         type_t *decl_type = declaration->type;
6111                         error = semantic_assign(decl_type, arg_expr);
6112                         if (error == ASSIGN_ERROR_INCOMPATIBLE
6113                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6114                                 continue;
6115
6116                         if (error == ASSIGN_SUCCESS) {
6117                                 best_type = decl_type;
6118                         } else if (best_type == NULL) {
6119                                 best_type = decl_type;
6120                         }
6121                 }
6122
6123                 if (best_type != NULL) {
6124                         expected_type = best_type;
6125                 }
6126         }
6127
6128         error                = semantic_assign(expected_type, arg_expr);
6129         argument->expression = create_implicit_cast(argument->expression,
6130                                                     expected_type);
6131
6132         /* TODO report exact scope in error messages (like "in 3rd parameter") */
6133         report_assign_error(error, expected_type, arg_expr,     "function call",
6134                             &arg_expr->base.source_position);
6135 }
6136
6137 /**
6138  * Parse a call expression, ie. expression '( ... )'.
6139  *
6140  * @param expression  the function address
6141  */
6142 static expression_t *parse_call_expression(unsigned precedence,
6143                                            expression_t *expression)
6144 {
6145         (void) precedence;
6146         expression_t *result = allocate_expression_zero(EXPR_CALL);
6147         result->base.source_position = expression->base.source_position;
6148
6149         call_expression_t *call = &result->call;
6150         call->function          = expression;
6151
6152         type_t *const orig_type = expression->base.type;
6153         type_t *const type      = skip_typeref(orig_type);
6154
6155         function_type_t *function_type = NULL;
6156         if (is_type_pointer(type)) {
6157                 type_t *const to_type = skip_typeref(type->pointer.points_to);
6158
6159                 if (is_type_function(to_type)) {
6160                         function_type   = &to_type->function;
6161                         call->base.type = function_type->return_type;
6162                 }
6163         }
6164
6165         if (function_type == NULL && is_type_valid(type)) {
6166                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6167         }
6168
6169         /* parse arguments */
6170         eat('(');
6171         add_anchor_token(')');
6172         add_anchor_token(',');
6173
6174         if (token.type != ')') {
6175                 call_argument_t *last_argument = NULL;
6176
6177                 while(true) {
6178                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6179
6180                         argument->expression = parse_assignment_expression();
6181                         if (last_argument == NULL) {
6182                                 call->arguments = argument;
6183                         } else {
6184                                 last_argument->next = argument;
6185                         }
6186                         last_argument = argument;
6187
6188                         if (token.type != ',')
6189                                 break;
6190                         next_token();
6191                 }
6192         }
6193         rem_anchor_token(',');
6194         rem_anchor_token(')');
6195         expect(')');
6196
6197         if (function_type == NULL)
6198                 return result;
6199
6200         function_parameter_t *parameter = function_type->parameters;
6201         call_argument_t      *argument  = call->arguments;
6202         if (!function_type->unspecified_parameters) {
6203                 for( ; parameter != NULL && argument != NULL;
6204                                 parameter = parameter->next, argument = argument->next) {
6205                         check_call_argument(parameter, argument);
6206                 }
6207
6208                 if (parameter != NULL) {
6209                         errorf(HERE, "too few arguments to function '%E'", expression);
6210                 } else if (argument != NULL && !function_type->variadic) {
6211                         errorf(HERE, "too many arguments to function '%E'", expression);
6212                 }
6213         }
6214
6215         /* do default promotion */
6216         for( ; argument != NULL; argument = argument->next) {
6217                 type_t *type = argument->expression->base.type;
6218
6219                 type = get_default_promoted_type(type);
6220
6221                 argument->expression
6222                         = create_implicit_cast(argument->expression, type);
6223         }
6224
6225         check_format(&result->call);
6226
6227         return result;
6228 end_error:
6229         return create_invalid_expression();
6230 }
6231
6232 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6233
6234 static bool same_compound_type(const type_t *type1, const type_t *type2)
6235 {
6236         return
6237                 is_type_compound(type1) &&
6238                 type1->kind == type2->kind &&
6239                 type1->compound.declaration == type2->compound.declaration;
6240 }
6241
6242 /**
6243  * Parse a conditional expression, ie. 'expression ? ... : ...'.
6244  *
6245  * @param expression  the conditional expression
6246  */
6247 static expression_t *parse_conditional_expression(unsigned precedence,
6248                                                   expression_t *expression)
6249 {
6250         eat('?');
6251         add_anchor_token(':');
6252
6253         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6254
6255         conditional_expression_t *conditional = &result->conditional;
6256         conditional->condition = expression;
6257
6258         /* 6.5.15.2 */
6259         type_t *const condition_type_orig = expression->base.type;
6260         type_t *const condition_type      = skip_typeref(condition_type_orig);
6261         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6262                 type_error("expected a scalar type in conditional condition",
6263                            &expression->base.source_position, condition_type_orig);
6264         }
6265
6266         expression_t *true_expression = parse_expression();
6267         rem_anchor_token(':');
6268         expect(':');
6269         expression_t *false_expression = parse_sub_expression(precedence);
6270
6271         type_t *const orig_true_type  = true_expression->base.type;
6272         type_t *const orig_false_type = false_expression->base.type;
6273         type_t *const true_type       = skip_typeref(orig_true_type);
6274         type_t *const false_type      = skip_typeref(orig_false_type);
6275
6276         /* 6.5.15.3 */
6277         type_t *result_type;
6278         if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6279                 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6280                 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6281                     || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6282                         warningf(&expression->base.source_position,
6283                                         "ISO C forbids conditional expression with only one void side");
6284                 }
6285                 result_type = type_void;
6286         } else if (is_type_arithmetic(true_type)
6287                    && is_type_arithmetic(false_type)) {
6288                 result_type = semantic_arithmetic(true_type, false_type);
6289
6290                 true_expression  = create_implicit_cast(true_expression, result_type);
6291                 false_expression = create_implicit_cast(false_expression, result_type);
6292
6293                 conditional->true_expression  = true_expression;
6294                 conditional->false_expression = false_expression;
6295                 conditional->base.type        = result_type;
6296         } else if (same_compound_type(true_type, false_type)) {
6297                 /* just take 1 of the 2 types */
6298                 result_type = true_type;
6299         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6300                 type_t *pointer_type;
6301                 type_t *other_type;
6302                 expression_t *other_expression;
6303                 if (is_type_pointer(true_type) &&
6304                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6305                         pointer_type     = true_type;
6306                         other_type       = false_type;
6307                         other_expression = false_expression;
6308                 } else {
6309                         pointer_type     = false_type;
6310                         other_type       = true_type;
6311                         other_expression = true_expression;
6312                 }
6313
6314                 if (is_null_pointer_constant(other_expression)) {
6315                         result_type = pointer_type;
6316                 } else if (is_type_pointer(other_type)) {
6317                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6318                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
6319
6320                         type_t *to;
6321                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6322                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6323                                 to = type_void;
6324                         } else if (types_compatible(get_unqualified_type(to1),
6325                                                     get_unqualified_type(to2))) {
6326                                 to = to1;
6327                         } else {
6328                                 warningf(&expression->base.source_position,
6329                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
6330                                         true_type, false_type);
6331                                 to = type_void;
6332                         }
6333
6334                         type_t *const copy = duplicate_type(to);
6335                         copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6336
6337                         type_t *const type = typehash_insert(copy);
6338                         if (type != copy)
6339                                 free_type(copy);
6340
6341                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6342                 } else if (is_type_integer(other_type)) {
6343                         warningf(&expression->base.source_position,
6344                                         "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6345                         result_type = pointer_type;
6346                 } else {
6347                         type_error_incompatible("while parsing conditional",
6348                                         &expression->base.source_position, true_type, false_type);
6349                         result_type = type_error_type;
6350                 }
6351         } else {
6352                 /* TODO: one pointer to void*, other some pointer */
6353
6354                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6355                         type_error_incompatible("while parsing conditional",
6356                                                 &expression->base.source_position, true_type,
6357                                                 false_type);
6358                 }
6359                 result_type = type_error_type;
6360         }
6361
6362         conditional->true_expression
6363                 = create_implicit_cast(true_expression, result_type);
6364         conditional->false_expression
6365                 = create_implicit_cast(false_expression, result_type);
6366         conditional->base.type = result_type;
6367         return result;
6368 end_error:
6369         return create_invalid_expression();
6370 }
6371
6372 /**
6373  * Parse an extension expression.
6374  */
6375 static expression_t *parse_extension(unsigned precedence)
6376 {
6377         eat(T___extension__);
6378
6379         /* TODO enable extensions */
6380         expression_t *expression = parse_sub_expression(precedence);
6381         /* TODO disable extensions */
6382         return expression;
6383 }
6384
6385 /**
6386  * Parse a __builtin_classify_type() expression.
6387  */
6388 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6389 {
6390         eat(T___builtin_classify_type);
6391
6392         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6393         result->base.type    = type_int;
6394
6395         expect('(');
6396         add_anchor_token(')');
6397         expression_t *expression = parse_sub_expression(precedence);
6398         rem_anchor_token(')');
6399         expect(')');
6400         result->classify_type.type_expression = expression;
6401
6402         return result;
6403 end_error:
6404         return create_invalid_expression();
6405 }
6406
6407 static void check_pointer_arithmetic(const source_position_t *source_position,
6408                                      type_t *pointer_type,
6409                                      type_t *orig_pointer_type)
6410 {
6411         type_t *points_to = pointer_type->pointer.points_to;
6412         points_to = skip_typeref(points_to);
6413
6414         if (is_type_incomplete(points_to) &&
6415                         (! (c_mode & _GNUC)
6416                          || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6417                 errorf(source_position,
6418                            "arithmetic with pointer to incomplete type '%T' not allowed",
6419                            orig_pointer_type);
6420         } else if (is_type_function(points_to)) {
6421                 errorf(source_position,
6422                            "arithmetic with pointer to function type '%T' not allowed",
6423                            orig_pointer_type);
6424         }
6425 }
6426
6427 static void semantic_incdec(unary_expression_t *expression)
6428 {
6429         type_t *const orig_type = expression->value->base.type;
6430         type_t *const type      = skip_typeref(orig_type);
6431         if (is_type_pointer(type)) {
6432                 check_pointer_arithmetic(&expression->base.source_position,
6433                                          type, orig_type);
6434         } else if (!is_type_real(type) && is_type_valid(type)) {
6435                 /* TODO: improve error message */
6436                 errorf(HERE, "operation needs an arithmetic or pointer type");
6437         }
6438         expression->base.type = orig_type;
6439 }
6440
6441 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6442 {
6443         type_t *const orig_type = expression->value->base.type;
6444         type_t *const type      = skip_typeref(orig_type);
6445         if (!is_type_arithmetic(type)) {
6446                 if (is_type_valid(type)) {
6447                         /* TODO: improve error message */
6448                         errorf(HERE, "operation needs an arithmetic type");
6449                 }
6450                 return;
6451         }
6452
6453         expression->base.type = orig_type;
6454 }
6455
6456 static void semantic_unexpr_scalar(unary_expression_t *expression)
6457 {
6458         type_t *const orig_type = expression->value->base.type;
6459         type_t *const type      = skip_typeref(orig_type);
6460         if (!is_type_scalar(type)) {
6461                 if (is_type_valid(type)) {
6462                         errorf(HERE, "operand of ! must be of scalar type");
6463                 }
6464                 return;
6465         }
6466
6467         expression->base.type = orig_type;
6468 }
6469
6470 static void semantic_unexpr_integer(unary_expression_t *expression)
6471 {
6472         type_t *const orig_type = expression->value->base.type;
6473         type_t *const type      = skip_typeref(orig_type);
6474         if (!is_type_integer(type)) {
6475                 if (is_type_valid(type)) {
6476                         errorf(HERE, "operand of ~ must be of integer type");
6477                 }
6478                 return;
6479         }
6480
6481         expression->base.type = orig_type;
6482 }
6483
6484 static void semantic_dereference(unary_expression_t *expression)
6485 {
6486         type_t *const orig_type = expression->value->base.type;
6487         type_t *const type      = skip_typeref(orig_type);
6488         if (!is_type_pointer(type)) {
6489                 if (is_type_valid(type)) {
6490                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6491                 }
6492                 return;
6493         }
6494
6495         type_t *result_type   = type->pointer.points_to;
6496         result_type           = automatic_type_conversion(result_type);
6497         expression->base.type = result_type;
6498 }
6499
6500 static void set_address_taken(expression_t *expression, bool may_be_register)
6501 {
6502         if (expression->kind != EXPR_REFERENCE)
6503                 return;
6504
6505         declaration_t *const declaration = expression->reference.declaration;
6506         /* happens for parse errors */
6507         if (declaration == NULL)
6508                 return;
6509
6510         if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6511                 errorf(&expression->base.source_position,
6512                                 "address of register variable '%Y' requested",
6513                                 declaration->symbol);
6514         } else {
6515                 declaration->address_taken = 1;
6516         }
6517 }
6518
6519 /**
6520  * Check the semantic of the address taken expression.
6521  */
6522 static void semantic_take_addr(unary_expression_t *expression)
6523 {
6524         expression_t *value = expression->value;
6525         value->base.type    = revert_automatic_type_conversion(value);
6526
6527         type_t *orig_type = value->base.type;
6528         if (!is_type_valid(orig_type))
6529                 return;
6530
6531         set_address_taken(value, false);
6532
6533         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6534 }
6535
6536 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
6537 static expression_t *parse_##unexpression_type(unsigned precedence)            \
6538 {                                                                              \
6539         eat(token_type);                                                           \
6540                                                                                    \
6541         expression_t *unary_expression                                             \
6542                 = allocate_expression_zero(unexpression_type);                         \
6543         unary_expression->base.source_position = *HERE;                            \
6544         unary_expression->unary.value = parse_sub_expression(precedence);          \
6545                                                                                    \
6546         sfunc(&unary_expression->unary);                                           \
6547                                                                                    \
6548         return unary_expression;                                                   \
6549 }
6550
6551 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6552                                semantic_unexpr_arithmetic)
6553 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6554                                semantic_unexpr_arithmetic)
6555 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6556                                semantic_unexpr_scalar)
6557 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6558                                semantic_dereference)
6559 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6560                                semantic_take_addr)
6561 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6562                                semantic_unexpr_integer)
6563 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
6564                                semantic_incdec)
6565 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6566                                semantic_incdec)
6567
6568 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6569                                                sfunc)                         \
6570 static expression_t *parse_##unexpression_type(unsigned precedence,           \
6571                                                expression_t *left)            \
6572 {                                                                             \
6573         (void) precedence;                                                        \
6574         eat(token_type);                                                          \
6575                                                                               \
6576         expression_t *unary_expression                                            \
6577                 = allocate_expression_zero(unexpression_type);                        \
6578         unary_expression->unary.value = left;                                     \
6579                                                                                   \
6580         sfunc(&unary_expression->unary);                                          \
6581                                                                               \
6582         return unary_expression;                                                  \
6583 }
6584
6585 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6586                                        EXPR_UNARY_POSTFIX_INCREMENT,
6587                                        semantic_incdec)
6588 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6589                                        EXPR_UNARY_POSTFIX_DECREMENT,
6590                                        semantic_incdec)
6591
6592 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6593 {
6594         /* TODO: handle complex + imaginary types */
6595
6596         /* Â§ 6.3.1.8 Usual arithmetic conversions */
6597         if (type_left == type_long_double || type_right == type_long_double) {
6598                 return type_long_double;
6599         } else if (type_left == type_double || type_right == type_double) {
6600                 return type_double;
6601         } else if (type_left == type_float || type_right == type_float) {
6602                 return type_float;
6603         }
6604
6605         type_left  = promote_integer(type_left);
6606         type_right = promote_integer(type_right);
6607
6608         if (type_left == type_right)
6609                 return type_left;
6610
6611         bool const signed_left  = is_type_signed(type_left);
6612         bool const signed_right = is_type_signed(type_right);
6613         int  const rank_left    = get_rank(type_left);
6614         int  const rank_right   = get_rank(type_right);
6615
6616         if (signed_left == signed_right)
6617                 return rank_left >= rank_right ? type_left : type_right;
6618
6619         int     s_rank;
6620         int     u_rank;
6621         type_t *s_type;
6622         type_t *u_type;
6623         if (signed_left) {
6624                 s_rank = rank_left;
6625                 s_type = type_left;
6626                 u_rank = rank_right;
6627                 u_type = type_right;
6628         } else {
6629                 s_rank = rank_right;
6630                 s_type = type_right;
6631                 u_rank = rank_left;
6632                 u_type = type_left;
6633         }
6634
6635         if (u_rank >= s_rank)
6636                 return u_type;
6637
6638         if (get_atomic_type_size(s_rank) > get_atomic_type_size(u_rank))
6639                 return s_type;
6640
6641         type_t *const type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
6642         type->atomic.akind = find_unsigned_int_atomic_type_kind_for_size(s_rank);
6643
6644         type_t* const result = typehash_insert(type);
6645         if (result != type)
6646                 free_type(type);
6647
6648         return result;
6649 }
6650
6651 /**
6652  * Check the semantic restrictions for a binary expression.
6653  */
6654 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6655 {
6656         expression_t *const left            = expression->left;
6657         expression_t *const right           = expression->right;
6658         type_t       *const orig_type_left  = left->base.type;
6659         type_t       *const orig_type_right = right->base.type;
6660         type_t       *const type_left       = skip_typeref(orig_type_left);
6661         type_t       *const type_right      = skip_typeref(orig_type_right);
6662
6663         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6664                 /* TODO: improve error message */
6665                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6666                         errorf(HERE, "operation needs arithmetic types");
6667                 }
6668                 return;
6669         }
6670
6671         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6672         expression->left      = create_implicit_cast(left, arithmetic_type);
6673         expression->right     = create_implicit_cast(right, arithmetic_type);
6674         expression->base.type = arithmetic_type;
6675 }
6676
6677 static void semantic_shift_op(binary_expression_t *expression)
6678 {
6679         expression_t *const left            = expression->left;
6680         expression_t *const right           = expression->right;
6681         type_t       *const orig_type_left  = left->base.type;
6682         type_t       *const orig_type_right = right->base.type;
6683         type_t       *      type_left       = skip_typeref(orig_type_left);
6684         type_t       *      type_right      = skip_typeref(orig_type_right);
6685
6686         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6687                 /* TODO: improve error message */
6688                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6689                         errorf(HERE, "operation needs integer types");
6690                 }
6691                 return;
6692         }
6693
6694         type_left  = promote_integer(type_left);
6695         type_right = promote_integer(type_right);
6696
6697         expression->left      = create_implicit_cast(left, type_left);
6698         expression->right     = create_implicit_cast(right, type_right);
6699         expression->base.type = type_left;
6700 }
6701
6702 static void semantic_add(binary_expression_t *expression)
6703 {
6704         expression_t *const left            = expression->left;
6705         expression_t *const right           = expression->right;
6706         type_t       *const orig_type_left  = left->base.type;
6707         type_t       *const orig_type_right = right->base.type;
6708         type_t       *const type_left       = skip_typeref(orig_type_left);
6709         type_t       *const type_right      = skip_typeref(orig_type_right);
6710
6711         /* Â§ 6.5.6 */
6712         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6713                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6714                 expression->left  = create_implicit_cast(left, arithmetic_type);
6715                 expression->right = create_implicit_cast(right, arithmetic_type);
6716                 expression->base.type = arithmetic_type;
6717                 return;
6718         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6719                 check_pointer_arithmetic(&expression->base.source_position,
6720                                          type_left, orig_type_left);
6721                 expression->base.type = type_left;
6722         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6723                 check_pointer_arithmetic(&expression->base.source_position,
6724                                          type_right, orig_type_right);
6725                 expression->base.type = type_right;
6726         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6727                 errorf(&expression->base.source_position,
6728                        "invalid operands to binary + ('%T', '%T')",
6729                        orig_type_left, orig_type_right);
6730         }
6731 }
6732
6733 static void semantic_sub(binary_expression_t *expression)
6734 {
6735         expression_t *const left            = expression->left;
6736         expression_t *const right           = expression->right;
6737         type_t       *const orig_type_left  = left->base.type;
6738         type_t       *const orig_type_right = right->base.type;
6739         type_t       *const type_left       = skip_typeref(orig_type_left);
6740         type_t       *const type_right      = skip_typeref(orig_type_right);
6741
6742         /* Â§ 5.6.5 */
6743         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6744                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6745                 expression->left        = create_implicit_cast(left, arithmetic_type);
6746                 expression->right       = create_implicit_cast(right, arithmetic_type);
6747                 expression->base.type =  arithmetic_type;
6748                 return;
6749         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6750                 check_pointer_arithmetic(&expression->base.source_position,
6751                                          type_left, orig_type_left);
6752                 expression->base.type = type_left;
6753         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6754                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6755                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6756                 if (!types_compatible(unqual_left, unqual_right)) {
6757                         errorf(&expression->base.source_position,
6758                                "subtracting pointers to incompatible types '%T' and '%T'",
6759                                orig_type_left, orig_type_right);
6760                 } else if (!is_type_object(unqual_left)) {
6761                         if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6762                                 warningf(&expression->base.source_position,
6763                                          "subtracting pointers to void");
6764                         } else {
6765                                 errorf(&expression->base.source_position,
6766                                        "subtracting pointers to non-object types '%T'",
6767                                        orig_type_left);
6768                         }
6769                 }
6770                 expression->base.type = type_ptrdiff_t;
6771         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6772                 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6773                        orig_type_left, orig_type_right);
6774         }
6775 }
6776
6777 /**
6778  * Check the semantics of comparison expressions.
6779  *
6780  * @param expression   The expression to check.
6781  */
6782 static void semantic_comparison(binary_expression_t *expression)
6783 {
6784         expression_t *left            = expression->left;
6785         expression_t *right           = expression->right;
6786         type_t       *orig_type_left  = left->base.type;
6787         type_t       *orig_type_right = right->base.type;
6788
6789         type_t *type_left  = skip_typeref(orig_type_left);
6790         type_t *type_right = skip_typeref(orig_type_right);
6791
6792         /* TODO non-arithmetic types */
6793         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6794                 /* test for signed vs unsigned compares */
6795                 if (warning.sign_compare &&
6796                     (expression->base.kind != EXPR_BINARY_EQUAL &&
6797                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6798                     (is_type_signed(type_left) != is_type_signed(type_right))) {
6799
6800                         /* check if 1 of the operands is a constant, in this case we just
6801                          * check wether we can safely represent the resulting constant in
6802                          * the type of the other operand. */
6803                         expression_t *const_expr = NULL;
6804                         expression_t *other_expr = NULL;
6805
6806                         if (is_constant_expression(left)) {
6807                                 const_expr = left;
6808                                 other_expr = right;
6809                         } else if (is_constant_expression(right)) {
6810                                 const_expr = right;
6811                                 other_expr = left;
6812                         }
6813
6814                         if (const_expr != NULL) {
6815                                 type_t *other_type = skip_typeref(other_expr->base.type);
6816                                 long    val        = fold_constant(const_expr);
6817                                 /* TODO: check if val can be represented by other_type */
6818                                 (void) other_type;
6819                                 (void) val;
6820                         }
6821                         warningf(&expression->base.source_position,
6822                                  "comparison between signed and unsigned");
6823                 }
6824                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6825                 expression->left        = create_implicit_cast(left, arithmetic_type);
6826                 expression->right       = create_implicit_cast(right, arithmetic_type);
6827                 expression->base.type   = arithmetic_type;
6828                 if (warning.float_equal &&
6829                     (expression->base.kind == EXPR_BINARY_EQUAL ||
6830                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6831                     is_type_float(arithmetic_type)) {
6832                         warningf(&expression->base.source_position,
6833                                  "comparing floating point with == or != is unsafe");
6834                 }
6835         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6836                 /* TODO check compatibility */
6837         } else if (is_type_pointer(type_left)) {
6838                 expression->right = create_implicit_cast(right, type_left);
6839         } else if (is_type_pointer(type_right)) {
6840                 expression->left = create_implicit_cast(left, type_right);
6841         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6842                 type_error_incompatible("invalid operands in comparison",
6843                                         &expression->base.source_position,
6844                                         type_left, type_right);
6845         }
6846         expression->base.type = type_int;
6847 }
6848
6849 /**
6850  * Checks if a compound type has constant fields.
6851  */
6852 static bool has_const_fields(const compound_type_t *type)
6853 {
6854         const scope_t       *scope       = &type->declaration->scope;
6855         const declaration_t *declaration = scope->declarations;
6856
6857         for (; declaration != NULL; declaration = declaration->next) {
6858                 if (declaration->namespc != NAMESPACE_NORMAL)
6859                         continue;
6860
6861                 const type_t *decl_type = skip_typeref(declaration->type);
6862                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6863                         return true;
6864         }
6865         /* TODO */
6866         return false;
6867 }
6868
6869 static bool is_lvalue(const expression_t *expression)
6870 {
6871         switch (expression->kind) {
6872         case EXPR_REFERENCE:
6873         case EXPR_ARRAY_ACCESS:
6874         case EXPR_SELECT:
6875         case EXPR_UNARY_DEREFERENCE:
6876                 return true;
6877
6878         default:
6879                 return false;
6880         }
6881 }
6882
6883 static bool is_valid_assignment_lhs(expression_t const* const left)
6884 {
6885         type_t *const orig_type_left = revert_automatic_type_conversion(left);
6886         type_t *const type_left      = skip_typeref(orig_type_left);
6887
6888         if (!is_lvalue(left)) {
6889                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6890                        left);
6891                 return false;
6892         }
6893
6894         if (is_type_array(type_left)) {
6895                 errorf(HERE, "cannot assign to arrays ('%E')", left);
6896                 return false;
6897         }
6898         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6899                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6900                        orig_type_left);
6901                 return false;
6902         }
6903         if (is_type_incomplete(type_left)) {
6904                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6905                        left, orig_type_left);
6906                 return false;
6907         }
6908         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6909                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6910                        left, orig_type_left);
6911                 return false;
6912         }
6913
6914         return true;
6915 }
6916
6917 static void semantic_arithmetic_assign(binary_expression_t *expression)
6918 {
6919         expression_t *left            = expression->left;
6920         expression_t *right           = expression->right;
6921         type_t       *orig_type_left  = left->base.type;
6922         type_t       *orig_type_right = right->base.type;
6923
6924         if (!is_valid_assignment_lhs(left))
6925                 return;
6926
6927         type_t *type_left  = skip_typeref(orig_type_left);
6928         type_t *type_right = skip_typeref(orig_type_right);
6929
6930         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6931                 /* TODO: improve error message */
6932                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6933                         errorf(HERE, "operation needs arithmetic types");
6934                 }
6935                 return;
6936         }
6937
6938         /* combined instructions are tricky. We can't create an implicit cast on
6939          * the left side, because we need the uncasted form for the store.
6940          * The ast2firm pass has to know that left_type must be right_type
6941          * for the arithmetic operation and create a cast by itself */
6942         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6943         expression->right       = create_implicit_cast(right, arithmetic_type);
6944         expression->base.type   = type_left;
6945 }
6946
6947 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6948 {
6949         expression_t *const left            = expression->left;
6950         expression_t *const right           = expression->right;
6951         type_t       *const orig_type_left  = left->base.type;
6952         type_t       *const orig_type_right = right->base.type;
6953         type_t       *const type_left       = skip_typeref(orig_type_left);
6954         type_t       *const type_right      = skip_typeref(orig_type_right);
6955
6956         if (!is_valid_assignment_lhs(left))
6957                 return;
6958
6959         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6960                 /* combined instructions are tricky. We can't create an implicit cast on
6961                  * the left side, because we need the uncasted form for the store.
6962                  * The ast2firm pass has to know that left_type must be right_type
6963                  * for the arithmetic operation and create a cast by itself */
6964                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6965                 expression->right     = create_implicit_cast(right, arithmetic_type);
6966                 expression->base.type = type_left;
6967         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6968                 check_pointer_arithmetic(&expression->base.source_position,
6969                                          type_left, orig_type_left);
6970                 expression->base.type = type_left;
6971         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6972                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6973         }
6974 }
6975
6976 /**
6977  * Check the semantic restrictions of a logical expression.
6978  */
6979 static void semantic_logical_op(binary_expression_t *expression)
6980 {
6981         expression_t *const left            = expression->left;
6982         expression_t *const right           = expression->right;
6983         type_t       *const orig_type_left  = left->base.type;
6984         type_t       *const orig_type_right = right->base.type;
6985         type_t       *const type_left       = skip_typeref(orig_type_left);
6986         type_t       *const type_right      = skip_typeref(orig_type_right);
6987
6988         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6989                 /* TODO: improve error message */
6990                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6991                         errorf(HERE, "operation needs scalar types");
6992                 }
6993                 return;
6994         }
6995
6996         expression->base.type = type_int;
6997 }
6998
6999 /**
7000  * Check the semantic restrictions of a binary assign expression.
7001  */
7002 static void semantic_binexpr_assign(binary_expression_t *expression)
7003 {
7004         expression_t *left           = expression->left;
7005         type_t       *orig_type_left = left->base.type;
7006
7007         type_t *type_left = revert_automatic_type_conversion(left);
7008         type_left         = skip_typeref(orig_type_left);
7009
7010         if (!is_valid_assignment_lhs(left))
7011                 return;
7012
7013         assign_error_t error = semantic_assign(orig_type_left, expression->right);
7014         report_assign_error(error, orig_type_left, expression->right,
7015                         "assignment", &left->base.source_position);
7016         expression->right = create_implicit_cast(expression->right, orig_type_left);
7017         expression->base.type = orig_type_left;
7018 }
7019
7020 /**
7021  * Determine if the outermost operation (or parts thereof) of the given
7022  * expression has no effect in order to generate a warning about this fact.
7023  * Therefore in some cases this only examines some of the operands of the
7024  * expression (see comments in the function and examples below).
7025  * Examples:
7026  *   f() + 23;    // warning, because + has no effect
7027  *   x || f();    // no warning, because x controls execution of f()
7028  *   x ? y : f(); // warning, because y has no effect
7029  *   (void)x;     // no warning to be able to suppress the warning
7030  * This function can NOT be used for an "expression has definitely no effect"-
7031  * analysis. */
7032 static bool expression_has_effect(const expression_t *const expr)
7033 {
7034         switch (expr->kind) {
7035                 case EXPR_UNKNOWN:                   break;
7036                 case EXPR_INVALID:                   return true; /* do NOT warn */
7037                 case EXPR_REFERENCE:                 return false;
7038                 /* suppress the warning for microsoft __noop operations */
7039                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
7040                 case EXPR_CHARACTER_CONSTANT:        return false;
7041                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
7042                 case EXPR_STRING_LITERAL:            return false;
7043                 case EXPR_WIDE_STRING_LITERAL:       return false;
7044
7045                 case EXPR_CALL: {
7046                         const call_expression_t *const call = &expr->call;
7047                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7048                                 return true;
7049
7050                         switch (call->function->builtin_symbol.symbol->ID) {
7051                                 case T___builtin_va_end: return true;
7052                                 default:                 return false;
7053                         }
7054                 }
7055
7056                 /* Generate the warning if either the left or right hand side of a
7057                  * conditional expression has no effect */
7058                 case EXPR_CONDITIONAL: {
7059                         const conditional_expression_t *const cond = &expr->conditional;
7060                         return
7061                                 expression_has_effect(cond->true_expression) &&
7062                                 expression_has_effect(cond->false_expression);
7063                 }
7064
7065                 case EXPR_SELECT:                    return false;
7066                 case EXPR_ARRAY_ACCESS:              return false;
7067                 case EXPR_SIZEOF:                    return false;
7068                 case EXPR_CLASSIFY_TYPE:             return false;
7069                 case EXPR_ALIGNOF:                   return false;
7070
7071                 case EXPR_FUNCNAME:                  return false;
7072                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
7073                 case EXPR_BUILTIN_CONSTANT_P:        return false;
7074                 case EXPR_BUILTIN_PREFETCH:          return true;
7075                 case EXPR_OFFSETOF:                  return false;
7076                 case EXPR_VA_START:                  return true;
7077                 case EXPR_VA_ARG:                    return true;
7078                 case EXPR_STATEMENT:                 return true; // TODO
7079                 case EXPR_COMPOUND_LITERAL:          return false;
7080
7081                 case EXPR_UNARY_NEGATE:              return false;
7082                 case EXPR_UNARY_PLUS:                return false;
7083                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
7084                 case EXPR_UNARY_NOT:                 return false;
7085                 case EXPR_UNARY_DEREFERENCE:         return false;
7086                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
7087                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
7088                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
7089                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
7090                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
7091
7092                 /* Treat void casts as if they have an effect in order to being able to
7093                  * suppress the warning */
7094                 case EXPR_UNARY_CAST: {
7095                         type_t *const type = skip_typeref(expr->base.type);
7096                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
7097                 }
7098
7099                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
7100                 case EXPR_UNARY_ASSUME:              return true;
7101
7102                 case EXPR_BINARY_ADD:                return false;
7103                 case EXPR_BINARY_SUB:                return false;
7104                 case EXPR_BINARY_MUL:                return false;
7105                 case EXPR_BINARY_DIV:                return false;
7106                 case EXPR_BINARY_MOD:                return false;
7107                 case EXPR_BINARY_EQUAL:              return false;
7108                 case EXPR_BINARY_NOTEQUAL:           return false;
7109                 case EXPR_BINARY_LESS:               return false;
7110                 case EXPR_BINARY_LESSEQUAL:          return false;
7111                 case EXPR_BINARY_GREATER:            return false;
7112                 case EXPR_BINARY_GREATEREQUAL:       return false;
7113                 case EXPR_BINARY_BITWISE_AND:        return false;
7114                 case EXPR_BINARY_BITWISE_OR:         return false;
7115                 case EXPR_BINARY_BITWISE_XOR:        return false;
7116                 case EXPR_BINARY_SHIFTLEFT:          return false;
7117                 case EXPR_BINARY_SHIFTRIGHT:         return false;
7118                 case EXPR_BINARY_ASSIGN:             return true;
7119                 case EXPR_BINARY_MUL_ASSIGN:         return true;
7120                 case EXPR_BINARY_DIV_ASSIGN:         return true;
7121                 case EXPR_BINARY_MOD_ASSIGN:         return true;
7122                 case EXPR_BINARY_ADD_ASSIGN:         return true;
7123                 case EXPR_BINARY_SUB_ASSIGN:         return true;
7124                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
7125                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
7126                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7127                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7128                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
7129
7130                 /* Only examine the right hand side of && and ||, because the left hand
7131                  * side already has the effect of controlling the execution of the right
7132                  * hand side */
7133                 case EXPR_BINARY_LOGICAL_AND:
7134                 case EXPR_BINARY_LOGICAL_OR:
7135                 /* Only examine the right hand side of a comma expression, because the left
7136                  * hand side has a separate warning */
7137                 case EXPR_BINARY_COMMA:
7138                         return expression_has_effect(expr->binary.right);
7139
7140                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
7141                 case EXPR_BINARY_ISGREATER:          return false;
7142                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
7143                 case EXPR_BINARY_ISLESS:             return false;
7144                 case EXPR_BINARY_ISLESSEQUAL:        return false;
7145                 case EXPR_BINARY_ISLESSGREATER:      return false;
7146                 case EXPR_BINARY_ISUNORDERED:        return false;
7147         }
7148
7149         internal_errorf(HERE, "unexpected expression");
7150 }
7151
7152 static void semantic_comma(binary_expression_t *expression)
7153 {
7154         if (warning.unused_value) {
7155                 const expression_t *const left = expression->left;
7156                 if (!expression_has_effect(left)) {
7157                         warningf(&left->base.source_position,
7158                                  "left-hand operand of comma expression has no effect");
7159                 }
7160         }
7161         expression->base.type = expression->right->base.type;
7162 }
7163
7164 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
7165 static expression_t *parse_##binexpression_type(unsigned precedence,      \
7166                                                 expression_t *left)       \
7167 {                                                                         \
7168         eat(token_type);                                                      \
7169         source_position_t pos = *HERE;                                        \
7170                                                                           \
7171         expression_t *right = parse_sub_expression(precedence + lr);          \
7172                                                                           \
7173         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7174         binexpr->base.source_position = pos;                                  \
7175         binexpr->binary.left  = left;                                         \
7176         binexpr->binary.right = right;                                        \
7177         sfunc(&binexpr->binary);                                              \
7178                                                                           \
7179         return binexpr;                                                       \
7180 }
7181
7182 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
7183 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
7184 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
7185 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
7186 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
7187 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
7188 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
7189 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
7190 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
7191
7192 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
7193                       semantic_comparison, 1)
7194 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7195                       semantic_comparison, 1)
7196 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
7197                       semantic_comparison, 1)
7198 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
7199                       semantic_comparison, 1)
7200
7201 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7202                       semantic_binexpr_arithmetic, 1)
7203 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7204                       semantic_binexpr_arithmetic, 1)
7205 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7206                       semantic_binexpr_arithmetic, 1)
7207 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7208                       semantic_logical_op, 1)
7209 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7210                       semantic_logical_op, 1)
7211 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7212                       semantic_shift_op, 1)
7213 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7214                       semantic_shift_op, 1)
7215 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7216                       semantic_arithmetic_addsubb_assign, 0)
7217 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7218                       semantic_arithmetic_addsubb_assign, 0)
7219 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7220                       semantic_arithmetic_assign, 0)
7221 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7222                       semantic_arithmetic_assign, 0)
7223 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7224                       semantic_arithmetic_assign, 0)
7225 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7226                       semantic_arithmetic_assign, 0)
7227 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7228                       semantic_arithmetic_assign, 0)
7229 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7230                       semantic_arithmetic_assign, 0)
7231 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7232                       semantic_arithmetic_assign, 0)
7233 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7234                       semantic_arithmetic_assign, 0)
7235
7236 static expression_t *parse_sub_expression(unsigned precedence)
7237 {
7238         if (token.type < 0) {
7239                 return expected_expression_error();
7240         }
7241
7242         expression_parser_function_t *parser
7243                 = &expression_parsers[token.type];
7244         source_position_t             source_position = token.source_position;
7245         expression_t                 *left;
7246
7247         if (parser->parser != NULL) {
7248                 left = parser->parser(parser->precedence);
7249         } else {
7250                 left = parse_primary_expression();
7251         }
7252         assert(left != NULL);
7253         left->base.source_position = source_position;
7254
7255         while(true) {
7256                 if (token.type < 0) {
7257                         return expected_expression_error();
7258                 }
7259
7260                 parser = &expression_parsers[token.type];
7261                 if (parser->infix_parser == NULL)
7262                         break;
7263                 if (parser->infix_precedence < precedence)
7264                         break;
7265
7266                 left = parser->infix_parser(parser->infix_precedence, left);
7267
7268                 assert(left != NULL);
7269                 assert(left->kind != EXPR_UNKNOWN);
7270                 left->base.source_position = source_position;
7271         }
7272
7273         return left;
7274 }
7275
7276 /**
7277  * Parse an expression.
7278  */
7279 static expression_t *parse_expression(void)
7280 {
7281         return parse_sub_expression(1);
7282 }
7283
7284 /**
7285  * Register a parser for a prefix-like operator with given precedence.
7286  *
7287  * @param parser      the parser function
7288  * @param token_type  the token type of the prefix token
7289  * @param precedence  the precedence of the operator
7290  */
7291 static void register_expression_parser(parse_expression_function parser,
7292                                        int token_type, unsigned precedence)
7293 {
7294         expression_parser_function_t *entry = &expression_parsers[token_type];
7295
7296         if (entry->parser != NULL) {
7297                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7298                 panic("trying to register multiple expression parsers for a token");
7299         }
7300         entry->parser     = parser;
7301         entry->precedence = precedence;
7302 }
7303
7304 /**
7305  * Register a parser for an infix operator with given precedence.
7306  *
7307  * @param parser      the parser function
7308  * @param token_type  the token type of the infix operator
7309  * @param precedence  the precedence of the operator
7310  */
7311 static void register_infix_parser(parse_expression_infix_function parser,
7312                 int token_type, unsigned precedence)
7313 {
7314         expression_parser_function_t *entry = &expression_parsers[token_type];
7315
7316         if (entry->infix_parser != NULL) {
7317                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7318                 panic("trying to register multiple infix expression parsers for a "
7319                       "token");
7320         }
7321         entry->infix_parser     = parser;
7322         entry->infix_precedence = precedence;
7323 }
7324
7325 /**
7326  * Initialize the expression parsers.
7327  */
7328 static void init_expression_parsers(void)
7329 {
7330         memset(&expression_parsers, 0, sizeof(expression_parsers));
7331
7332         register_infix_parser(parse_array_expression,         '[',              30);
7333         register_infix_parser(parse_call_expression,          '(',              30);
7334         register_infix_parser(parse_select_expression,        '.',              30);
7335         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
7336         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7337                                                               T_PLUSPLUS,       30);
7338         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7339                                                               T_MINUSMINUS,     30);
7340
7341         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              17);
7342         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              17);
7343         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              17);
7344         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              16);
7345         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              16);
7346         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       15);
7347         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 15);
7348         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
7349         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
7350         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
7351         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
7352         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
7353         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7354                                                     T_EXCLAMATIONMARKEQUAL, 13);
7355         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
7356         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
7357         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
7358         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
7359         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
7360         register_infix_parser(parse_conditional_expression,   '?',               7);
7361         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
7362         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
7363         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
7364         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
7365         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
7366         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
7367         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7368                                                                 T_LESSLESSEQUAL, 2);
7369         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7370                                                           T_GREATERGREATEREQUAL, 2);
7371         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7372                                                                      T_ANDEQUAL, 2);
7373         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7374                                                                     T_PIPEEQUAL, 2);
7375         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7376                                                                    T_CARETEQUAL, 2);
7377
7378         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
7379
7380         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
7381         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
7382         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
7383         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
7384         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
7385         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
7386         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7387                                                                   T_PLUSPLUS,   25);
7388         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7389                                                                   T_MINUSMINUS, 25);
7390         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
7391         register_expression_parser(parse_alignof,                T___alignof__, 25);
7392         register_expression_parser(parse_extension,            T___extension__, 25);
7393         register_expression_parser(parse_builtin_classify_type,
7394                                                      T___builtin_classify_type, 25);
7395 }
7396
7397 /**
7398  * Parse a asm statement arguments specification.
7399  */
7400 static asm_argument_t *parse_asm_arguments(bool is_out)
7401 {
7402         asm_argument_t *result = NULL;
7403         asm_argument_t *last   = NULL;
7404
7405         while (token.type == T_STRING_LITERAL || token.type == '[') {
7406                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7407                 memset(argument, 0, sizeof(argument[0]));
7408
7409                 if (token.type == '[') {
7410                         eat('[');
7411                         if (token.type != T_IDENTIFIER) {
7412                                 parse_error_expected("while parsing asm argument",
7413                                                      T_IDENTIFIER, NULL);
7414                                 return NULL;
7415                         }
7416                         argument->symbol = token.v.symbol;
7417
7418                         expect(']');
7419                 }
7420
7421                 argument->constraints = parse_string_literals();
7422                 expect('(');
7423                 expression_t *expression = parse_expression();
7424                 argument->expression     = expression;
7425                 if (is_out && !is_lvalue(expression)) {
7426                         errorf(&expression->base.source_position,
7427                                "asm output argument is not an lvalue");
7428                 }
7429                 expect(')');
7430
7431                 set_address_taken(expression, true);
7432
7433                 if (last != NULL) {
7434                         last->next = argument;
7435                 } else {
7436                         result = argument;
7437                 }
7438                 last = argument;
7439
7440                 if (token.type != ',')
7441                         break;
7442                 eat(',');
7443         }
7444
7445         return result;
7446 end_error:
7447         return NULL;
7448 }
7449
7450 /**
7451  * Parse a asm statement clobber specification.
7452  */
7453 static asm_clobber_t *parse_asm_clobbers(void)
7454 {
7455         asm_clobber_t *result = NULL;
7456         asm_clobber_t *last   = NULL;
7457
7458         while(token.type == T_STRING_LITERAL) {
7459                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7460                 clobber->clobber       = parse_string_literals();
7461
7462                 if (last != NULL) {
7463                         last->next = clobber;
7464                 } else {
7465                         result = clobber;
7466                 }
7467                 last = clobber;
7468
7469                 if (token.type != ',')
7470                         break;
7471                 eat(',');
7472         }
7473
7474         return result;
7475 }
7476
7477 /**
7478  * Parse an asm statement.
7479  */
7480 static statement_t *parse_asm_statement(void)
7481 {
7482         eat(T_asm);
7483
7484         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
7485         statement->base.source_position = token.source_position;
7486
7487         asm_statement_t *asm_statement = &statement->asms;
7488
7489         if (token.type == T_volatile) {
7490                 next_token();
7491                 asm_statement->is_volatile = true;
7492         }
7493
7494         expect('(');
7495         add_anchor_token(')');
7496         add_anchor_token(':');
7497         asm_statement->asm_text = parse_string_literals();
7498
7499         if (token.type != ':') {
7500                 rem_anchor_token(':');
7501                 goto end_of_asm;
7502         }
7503         eat(':');
7504
7505         asm_statement->outputs = parse_asm_arguments(true);
7506         if (token.type != ':') {
7507                 rem_anchor_token(':');
7508                 goto end_of_asm;
7509         }
7510         eat(':');
7511
7512         asm_statement->inputs = parse_asm_arguments(false);
7513         if (token.type != ':') {
7514                 rem_anchor_token(':');
7515                 goto end_of_asm;
7516         }
7517         rem_anchor_token(':');
7518         eat(':');
7519
7520         asm_statement->clobbers = parse_asm_clobbers();
7521
7522 end_of_asm:
7523         rem_anchor_token(')');
7524         expect(')');
7525         expect(';');
7526         return statement;
7527 end_error:
7528         return create_invalid_statement();
7529 }
7530
7531 /**
7532  * Parse a case statement.
7533  */
7534 static statement_t *parse_case_statement(void)
7535 {
7536         eat(T_case);
7537
7538         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7539
7540         statement->base.source_position  = token.source_position;
7541         statement->case_label.expression = parse_expression();
7542
7543         if (c_mode & _GNUC) {
7544                 if (token.type == T_DOTDOTDOT) {
7545                         next_token();
7546                         statement->case_label.end_range = parse_expression();
7547                 }
7548         }
7549
7550         expect(':');
7551
7552         if (! is_constant_expression(statement->case_label.expression)) {
7553                 errorf(&statement->base.source_position,
7554                        "case label does not reduce to an integer constant");
7555         } else {
7556                 /* TODO: check if the case label is already known */
7557                 if (current_switch != NULL) {
7558                         /* link all cases into the switch statement */
7559                         if (current_switch->last_case == NULL) {
7560                                 current_switch->first_case =
7561                                 current_switch->last_case  = &statement->case_label;
7562                         } else {
7563                                 current_switch->last_case->next = &statement->case_label;
7564                         }
7565                 } else {
7566                         errorf(&statement->base.source_position,
7567                                "case label not within a switch statement");
7568                 }
7569         }
7570         statement->case_label.statement = parse_statement();
7571
7572         return statement;
7573 end_error:
7574         return create_invalid_statement();
7575 }
7576
7577 /**
7578  * Finds an existing default label of a switch statement.
7579  */
7580 static case_label_statement_t *
7581 find_default_label(const switch_statement_t *statement)
7582 {
7583         case_label_statement_t *label = statement->first_case;
7584         for ( ; label != NULL; label = label->next) {
7585                 if (label->expression == NULL)
7586                         return label;
7587         }
7588         return NULL;
7589 }
7590
7591 /**
7592  * Parse a default statement.
7593  */
7594 static statement_t *parse_default_statement(void)
7595 {
7596         eat(T_default);
7597
7598         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7599
7600         statement->base.source_position = token.source_position;
7601
7602         expect(':');
7603         if (current_switch != NULL) {
7604                 const case_label_statement_t *def_label = find_default_label(current_switch);
7605                 if (def_label != NULL) {
7606                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7607                                &def_label->base.source_position);
7608                 } else {
7609                         /* link all cases into the switch statement */
7610                         if (current_switch->last_case == NULL) {
7611                                 current_switch->first_case =
7612                                         current_switch->last_case  = &statement->case_label;
7613                         } else {
7614                                 current_switch->last_case->next = &statement->case_label;
7615                         }
7616                 }
7617         } else {
7618                 errorf(&statement->base.source_position,
7619                         "'default' label not within a switch statement");
7620         }
7621         statement->case_label.statement = parse_statement();
7622
7623         return statement;
7624 end_error:
7625         return create_invalid_statement();
7626 }
7627
7628 /**
7629  * Return the declaration for a given label symbol or create a new one.
7630  *
7631  * @param symbol  the symbol of the label
7632  */
7633 static declaration_t *get_label(symbol_t *symbol)
7634 {
7635         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7636         assert(current_function != NULL);
7637         /* if we found a label in the same function, then we already created the
7638          * declaration */
7639         if (candidate != NULL
7640                         && candidate->parent_scope == &current_function->scope) {
7641                 return candidate;
7642         }
7643
7644         /* otherwise we need to create a new one */
7645         declaration_t *const declaration = allocate_declaration_zero();
7646         declaration->namespc       = NAMESPACE_LABEL;
7647         declaration->symbol        = symbol;
7648
7649         label_push(declaration);
7650
7651         return declaration;
7652 }
7653
7654 /**
7655  * Parse a label statement.
7656  */
7657 static statement_t *parse_label_statement(void)
7658 {
7659         assert(token.type == T_IDENTIFIER);
7660         symbol_t *symbol = token.v.symbol;
7661         next_token();
7662
7663         declaration_t *label = get_label(symbol);
7664
7665         /* if source position is already set then the label is defined twice,
7666          * otherwise it was just mentioned in a goto so far */
7667         if (label->source_position.input_name != NULL) {
7668                 errorf(HERE, "duplicate label '%Y' (declared %P)",
7669                        symbol, &label->source_position);
7670         } else {
7671                 label->source_position = token.source_position;
7672         }
7673
7674         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7675
7676         statement->base.source_position = token.source_position;
7677         statement->label.label          = label;
7678
7679         eat(':');
7680
7681         if (token.type == '}') {
7682                 /* TODO only warn? */
7683                 if (false) {
7684                         warningf(HERE, "label at end of compound statement");
7685                         statement->label.statement = create_empty_statement();
7686                 } else {
7687                         errorf(HERE, "label at end of compound statement");
7688                         statement->label.statement = create_invalid_statement();
7689                 }
7690                 return statement;
7691         } else {
7692                 if (token.type == ';') {
7693                         /* eat an empty statement here, to avoid the warning about an empty
7694                          * after a label.  label:; is commonly used to have a label before
7695                          * a }. */
7696                         statement->label.statement = create_empty_statement();
7697                         next_token();
7698                 } else {
7699                         statement->label.statement = parse_statement();
7700                 }
7701         }
7702
7703         /* remember the labels in a list for later checking */
7704         if (label_last == NULL) {
7705                 label_first = &statement->label;
7706         } else {
7707                 label_last->next = &statement->label;
7708         }
7709         label_last = &statement->label;
7710
7711         return statement;
7712 }
7713
7714 /**
7715  * Parse an if statement.
7716  */
7717 static statement_t *parse_if(void)
7718 {
7719         eat(T_if);
7720
7721         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
7722         statement->base.source_position = token.source_position;
7723
7724         expect('(');
7725         add_anchor_token(')');
7726         statement->ifs.condition = parse_expression();
7727         rem_anchor_token(')');
7728         expect(')');
7729
7730         add_anchor_token(T_else);
7731         statement->ifs.true_statement = parse_statement();
7732         rem_anchor_token(T_else);
7733
7734         if (token.type == T_else) {
7735                 next_token();
7736                 statement->ifs.false_statement = parse_statement();
7737         }
7738
7739         return statement;
7740 end_error:
7741         return create_invalid_statement();
7742 }
7743
7744 /**
7745  * Parse a switch statement.
7746  */
7747 static statement_t *parse_switch(void)
7748 {
7749         eat(T_switch);
7750
7751         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
7752         statement->base.source_position = token.source_position;
7753
7754         expect('(');
7755         expression_t *const expr = parse_expression();
7756         type_t       *      type = skip_typeref(expr->base.type);
7757         if (is_type_integer(type)) {
7758                 type = promote_integer(type);
7759         } else if (is_type_valid(type)) {
7760                 errorf(&expr->base.source_position,
7761                        "switch quantity is not an integer, but '%T'", type);
7762                 type = type_error_type;
7763         }
7764         statement->switchs.expression = create_implicit_cast(expr, type);
7765         expect(')');
7766
7767         switch_statement_t *rem = current_switch;
7768         current_switch          = &statement->switchs;
7769         statement->switchs.body = parse_statement();
7770         current_switch          = rem;
7771
7772         if (warning.switch_default &&
7773            find_default_label(&statement->switchs) == NULL) {
7774                 warningf(&statement->base.source_position, "switch has no default case");
7775         }
7776
7777         return statement;
7778 end_error:
7779         return create_invalid_statement();
7780 }
7781
7782 static statement_t *parse_loop_body(statement_t *const loop)
7783 {
7784         statement_t *const rem = current_loop;
7785         current_loop = loop;
7786
7787         statement_t *const body = parse_statement();
7788
7789         current_loop = rem;
7790         return body;
7791 }
7792
7793 /**
7794  * Parse a while statement.
7795  */
7796 static statement_t *parse_while(void)
7797 {
7798         eat(T_while);
7799
7800         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
7801         statement->base.source_position = token.source_position;
7802
7803         expect('(');
7804         add_anchor_token(')');
7805         statement->whiles.condition = parse_expression();
7806         rem_anchor_token(')');
7807         expect(')');
7808
7809         statement->whiles.body = parse_loop_body(statement);
7810
7811         return statement;
7812 end_error:
7813         return create_invalid_statement();
7814 }
7815
7816 /**
7817  * Parse a do statement.
7818  */
7819 static statement_t *parse_do(void)
7820 {
7821         eat(T_do);
7822
7823         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7824
7825         statement->base.source_position = token.source_position;
7826
7827         add_anchor_token(T_while);
7828         statement->do_while.body = parse_loop_body(statement);
7829         rem_anchor_token(T_while);
7830
7831         expect(T_while);
7832         expect('(');
7833         add_anchor_token(')');
7834         statement->do_while.condition = parse_expression();
7835         rem_anchor_token(')');
7836         expect(')');
7837         expect(';');
7838
7839         return statement;
7840 end_error:
7841         return create_invalid_statement();
7842 }
7843
7844 /**
7845  * Parse a for statement.
7846  */
7847 static statement_t *parse_for(void)
7848 {
7849         eat(T_for);
7850
7851         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
7852         statement->base.source_position = token.source_position;
7853
7854         int      top        = environment_top();
7855         scope_t *last_scope = scope;
7856         set_scope(&statement->fors.scope);
7857
7858         expect('(');
7859         add_anchor_token(')');
7860
7861         if (token.type != ';') {
7862                 if (is_declaration_specifier(&token, false)) {
7863                         parse_declaration(record_declaration);
7864                 } else {
7865                         add_anchor_token(';');
7866                         expression_t *const init = parse_expression();
7867                         statement->fors.initialisation = init;
7868                         if (warning.unused_value && !expression_has_effect(init)) {
7869                                 warningf(&init->base.source_position,
7870                                          "initialisation of 'for'-statement has no effect");
7871                         }
7872                         rem_anchor_token(';');
7873                         expect(';');
7874                 }
7875         } else {
7876                 expect(';');
7877         }
7878
7879         if (token.type != ';') {
7880                 add_anchor_token(';');
7881                 statement->fors.condition = parse_expression();
7882                 rem_anchor_token(';');
7883         }
7884         expect(';');
7885         if (token.type != ')') {
7886                 expression_t *const step = parse_expression();
7887                 statement->fors.step = step;
7888                 if (warning.unused_value && !expression_has_effect(step)) {
7889                         warningf(&step->base.source_position,
7890                                  "step of 'for'-statement has no effect");
7891                 }
7892         }
7893         rem_anchor_token(')');
7894         expect(')');
7895         statement->fors.body = parse_loop_body(statement);
7896
7897         assert(scope == &statement->fors.scope);
7898         set_scope(last_scope);
7899         environment_pop_to(top);
7900
7901         return statement;
7902
7903 end_error:
7904         rem_anchor_token(')');
7905         assert(scope == &statement->fors.scope);
7906         set_scope(last_scope);
7907         environment_pop_to(top);
7908
7909         return create_invalid_statement();
7910 }
7911
7912 /**
7913  * Parse a goto statement.
7914  */
7915 static statement_t *parse_goto(void)
7916 {
7917         eat(T_goto);
7918
7919         if (token.type != T_IDENTIFIER) {
7920                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7921                 eat_statement();
7922                 goto end_error;
7923         }
7924         symbol_t *symbol = token.v.symbol;
7925         next_token();
7926
7927         declaration_t *label = get_label(symbol);
7928
7929         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
7930         statement->base.source_position = token.source_position;
7931
7932         statement->gotos.label = label;
7933
7934         /* remember the goto's in a list for later checking */
7935         if (goto_last == NULL) {
7936                 goto_first = &statement->gotos;
7937         } else {
7938                 goto_last->next = &statement->gotos;
7939         }
7940         goto_last = &statement->gotos;
7941
7942         expect(';');
7943
7944         return statement;
7945 end_error:
7946         return create_invalid_statement();
7947 }
7948
7949 /**
7950  * Parse a continue statement.
7951  */
7952 static statement_t *parse_continue(void)
7953 {
7954         statement_t *statement;
7955         if (current_loop == NULL) {
7956                 errorf(HERE, "continue statement not within loop");
7957                 statement = create_invalid_statement();
7958         } else {
7959                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7960
7961                 statement->base.source_position = token.source_position;
7962         }
7963
7964         eat(T_continue);
7965         expect(';');
7966
7967         return statement;
7968 end_error:
7969         return create_invalid_statement();
7970 }
7971
7972 /**
7973  * Parse a break statement.
7974  */
7975 static statement_t *parse_break(void)
7976 {
7977         statement_t *statement;
7978         if (current_switch == NULL && current_loop == NULL) {
7979                 errorf(HERE, "break statement not within loop or switch");
7980                 statement = create_invalid_statement();
7981         } else {
7982                 statement = allocate_statement_zero(STATEMENT_BREAK);
7983
7984                 statement->base.source_position = token.source_position;
7985         }
7986
7987         eat(T_break);
7988         expect(';');
7989
7990         return statement;
7991 end_error:
7992         return create_invalid_statement();
7993 }
7994
7995 /**
7996  * Parse a __leave statement.
7997  */
7998 static statement_t *parse_leave(void)
7999 {
8000         statement_t *statement;
8001         if (current_try == NULL) {
8002                 errorf(HERE, "__leave statement not within __try");
8003                 statement = create_invalid_statement();
8004         } else {
8005                 statement = allocate_statement_zero(STATEMENT_LEAVE);
8006
8007                 statement->base.source_position = token.source_position;
8008         }
8009
8010         eat(T___leave);
8011         expect(';');
8012
8013         return statement;
8014 end_error:
8015         return create_invalid_statement();
8016 }
8017
8018 /**
8019  * Check if a given declaration represents a local variable.
8020  */
8021 static bool is_local_var_declaration(const declaration_t *declaration) {
8022         switch ((storage_class_tag_t) declaration->storage_class) {
8023         case STORAGE_CLASS_AUTO:
8024         case STORAGE_CLASS_REGISTER: {
8025                 const type_t *type = skip_typeref(declaration->type);
8026                 if (is_type_function(type)) {
8027                         return false;
8028                 } else {
8029                         return true;
8030                 }
8031         }
8032         default:
8033                 return false;
8034         }
8035 }
8036
8037 /**
8038  * Check if a given declaration represents a variable.
8039  */
8040 static bool is_var_declaration(const declaration_t *declaration) {
8041         if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
8042                 return false;
8043
8044         const type_t *type = skip_typeref(declaration->type);
8045         return !is_type_function(type);
8046 }
8047
8048 /**
8049  * Check if a given expression represents a local variable.
8050  */
8051 static bool is_local_variable(const expression_t *expression)
8052 {
8053         if (expression->base.kind != EXPR_REFERENCE) {
8054                 return false;
8055         }
8056         const declaration_t *declaration = expression->reference.declaration;
8057         return is_local_var_declaration(declaration);
8058 }
8059
8060 /**
8061  * Check if a given expression represents a local variable and
8062  * return its declaration then, else return NULL.
8063  */
8064 declaration_t *expr_is_variable(const expression_t *expression)
8065 {
8066         if (expression->base.kind != EXPR_REFERENCE) {
8067                 return NULL;
8068         }
8069         declaration_t *declaration = expression->reference.declaration;
8070         if (is_var_declaration(declaration))
8071                 return declaration;
8072         return NULL;
8073 }
8074
8075 /**
8076  * Parse a return statement.
8077  */
8078 static statement_t *parse_return(void)
8079 {
8080         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
8081         statement->base.source_position = token.source_position;
8082
8083         eat(T_return);
8084
8085         expression_t *return_value = NULL;
8086         if (token.type != ';') {
8087                 return_value = parse_expression();
8088         }
8089         expect(';');
8090
8091         const type_t *const func_type = current_function->type;
8092         assert(is_type_function(func_type));
8093         type_t *const return_type = skip_typeref(func_type->function.return_type);
8094
8095         if (return_value != NULL) {
8096                 type_t *return_value_type = skip_typeref(return_value->base.type);
8097
8098                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8099                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8100                         warningf(&statement->base.source_position,
8101                                  "'return' with a value, in function returning void");
8102                         return_value = NULL;
8103                 } else {
8104                         assign_error_t error = semantic_assign(return_type, return_value);
8105                         report_assign_error(error, return_type, return_value, "'return'",
8106                                             &statement->base.source_position);
8107                         return_value = create_implicit_cast(return_value, return_type);
8108                 }
8109                 /* check for returning address of a local var */
8110                 if (return_value != NULL &&
8111                                 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8112                         const expression_t *expression = return_value->unary.value;
8113                         if (is_local_variable(expression)) {
8114                                 warningf(&statement->base.source_position,
8115                                          "function returns address of local variable");
8116                         }
8117                 }
8118         } else {
8119                 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8120                         warningf(&statement->base.source_position,
8121                                  "'return' without value, in function returning non-void");
8122                 }
8123         }
8124         statement->returns.value = return_value;
8125
8126         return statement;
8127 end_error:
8128         return create_invalid_statement();
8129 }
8130
8131 /**
8132  * Parse a declaration statement.
8133  */
8134 static statement_t *parse_declaration_statement(void)
8135 {
8136         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8137
8138         statement->base.source_position = token.source_position;
8139
8140         declaration_t *before = last_declaration;
8141         parse_declaration(record_declaration);
8142
8143         if (before == NULL) {
8144                 statement->declaration.declarations_begin = scope->declarations;
8145         } else {
8146                 statement->declaration.declarations_begin = before->next;
8147         }
8148         statement->declaration.declarations_end = last_declaration;
8149
8150         return statement;
8151 }
8152
8153 /**
8154  * Parse an expression statement, ie. expr ';'.
8155  */
8156 static statement_t *parse_expression_statement(void)
8157 {
8158         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8159
8160         statement->base.source_position  = token.source_position;
8161         expression_t *const expr         = parse_expression();
8162         statement->expression.expression = expr;
8163
8164         expect(';');
8165
8166         return statement;
8167 end_error:
8168         return create_invalid_statement();
8169 }
8170
8171 /**
8172  * Parse a microsoft __try { } __finally { } or
8173  * __try{ } __except() { }
8174  */
8175 static statement_t *parse_ms_try_statment(void) {
8176         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8177
8178         statement->base.source_position  = token.source_position;
8179         eat(T___try);
8180
8181         ms_try_statement_t *rem = current_try;
8182         current_try = &statement->ms_try;
8183         statement->ms_try.try_statement = parse_compound_statement(false);
8184         current_try = rem;
8185
8186         if (token.type == T___except) {
8187                 eat(T___except);
8188                 expect('(');
8189                 add_anchor_token(')');
8190                 expression_t *const expr = parse_expression();
8191                 type_t       *      type = skip_typeref(expr->base.type);
8192                 if (is_type_integer(type)) {
8193                         type = promote_integer(type);
8194                 } else if (is_type_valid(type)) {
8195                         errorf(&expr->base.source_position,
8196                                "__expect expression is not an integer, but '%T'", type);
8197                         type = type_error_type;
8198                 }
8199                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8200                 rem_anchor_token(')');
8201                 expect(')');
8202                 statement->ms_try.final_statement = parse_compound_statement(false);
8203         } else if (token.type == T__finally) {
8204                 eat(T___finally);
8205                 statement->ms_try.final_statement = parse_compound_statement(false);
8206         } else {
8207                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8208                 return create_invalid_statement();
8209         }
8210         return statement;
8211 end_error:
8212         return create_invalid_statement();
8213 }
8214
8215 /**
8216  * Parse a statement.
8217  * There's also parse_statement() which additionally checks for
8218  * "statement has no effect" warnings
8219  */
8220 static statement_t *intern_parse_statement(void)
8221 {
8222         statement_t *statement = NULL;
8223
8224         /* declaration or statement */
8225         add_anchor_token(';');
8226         switch(token.type) {
8227         case T_asm:
8228                 statement = parse_asm_statement();
8229                 break;
8230
8231         case T_case:
8232                 statement = parse_case_statement();
8233                 break;
8234
8235         case T_default:
8236                 statement = parse_default_statement();
8237                 break;
8238
8239         case '{':
8240                 statement = parse_compound_statement(false);
8241                 break;
8242
8243         case T_if:
8244                 statement = parse_if ();
8245                 break;
8246
8247         case T_switch:
8248                 statement = parse_switch();
8249                 break;
8250
8251         case T_while:
8252                 statement = parse_while();
8253                 break;
8254
8255         case T_do:
8256                 statement = parse_do();
8257                 break;
8258
8259         case T_for:
8260                 statement = parse_for();
8261                 break;
8262
8263         case T_goto:
8264                 statement = parse_goto();
8265                 break;
8266
8267         case T_continue:
8268                 statement = parse_continue();
8269                 break;
8270
8271         case T_break:
8272                 statement = parse_break();
8273                 break;
8274
8275         case T___leave:
8276                 statement = parse_leave();
8277                 break;
8278
8279         case T_return:
8280                 statement = parse_return();
8281                 break;
8282
8283         case ';':
8284                 if (warning.empty_statement) {
8285                         warningf(HERE, "statement is empty");
8286                 }
8287                 statement = create_empty_statement();
8288                 next_token();
8289                 break;
8290
8291         case T_IDENTIFIER:
8292                 if (look_ahead(1)->type == ':') {
8293                         statement = parse_label_statement();
8294                         break;
8295                 }
8296
8297                 if (is_typedef_symbol(token.v.symbol)) {
8298                         statement = parse_declaration_statement();
8299                         break;
8300                 }
8301
8302                 statement = parse_expression_statement();
8303                 break;
8304
8305         case T___extension__:
8306                 /* this can be a prefix to a declaration or an expression statement */
8307                 /* we simply eat it now and parse the rest with tail recursion */
8308                 do {
8309                         next_token();
8310                 } while(token.type == T___extension__);
8311                 statement = parse_statement();
8312                 break;
8313
8314         DECLARATION_START
8315                 statement = parse_declaration_statement();
8316                 break;
8317
8318         case T___try:
8319                 statement = parse_ms_try_statment();
8320                 break;
8321
8322         default:
8323                 statement = parse_expression_statement();
8324                 break;
8325         }
8326         rem_anchor_token(';');
8327
8328         assert(statement != NULL
8329                         && statement->base.source_position.input_name != NULL);
8330
8331         return statement;
8332 }
8333
8334 /**
8335  * parse a statement and emits "statement has no effect" warning if needed
8336  * (This is really a wrapper around intern_parse_statement with check for 1
8337  *  single warning. It is needed, because for statement expressions we have
8338  *  to avoid the warning on the last statement)
8339  */
8340 static statement_t *parse_statement(void)
8341 {
8342         statement_t *statement = intern_parse_statement();
8343
8344         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8345                 expression_t *expression = statement->expression.expression;
8346                 if (!expression_has_effect(expression)) {
8347                         warningf(&expression->base.source_position,
8348                                         "statement has no effect");
8349                 }
8350         }
8351
8352         return statement;
8353 }
8354
8355 /**
8356  * Parse a compound statement.
8357  */
8358 static statement_t *parse_compound_statement(bool inside_expression_statement)
8359 {
8360         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8361
8362         statement->base.source_position = token.source_position;
8363
8364         eat('{');
8365         add_anchor_token('}');
8366
8367         int      top        = environment_top();
8368         scope_t *last_scope = scope;
8369         set_scope(&statement->compound.scope);
8370
8371         statement_t *last_statement = NULL;
8372
8373         while(token.type != '}' && token.type != T_EOF) {
8374                 statement_t *sub_statement = intern_parse_statement();
8375                 if (is_invalid_statement(sub_statement)) {
8376                         /* an error occurred. if we are at an anchor, return */
8377                         if (at_anchor())
8378                                 goto end_error;
8379                         continue;
8380                 }
8381
8382                 if (last_statement != NULL) {
8383                         last_statement->base.next = sub_statement;
8384                 } else {
8385                         statement->compound.statements = sub_statement;
8386                 }
8387
8388                 while(sub_statement->base.next != NULL)
8389                         sub_statement = sub_statement->base.next;
8390
8391                 last_statement = sub_statement;
8392         }
8393
8394         if (token.type == '}') {
8395                 next_token();
8396         } else {
8397                 errorf(&statement->base.source_position,
8398                        "end of file while looking for closing '}'");
8399         }
8400
8401         /* look over all statements again to produce no effect warnings */
8402         if (warning.unused_value) {
8403                 statement_t *sub_statement = statement->compound.statements;
8404                 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8405                         if (sub_statement->kind != STATEMENT_EXPRESSION)
8406                                 continue;
8407                         /* don't emit a warning for the last expression in an expression
8408                          * statement as it has always an effect */
8409                         if (inside_expression_statement && sub_statement->base.next == NULL)
8410                                 continue;
8411
8412                         expression_t *expression = sub_statement->expression.expression;
8413                         if (!expression_has_effect(expression)) {
8414                                 warningf(&expression->base.source_position,
8415                                          "statement has no effect");
8416                         }
8417                 }
8418         }
8419
8420 end_error:
8421         rem_anchor_token('}');
8422         assert(scope == &statement->compound.scope);
8423         set_scope(last_scope);
8424         environment_pop_to(top);
8425
8426         return statement;
8427 }
8428
8429 /**
8430  * Initialize builtin types.
8431  */
8432 static void initialize_builtin_types(void)
8433 {
8434         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
8435         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
8436         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
8437         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
8438         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
8439         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8440         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
8441         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
8442
8443         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
8444         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8445         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
8446         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
8447 }
8448
8449 /**
8450  * Check for unused global static functions and variables
8451  */
8452 static void check_unused_globals(void)
8453 {
8454         if (!warning.unused_function && !warning.unused_variable)
8455                 return;
8456
8457         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8458                 if (decl->used                ||
8459                     decl->modifiers & DM_USED ||
8460                     decl->storage_class != STORAGE_CLASS_STATIC)
8461                         continue;
8462
8463                 type_t *const type = decl->type;
8464                 const char *s;
8465                 if (is_type_function(skip_typeref(type))) {
8466                         if (!warning.unused_function || decl->is_inline)
8467                                 continue;
8468
8469                         s = (decl->init.statement != NULL ? "defined" : "declared");
8470                 } else {
8471                         if (!warning.unused_variable)
8472                                 continue;
8473
8474                         s = "defined";
8475                 }
8476
8477                 warningf(&decl->source_position, "'%#T' %s but not used",
8478                         type, decl->symbol, s);
8479         }
8480 }
8481
8482 static void parse_global_asm(void)
8483 {
8484         eat(T_asm);
8485         expect('(');
8486
8487         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
8488         statement->base.source_position = token.source_position;
8489         statement->asms.asm_text        = parse_string_literals();
8490         statement->base.next            = unit->global_asm;
8491         unit->global_asm                = statement;
8492
8493         expect(')');
8494         expect(';');
8495
8496 end_error:;
8497 }
8498
8499 /**
8500  * Parse a translation unit.
8501  */
8502 static void parse_translation_unit(void)
8503 {
8504         while(token.type != T_EOF) {
8505                 switch (token.type) {
8506                         case ';':
8507                                 /* TODO error in strict mode */
8508                                 warningf(HERE, "stray ';' outside of function");
8509                                 next_token();
8510                                 break;
8511
8512                         case T_asm:
8513                                 parse_global_asm();
8514                                 break;
8515
8516                         default:
8517                                 parse_external_declaration();
8518                                 break;
8519                 }
8520         }
8521 }
8522
8523 /**
8524  * Parse the input.
8525  *
8526  * @return  the translation unit or NULL if errors occurred.
8527  */
8528 void start_parsing(void)
8529 {
8530         environment_stack = NEW_ARR_F(stack_entry_t, 0);
8531         label_stack       = NEW_ARR_F(stack_entry_t, 0);
8532         diagnostic_count  = 0;
8533         error_count       = 0;
8534         warning_count     = 0;
8535
8536         type_set_output(stderr);
8537         ast_set_output(stderr);
8538
8539         assert(unit == NULL);
8540         unit = allocate_ast_zero(sizeof(unit[0]));
8541
8542         assert(global_scope == NULL);
8543         global_scope = &unit->scope;
8544
8545         assert(scope == NULL);
8546         set_scope(&unit->scope);
8547
8548         initialize_builtin_types();
8549 }
8550
8551 translation_unit_t *finish_parsing(void)
8552 {
8553         assert(scope == &unit->scope);
8554         scope          = NULL;
8555         last_declaration = NULL;
8556
8557         assert(global_scope == &unit->scope);
8558         check_unused_globals();
8559         global_scope = NULL;
8560
8561         DEL_ARR_F(environment_stack);
8562         DEL_ARR_F(label_stack);
8563
8564         translation_unit_t *result = unit;
8565         unit = NULL;
8566         return result;
8567 }
8568
8569 void parse(void)
8570 {
8571         lookahead_bufpos = 0;
8572         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8573                 next_token();
8574         }
8575         parse_translation_unit();
8576 }
8577
8578 /**
8579  * Initialize the parser.
8580  */
8581 void init_parser(void)
8582 {
8583         if (c_mode & _MS) {
8584                 /* add predefined symbols for extended-decl-modifier */
8585                 sym_align      = symbol_table_insert("align");
8586                 sym_allocate   = symbol_table_insert("allocate");
8587                 sym_dllimport  = symbol_table_insert("dllimport");
8588                 sym_dllexport  = symbol_table_insert("dllexport");
8589                 sym_naked      = symbol_table_insert("naked");
8590                 sym_noinline   = symbol_table_insert("noinline");
8591                 sym_noreturn   = symbol_table_insert("noreturn");
8592                 sym_nothrow    = symbol_table_insert("nothrow");
8593                 sym_novtable   = symbol_table_insert("novtable");
8594                 sym_property   = symbol_table_insert("property");
8595                 sym_get        = symbol_table_insert("get");
8596                 sym_put        = symbol_table_insert("put");
8597                 sym_selectany  = symbol_table_insert("selectany");
8598                 sym_thread     = symbol_table_insert("thread");
8599                 sym_uuid       = symbol_table_insert("uuid");
8600                 sym_deprecated = symbol_table_insert("deprecated");
8601                 sym_restrict   = symbol_table_insert("restrict");
8602                 sym_noalias    = symbol_table_insert("noalias");
8603         }
8604         memset(token_anchor_set, 0, sizeof(token_anchor_set));
8605
8606         init_expression_parsers();
8607         obstack_init(&temp_obst);
8608
8609         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8610         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8611 }
8612
8613 /**
8614  * Terminate the parser.
8615  */
8616 void exit_parser(void)
8617 {
8618         obstack_free(&temp_obst, NULL);
8619 }