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