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