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