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