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