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