e791fbaf1667087639118dc29ef1bb309fe0ec72
[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 end_error:
2677         return (construct_type_t*) construct_function_type;
2678 }
2679
2680 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2681                 bool may_be_abstract)
2682 {
2683         /* construct a single linked list of construct_type_t's which describe
2684          * how to construct the final declarator type */
2685         construct_type_t *first = NULL;
2686         construct_type_t *last  = NULL;
2687
2688         /* pointers */
2689         while(token.type == '*') {
2690                 construct_type_t *type = parse_pointer_declarator();
2691
2692                 if(last == NULL) {
2693                         first = type;
2694                         last  = type;
2695                 } else {
2696                         last->next = type;
2697                         last       = type;
2698                 }
2699         }
2700
2701         /* TODO: find out if this is correct */
2702         parse_attributes();
2703
2704         construct_type_t *inner_types = NULL;
2705
2706         switch(token.type) {
2707         case T_IDENTIFIER:
2708                 if(declaration == NULL) {
2709                         errorf(HERE, "no identifier expected in typename");
2710                 } else {
2711                         declaration->symbol          = token.v.symbol;
2712                         declaration->source_position = token.source_position;
2713                 }
2714                 next_token();
2715                 break;
2716         case '(':
2717                 next_token();
2718                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2719                 expect(')');
2720                 break;
2721         default:
2722                 if(may_be_abstract)
2723                         break;
2724                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2725                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2726                  * eat '}' */
2727                 if(token.type == '}' && current_function == NULL) {
2728                         next_token();
2729                 } else {
2730                         eat_statement();
2731                 }
2732                 return NULL;
2733         }
2734
2735         construct_type_t *p = last;
2736
2737         while(true) {
2738                 construct_type_t *type;
2739                 switch(token.type) {
2740                 case '(':
2741                         type = parse_function_declarator(declaration);
2742                         break;
2743                 case '[':
2744                         type = parse_array_declarator();
2745                         break;
2746                 default:
2747                         goto declarator_finished;
2748                 }
2749
2750                 /* insert in the middle of the list (behind p) */
2751                 if(p != NULL) {
2752                         type->next = p->next;
2753                         p->next    = type;
2754                 } else {
2755                         type->next = first;
2756                         first      = type;
2757                 }
2758                 if(last == p) {
2759                         last = type;
2760                 }
2761         }
2762
2763 declarator_finished:
2764         parse_attributes();
2765
2766         /* append inner_types at the end of the list, we don't to set last anymore
2767          * as it's not needed anymore */
2768         if(last == NULL) {
2769                 assert(first == NULL);
2770                 first = inner_types;
2771         } else {
2772                 last->next = inner_types;
2773         }
2774
2775         return first;
2776 end_error:
2777         return NULL;
2778 }
2779
2780 static type_t *construct_declarator_type(construct_type_t *construct_list,
2781                                          type_t *type)
2782 {
2783         construct_type_t *iter = construct_list;
2784         for( ; iter != NULL; iter = iter->next) {
2785                 switch(iter->kind) {
2786                 case CONSTRUCT_INVALID:
2787                         panic("invalid type construction found");
2788                 case CONSTRUCT_FUNCTION: {
2789                         construct_function_type_t *construct_function_type
2790                                 = (construct_function_type_t*) iter;
2791
2792                         type_t *function_type = construct_function_type->function_type;
2793
2794                         function_type->function.return_type = type;
2795
2796                         type_t *skipped_return_type = skip_typeref(type);
2797                         if (is_type_function(skipped_return_type)) {
2798                                 errorf(HERE, "function returning function is not allowed");
2799                                 type = type_error_type;
2800                         } else if (is_type_array(skipped_return_type)) {
2801                                 errorf(HERE, "function returning array is not allowed");
2802                                 type = type_error_type;
2803                         } else {
2804                                 type = function_type;
2805                         }
2806                         break;
2807                 }
2808
2809                 case CONSTRUCT_POINTER: {
2810                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2811                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2812                         pointer_type->pointer.points_to  = type;
2813                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2814
2815                         type = pointer_type;
2816                         break;
2817                 }
2818
2819                 case CONSTRUCT_ARRAY: {
2820                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2821                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2822
2823                         expression_t *size_expression = parsed_array->size;
2824                         if(size_expression != NULL) {
2825                                 size_expression
2826                                         = create_implicit_cast(size_expression, type_size_t);
2827                         }
2828
2829                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
2830                         array_type->array.element_type    = type;
2831                         array_type->array.is_static       = parsed_array->is_static;
2832                         array_type->array.is_variable     = parsed_array->is_variable;
2833                         array_type->array.size_expression = size_expression;
2834
2835                         if(size_expression != NULL) {
2836                                 if(is_constant_expression(size_expression)) {
2837                                         array_type->array.size_constant = true;
2838                                         array_type->array.size
2839                                                 = fold_constant(size_expression);
2840                                 } else {
2841                                         array_type->array.is_vla = true;
2842                                 }
2843                         }
2844
2845                         type_t *skipped_type = skip_typeref(type);
2846                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2847                                 errorf(HERE, "array of void is not allowed");
2848                                 type = type_error_type;
2849                         } else {
2850                                 type = array_type;
2851                         }
2852                         break;
2853                 }
2854                 }
2855
2856                 type_t *hashed_type = typehash_insert(type);
2857                 if(hashed_type != type) {
2858                         /* the function type was constructed earlier freeing it here will
2859                          * destroy other types... */
2860                         if(iter->kind != CONSTRUCT_FUNCTION) {
2861                                 free_type(type);
2862                         }
2863                         type = hashed_type;
2864                 }
2865         }
2866
2867         return type;
2868 }
2869
2870 static declaration_t *parse_declarator(
2871                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2872 {
2873         declaration_t *const declaration    = allocate_declaration_zero();
2874         declaration->declared_storage_class = specifiers->declared_storage_class;
2875         declaration->modifiers              = specifiers->decl_modifiers;
2876         declaration->deprecated_string      = specifiers->deprecated_string;
2877         declaration->get_property_sym       = specifiers->get_property_sym;
2878         declaration->put_property_sym       = specifiers->put_property_sym;
2879         declaration->is_inline              = specifiers->is_inline;
2880
2881         declaration->storage_class          = specifiers->declared_storage_class;
2882         if(declaration->storage_class == STORAGE_CLASS_NONE
2883                         && scope != global_scope) {
2884                 declaration->storage_class = STORAGE_CLASS_AUTO;
2885         }
2886
2887         if(specifiers->alignment != 0) {
2888                 /* TODO: add checks here */
2889                 declaration->alignment = specifiers->alignment;
2890         }
2891
2892         construct_type_t *construct_type
2893                 = parse_inner_declarator(declaration, may_be_abstract);
2894         type_t *const type = specifiers->type;
2895         declaration->type = construct_declarator_type(construct_type, type);
2896
2897         if(construct_type != NULL) {
2898                 obstack_free(&temp_obst, construct_type);
2899         }
2900
2901         return declaration;
2902 }
2903
2904 static type_t *parse_abstract_declarator(type_t *base_type)
2905 {
2906         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2907
2908         type_t *result = construct_declarator_type(construct_type, base_type);
2909         if(construct_type != NULL) {
2910                 obstack_free(&temp_obst, construct_type);
2911         }
2912
2913         return result;
2914 }
2915
2916 static declaration_t *append_declaration(declaration_t* const declaration)
2917 {
2918         if (last_declaration != NULL) {
2919                 last_declaration->next = declaration;
2920         } else {
2921                 scope->declarations = declaration;
2922         }
2923         last_declaration = declaration;
2924         return declaration;
2925 }
2926
2927 /**
2928  * Check if the declaration of main is suspicious.  main should be a
2929  * function with external linkage, returning int, taking either zero
2930  * arguments, two, or three arguments of appropriate types, ie.
2931  *
2932  * int main([ int argc, char **argv [, char **env ] ]).
2933  *
2934  * @param decl    the declaration to check
2935  * @param type    the function type of the declaration
2936  */
2937 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2938 {
2939         if (decl->storage_class == STORAGE_CLASS_STATIC) {
2940                 warningf(decl->source_position, "'main' is normally a non-static function");
2941         }
2942         if (skip_typeref(func_type->return_type) != type_int) {
2943                 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2944         }
2945         const function_parameter_t *parm = func_type->parameters;
2946         if (parm != NULL) {
2947                 type_t *const first_type = parm->type;
2948                 if (!types_compatible(skip_typeref(first_type), type_int)) {
2949                         warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2950                 }
2951                 parm = parm->next;
2952                 if (parm != NULL) {
2953                         type_t *const second_type = parm->type;
2954                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2955                                 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2956                         }
2957                         parm = parm->next;
2958                         if (parm != NULL) {
2959                                 type_t *const third_type = parm->type;
2960                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2961                                         warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2962                                 }
2963                                 parm = parm->next;
2964                                 if (parm != NULL) {
2965                                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2966                                 }
2967                         }
2968                 } else {
2969                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2970                 }
2971         }
2972 }
2973
2974 /**
2975  * Check if a symbol is the equal to "main".
2976  */
2977 static bool is_sym_main(const symbol_t *const sym)
2978 {
2979         return strcmp(sym->string, "main") == 0;
2980 }
2981
2982 static declaration_t *internal_record_declaration(
2983         declaration_t *const declaration,
2984         const bool is_function_definition)
2985 {
2986         const symbol_t *const symbol  = declaration->symbol;
2987         const namespace_t     namespc = (namespace_t)declaration->namespc;
2988
2989         type_t *const orig_type = declaration->type;
2990         type_t *const type      = skip_typeref(orig_type);
2991         if (is_type_function(type) &&
2992                         type->function.unspecified_parameters &&
2993                         warning.strict_prototypes) {
2994                 warningf(declaration->source_position,
2995                          "function declaration '%#T' is not a prototype",
2996                          orig_type, declaration->symbol);
2997         }
2998
2999         if (is_function_definition && warning.main && is_sym_main(symbol)) {
3000                 check_type_of_main(declaration, &type->function);
3001         }
3002
3003         assert(declaration->symbol != NULL);
3004         declaration_t *previous_declaration = get_declaration(symbol, namespc);
3005
3006         assert(declaration != previous_declaration);
3007         if (previous_declaration != NULL) {
3008                 if (previous_declaration->parent_scope == scope) {
3009                         /* can happen for K&R style declarations */
3010                         if(previous_declaration->type == NULL) {
3011                                 previous_declaration->type = declaration->type;
3012                         }
3013
3014                         const type_t *prev_type = skip_typeref(previous_declaration->type);
3015                         if (!types_compatible(type, prev_type)) {
3016                                 errorf(declaration->source_position,
3017                                        "declaration '%#T' is incompatible with "
3018                                        "previous declaration '%#T'",
3019                                        orig_type, symbol, previous_declaration->type, symbol);
3020                                 errorf(previous_declaration->source_position,
3021                                        "previous declaration of '%Y' was here", symbol);
3022                         } else {
3023                                 unsigned old_storage_class = previous_declaration->storage_class;
3024                                 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3025                                         errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3026                                         errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3027                                         return previous_declaration;
3028                                 }
3029
3030                                 unsigned new_storage_class = declaration->storage_class;
3031
3032                                 if(is_type_incomplete(prev_type)) {
3033                                         previous_declaration->type = type;
3034                                         prev_type                  = type;
3035                                 }
3036
3037                                 /* pretend no storage class means extern for function
3038                                  * declarations (except if the previous declaration is neither
3039                                  * none nor extern) */
3040                                 if (is_type_function(type)) {
3041                                         switch (old_storage_class) {
3042                                                 case STORAGE_CLASS_NONE:
3043                                                         old_storage_class = STORAGE_CLASS_EXTERN;
3044
3045                                                 case STORAGE_CLASS_EXTERN:
3046                                                         if (is_function_definition) {
3047                                                                 if (warning.missing_prototypes &&
3048                                                                     prev_type->function.unspecified_parameters &&
3049                                                                     !is_sym_main(symbol)) {
3050                                                                         warningf(declaration->source_position,
3051                                                                                  "no previous prototype for '%#T'",
3052                                                                                  orig_type, symbol);
3053                                                                 }
3054                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
3055                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
3056                                                         }
3057                                                         break;
3058
3059                                                 default: break;
3060                                         }
3061                                 }
3062
3063                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3064                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
3065 warn_redundant_declaration:
3066                                         if (warning.redundant_decls) {
3067                                                 warningf(declaration->source_position,
3068                                                          "redundant declaration for '%Y'", symbol);
3069                                                 warningf(previous_declaration->source_position,
3070                                                          "previous declaration of '%Y' was here",
3071                                                          symbol);
3072                                         }
3073                                 } else if (current_function == NULL) {
3074                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
3075                                                         new_storage_class == STORAGE_CLASS_STATIC) {
3076                                                 errorf(declaration->source_position,
3077                                                        "static declaration of '%Y' follows non-static declaration",
3078                                                        symbol);
3079                                                 errorf(previous_declaration->source_position,
3080                                                        "previous declaration of '%Y' was here", symbol);
3081                                         } else {
3082                                                 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3083                                                         goto warn_redundant_declaration;
3084                                                 }
3085                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
3086                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
3087                                                         previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3088                                                 }
3089                                         }
3090                                 } else {
3091                                         if (old_storage_class == new_storage_class) {
3092                                                 errorf(declaration->source_position,
3093                                                        "redeclaration of '%Y'", symbol);
3094                                         } else {
3095                                                 errorf(declaration->source_position,
3096                                                        "redeclaration of '%Y' with different linkage",
3097                                                        symbol);
3098                                         }
3099                                         errorf(previous_declaration->source_position,
3100                                                "previous declaration of '%Y' was here", symbol);
3101                                 }
3102                         }
3103                         return previous_declaration;
3104                 }
3105         } else if (is_function_definition) {
3106                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3107                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
3108                                 warningf(declaration->source_position,
3109                                          "no previous prototype for '%#T'", orig_type, symbol);
3110                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3111                                 warningf(declaration->source_position,
3112                                          "no previous declaration for '%#T'", orig_type,
3113                                          symbol);
3114                         }
3115                 }
3116         } else if (warning.missing_declarations &&
3117             scope == global_scope &&
3118             !is_type_function(type) && (
3119               declaration->storage_class == STORAGE_CLASS_NONE ||
3120               declaration->storage_class == STORAGE_CLASS_THREAD
3121             )) {
3122                 warningf(declaration->source_position,
3123                          "no previous declaration for '%#T'", orig_type, symbol);
3124         }
3125
3126         assert(declaration->parent_scope == NULL);
3127         assert(scope != NULL);
3128
3129         declaration->parent_scope = scope;
3130
3131         environment_push(declaration);
3132         return append_declaration(declaration);
3133 }
3134
3135 static declaration_t *record_declaration(declaration_t *declaration)
3136 {
3137         return internal_record_declaration(declaration, false);
3138 }
3139
3140 static declaration_t *record_function_definition(declaration_t *declaration)
3141 {
3142         return internal_record_declaration(declaration, true);
3143 }
3144
3145 static void parser_error_multiple_definition(declaration_t *declaration,
3146                 const source_position_t source_position)
3147 {
3148         errorf(source_position, "multiple definition of symbol '%Y'",
3149                declaration->symbol);
3150         errorf(declaration->source_position,
3151                "this is the location of the previous definition.");
3152 }
3153
3154 static bool is_declaration_specifier(const token_t *token,
3155                                      bool only_type_specifiers)
3156 {
3157         switch(token->type) {
3158                 TYPE_SPECIFIERS
3159                         return true;
3160                 case T_IDENTIFIER:
3161                         return is_typedef_symbol(token->v.symbol);
3162
3163                 case T___extension__:
3164                 STORAGE_CLASSES
3165                 TYPE_QUALIFIERS
3166                         return !only_type_specifiers;
3167
3168                 default:
3169                         return false;
3170         }
3171 }
3172
3173 static void parse_init_declarator_rest(declaration_t *declaration)
3174 {
3175         eat('=');
3176
3177         type_t *orig_type = declaration->type;
3178         type_t *type      = skip_typeref(orig_type);
3179
3180         if(declaration->init.initializer != NULL) {
3181                 parser_error_multiple_definition(declaration, token.source_position);
3182         }
3183
3184         bool must_be_constant = false;
3185         if(declaration->storage_class == STORAGE_CLASS_STATIC
3186                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3187                         || declaration->parent_scope == global_scope) {
3188                 must_be_constant = true;
3189         }
3190
3191         parse_initializer_env_t env;
3192         env.type             = orig_type;
3193         env.must_be_constant = must_be_constant;
3194         env.declaration      = declaration;
3195
3196         initializer_t *initializer = parse_initializer(&env);
3197
3198         if(env.type != orig_type) {
3199                 orig_type         = env.type;
3200                 type              = skip_typeref(orig_type);
3201                 declaration->type = env.type;
3202         }
3203
3204         if(is_type_function(type)) {
3205                 errorf(declaration->source_position,
3206                        "initializers not allowed for function types at declator '%Y' (type '%T')",
3207                        declaration->symbol, orig_type);
3208         } else {
3209                 declaration->init.initializer = initializer;
3210         }
3211 }
3212
3213 /* parse rest of a declaration without any declarator */
3214 static void parse_anonymous_declaration_rest(
3215                 const declaration_specifiers_t *specifiers,
3216                 parsed_declaration_func finished_declaration)
3217 {
3218         eat(';');
3219
3220         declaration_t *const declaration    = allocate_declaration_zero();
3221         declaration->type                   = specifiers->type;
3222         declaration->declared_storage_class = specifiers->declared_storage_class;
3223         declaration->source_position        = specifiers->source_position;
3224         declaration->modifiers              = specifiers->decl_modifiers;
3225
3226         if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3227                 warningf(declaration->source_position, "useless storage class in empty declaration");
3228         }
3229         declaration->storage_class = STORAGE_CLASS_NONE;
3230
3231         type_t *type = declaration->type;
3232         switch (type->kind) {
3233                 case TYPE_COMPOUND_STRUCT:
3234                 case TYPE_COMPOUND_UNION: {
3235                         if (type->compound.declaration->symbol == NULL) {
3236                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3237                         }
3238                         break;
3239                 }
3240
3241                 case TYPE_ENUM:
3242                         break;
3243
3244                 default:
3245                         warningf(declaration->source_position, "empty declaration");
3246                         break;
3247         }
3248
3249         finished_declaration(declaration);
3250 }
3251
3252 static void parse_declaration_rest(declaration_t *ndeclaration,
3253                 const declaration_specifiers_t *specifiers,
3254                 parsed_declaration_func finished_declaration)
3255 {
3256         while(true) {
3257                 declaration_t *declaration = finished_declaration(ndeclaration);
3258
3259                 type_t *orig_type = declaration->type;
3260                 type_t *type      = skip_typeref(orig_type);
3261
3262                 if (type->kind != TYPE_FUNCTION &&
3263                     declaration->is_inline &&
3264                     is_type_valid(type)) {
3265                         warningf(declaration->source_position,
3266                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
3267                 }
3268
3269                 if(token.type == '=') {
3270                         parse_init_declarator_rest(declaration);
3271                 }
3272
3273                 if(token.type != ',')
3274                         break;
3275                 eat(',');
3276
3277                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3278         }
3279         expect(';');
3280
3281 end_error:
3282         ;
3283 }
3284
3285 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3286 {
3287         symbol_t *symbol  = declaration->symbol;
3288         if(symbol == NULL) {
3289                 errorf(HERE, "anonymous declaration not valid as function parameter");
3290                 return declaration;
3291         }
3292         namespace_t namespc = (namespace_t) declaration->namespc;
3293         if(namespc != NAMESPACE_NORMAL) {
3294                 return record_declaration(declaration);
3295         }
3296
3297         declaration_t *previous_declaration = get_declaration(symbol, namespc);
3298         if(previous_declaration == NULL ||
3299                         previous_declaration->parent_scope != scope) {
3300                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3301                        symbol);
3302                 return declaration;
3303         }
3304
3305         if(previous_declaration->type == NULL) {
3306                 previous_declaration->type          = declaration->type;
3307                 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3308                 previous_declaration->storage_class = declaration->storage_class;
3309                 previous_declaration->parent_scope  = scope;
3310                 return previous_declaration;
3311         } else {
3312                 return record_declaration(declaration);
3313         }
3314 }
3315
3316 static void parse_declaration(parsed_declaration_func finished_declaration)
3317 {
3318         declaration_specifiers_t specifiers;
3319         memset(&specifiers, 0, sizeof(specifiers));
3320         parse_declaration_specifiers(&specifiers);
3321
3322         if(token.type == ';') {
3323                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3324         } else {
3325                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3326                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3327         }
3328 }
3329
3330 static void parse_kr_declaration_list(declaration_t *declaration)
3331 {
3332         type_t *type = skip_typeref(declaration->type);
3333         if(!is_type_function(type))
3334                 return;
3335
3336         if(!type->function.kr_style_parameters)
3337                 return;
3338
3339         /* push function parameters */
3340         int       top        = environment_top();
3341         scope_t  *last_scope = scope;
3342         set_scope(&declaration->scope);
3343
3344         declaration_t *parameter = declaration->scope.declarations;
3345         for( ; parameter != NULL; parameter = parameter->next) {
3346                 assert(parameter->parent_scope == NULL);
3347                 parameter->parent_scope = scope;
3348                 environment_push(parameter);
3349         }
3350
3351         /* parse declaration list */
3352         while(is_declaration_specifier(&token, false)) {
3353                 parse_declaration(finished_kr_declaration);
3354         }
3355
3356         /* pop function parameters */
3357         assert(scope == &declaration->scope);
3358         set_scope(last_scope);
3359         environment_pop_to(top);
3360
3361         /* update function type */
3362         type_t *new_type = duplicate_type(type);
3363         new_type->function.kr_style_parameters = false;
3364
3365         function_parameter_t *parameters     = NULL;
3366         function_parameter_t *last_parameter = NULL;
3367
3368         declaration_t *parameter_declaration = declaration->scope.declarations;
3369         for( ; parameter_declaration != NULL;
3370                         parameter_declaration = parameter_declaration->next) {
3371                 type_t *parameter_type = parameter_declaration->type;
3372                 if(parameter_type == NULL) {
3373                         if (strict_mode) {
3374                                 errorf(HERE, "no type specified for function parameter '%Y'",
3375                                        parameter_declaration->symbol);
3376                         } else {
3377                                 if (warning.implicit_int) {
3378                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3379                                                 parameter_declaration->symbol);
3380                                 }
3381                                 parameter_type              = type_int;
3382                                 parameter_declaration->type = parameter_type;
3383                         }
3384                 }
3385
3386                 semantic_parameter(parameter_declaration);
3387                 parameter_type = parameter_declaration->type;
3388
3389                 function_parameter_t *function_parameter
3390                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3391                 memset(function_parameter, 0, sizeof(function_parameter[0]));
3392
3393                 function_parameter->type = parameter_type;
3394                 if(last_parameter != NULL) {
3395                         last_parameter->next = function_parameter;
3396                 } else {
3397                         parameters = function_parameter;
3398                 }
3399                 last_parameter = function_parameter;
3400         }
3401         new_type->function.parameters = parameters;
3402
3403         type = typehash_insert(new_type);
3404         if(type != new_type) {
3405                 obstack_free(type_obst, new_type);
3406         }
3407
3408         declaration->type = type;
3409 }
3410
3411 static bool first_err = true;
3412
3413 /**
3414  * When called with first_err set, prints the name of the current function,
3415  * else does noting.
3416  */
3417 static void print_in_function(void) {
3418         if (first_err) {
3419                 first_err = false;
3420                 diagnosticf("%s: In function '%Y':\n",
3421                         current_function->source_position.input_name,
3422                         current_function->symbol);
3423         }
3424 }
3425
3426 /**
3427  * Check if all labels are defined in the current function.
3428  * Check if all labels are used in the current function.
3429  */
3430 static void check_labels(void)
3431 {
3432         for (const goto_statement_t *goto_statement = goto_first;
3433             goto_statement != NULL;
3434             goto_statement = goto_statement->next) {
3435                 declaration_t *label = goto_statement->label;
3436
3437                 label->used = true;
3438                 if (label->source_position.input_name == NULL) {
3439                         print_in_function();
3440                         errorf(goto_statement->base.source_position,
3441                                "label '%Y' used but not defined", label->symbol);
3442                  }
3443         }
3444         goto_first = goto_last = NULL;
3445
3446         if (warning.unused_label) {
3447                 for (const label_statement_t *label_statement = label_first;
3448                          label_statement != NULL;
3449                          label_statement = label_statement->next) {
3450                         const declaration_t *label = label_statement->label;
3451
3452                         if (! label->used) {
3453                                 print_in_function();
3454                                 warningf(label_statement->base.source_position,
3455                                         "label '%Y' defined but not used", label->symbol);
3456                         }
3457                 }
3458         }
3459         label_first = label_last = NULL;
3460 }
3461
3462 /**
3463  * Check declarations of current_function for unused entities.
3464  */
3465 static void check_declarations(void)
3466 {
3467         if (warning.unused_parameter) {
3468                 const scope_t *scope = &current_function->scope;
3469
3470                 const declaration_t *parameter = scope->declarations;
3471                 for (; parameter != NULL; parameter = parameter->next) {
3472                         if (! parameter->used) {
3473                                 print_in_function();
3474                                 warningf(parameter->source_position,
3475                                         "unused parameter '%Y'", parameter->symbol);
3476                         }
3477                 }
3478         }
3479         if (warning.unused_variable) {
3480         }
3481 }
3482
3483 static void parse_external_declaration(void)
3484 {
3485         /* function-definitions and declarations both start with declaration
3486          * specifiers */
3487         declaration_specifiers_t specifiers;
3488         memset(&specifiers, 0, sizeof(specifiers));
3489         parse_declaration_specifiers(&specifiers);
3490
3491         /* must be a declaration */
3492         if(token.type == ';') {
3493                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3494                 return;
3495         }
3496
3497         /* declarator is common to both function-definitions and declarations */
3498         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3499
3500         /* must be a declaration */
3501         if(token.type == ',' || token.type == '=' || token.type == ';') {
3502                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3503                 return;
3504         }
3505
3506         /* must be a function definition */
3507         parse_kr_declaration_list(ndeclaration);
3508
3509         if(token.type != '{') {
3510                 parse_error_expected("while parsing function definition", '{', 0);
3511                 eat_statement();
3512                 return;
3513         }
3514
3515         type_t *type = ndeclaration->type;
3516
3517         /* note that we don't skip typerefs: the standard doesn't allow them here
3518          * (so we can't use is_type_function here) */
3519         if(type->kind != TYPE_FUNCTION) {
3520                 if (is_type_valid(type)) {
3521                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
3522                                type, ndeclaration->symbol);
3523                 }
3524                 eat_block();
3525                 return;
3526         }
3527
3528         /* Â§ 6.7.5.3 (14) a function definition with () means no
3529          * parameters (and not unspecified parameters) */
3530         if(type->function.unspecified_parameters) {
3531                 type_t *duplicate = duplicate_type(type);
3532                 duplicate->function.unspecified_parameters = false;
3533
3534                 type = typehash_insert(duplicate);
3535                 if(type != duplicate) {
3536                         obstack_free(type_obst, duplicate);
3537                 }
3538                 ndeclaration->type = type;
3539         }
3540
3541         declaration_t *const declaration = record_function_definition(ndeclaration);
3542         if(ndeclaration != declaration) {
3543                 declaration->scope = ndeclaration->scope;
3544         }
3545         type = skip_typeref(declaration->type);
3546
3547         /* push function parameters and switch scope */
3548         int       top        = environment_top();
3549         scope_t  *last_scope = scope;
3550         set_scope(&declaration->scope);
3551
3552         declaration_t *parameter = declaration->scope.declarations;
3553         for( ; parameter != NULL; parameter = parameter->next) {
3554                 if(parameter->parent_scope == &ndeclaration->scope) {
3555                         parameter->parent_scope = scope;
3556                 }
3557                 assert(parameter->parent_scope == NULL
3558                                 || parameter->parent_scope == scope);
3559                 parameter->parent_scope = scope;
3560                 environment_push(parameter);
3561         }
3562
3563         if(declaration->init.statement != NULL) {
3564                 parser_error_multiple_definition(declaration, token.source_position);
3565                 eat_block();
3566                 goto end_of_parse_external_declaration;
3567         } else {
3568                 /* parse function body */
3569                 int            label_stack_top      = label_top();
3570                 declaration_t *old_current_function = current_function;
3571                 current_function                    = declaration;
3572
3573                 declaration->init.statement = parse_compound_statement();
3574                 first_err = true;
3575                 check_labels();
3576                 check_declarations();
3577
3578                 assert(current_function == declaration);
3579                 current_function = old_current_function;
3580                 label_pop_to(label_stack_top);
3581         }
3582
3583 end_of_parse_external_declaration:
3584         assert(scope == &declaration->scope);
3585         set_scope(last_scope);
3586         environment_pop_to(top);
3587 }
3588
3589 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3590                                   source_position_t source_position)
3591 {
3592         type_t *type        = allocate_type_zero(TYPE_BITFIELD, source_position);
3593         type->bitfield.base = base;
3594         type->bitfield.size = size;
3595
3596         return type;
3597 }
3598
3599 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3600                                           symbol_t *symbol)
3601 {
3602         declaration_t *iter = compound_declaration->scope.declarations;
3603         for( ; iter != NULL; iter = iter->next) {
3604                 if(iter->namespc != NAMESPACE_NORMAL)
3605                         continue;
3606
3607                 if(iter->symbol == NULL) {
3608                         type_t *type = skip_typeref(iter->type);
3609                         if(is_type_compound(type)) {
3610                                 declaration_t *result
3611                                         = find_compound_entry(type->compound.declaration, symbol);
3612                                 if(result != NULL)
3613                                         return result;
3614                         }
3615                         continue;
3616                 }
3617
3618                 if(iter->symbol == symbol) {
3619                         return iter;
3620                 }
3621         }
3622
3623         return NULL;
3624 }
3625
3626 static void parse_compound_declarators(declaration_t *struct_declaration,
3627                 const declaration_specifiers_t *specifiers)
3628 {
3629         declaration_t *last_declaration = struct_declaration->scope.declarations;
3630         if(last_declaration != NULL) {
3631                 while(last_declaration->next != NULL) {
3632                         last_declaration = last_declaration->next;
3633                 }
3634         }
3635
3636         while(1) {
3637                 declaration_t *declaration;
3638
3639                 if(token.type == ':') {
3640                         source_position_t source_position = HERE;
3641                         next_token();
3642
3643                         type_t *base_type = specifiers->type;
3644                         expression_t *size = parse_constant_expression();
3645
3646                         if(!is_type_integer(skip_typeref(base_type))) {
3647                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
3648                                        base_type);
3649                         }
3650
3651                         type_t *type = make_bitfield_type(base_type, size, source_position);
3652
3653                         declaration                         = allocate_declaration_zero();
3654                         declaration->namespc                = NAMESPACE_NORMAL;
3655                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
3656                         declaration->storage_class          = STORAGE_CLASS_NONE;
3657                         declaration->source_position        = source_position;
3658                         declaration->modifiers              = specifiers->decl_modifiers;
3659                         declaration->type                   = type;
3660                 } else {
3661                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3662
3663                         type_t *orig_type = declaration->type;
3664                         type_t *type      = skip_typeref(orig_type);
3665
3666                         if(token.type == ':') {
3667                                 source_position_t source_position = HERE;
3668                                 next_token();
3669                                 expression_t *size = parse_constant_expression();
3670
3671                                 if(!is_type_integer(type)) {
3672                                         errorf(HERE, "bitfield base type '%T' is not an "
3673                                                "integer type", orig_type);
3674                                 }
3675
3676                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3677                                 declaration->type = bitfield_type;
3678                         } else {
3679                                 /* TODO we ignore arrays for now... what is missing is a check
3680                                  * that they're at the end of the struct */
3681                                 if(is_type_incomplete(type) && !is_type_array(type)) {
3682                                         errorf(HERE,
3683                                                "compound member '%Y' has incomplete type '%T'",
3684                                                declaration->symbol, orig_type);
3685                                 } else if(is_type_function(type)) {
3686                                         errorf(HERE, "compound member '%Y' must not have function "
3687                                                "type '%T'", declaration->symbol, orig_type);
3688                                 }
3689                         }
3690                 }
3691
3692                 /* make sure we don't define a symbol multiple times */
3693                 symbol_t *symbol = declaration->symbol;
3694                 if(symbol != NULL) {
3695                         declaration_t *prev_decl
3696                                 = find_compound_entry(struct_declaration, symbol);
3697
3698                         if(prev_decl != NULL) {
3699                                 assert(prev_decl->symbol == symbol);
3700                                 errorf(declaration->source_position,
3701                                        "multiple declarations of symbol '%Y'", symbol);
3702                                 errorf(prev_decl->source_position,
3703                                        "previous declaration of '%Y' was here", symbol);
3704                         }
3705                 }
3706
3707                 /* append declaration */
3708                 if(last_declaration != NULL) {
3709                         last_declaration->next = declaration;
3710                 } else {
3711                         struct_declaration->scope.declarations = declaration;
3712                 }
3713                 last_declaration = declaration;
3714
3715                 if(token.type != ',')
3716                         break;
3717                 next_token();
3718         }
3719         expect(';');
3720
3721 end_error:
3722         ;
3723 }
3724
3725 static void parse_compound_type_entries(declaration_t *compound_declaration)
3726 {
3727         eat('{');
3728
3729         while(token.type != '}' && token.type != T_EOF) {
3730                 declaration_specifiers_t specifiers;
3731                 memset(&specifiers, 0, sizeof(specifiers));
3732                 parse_declaration_specifiers(&specifiers);
3733
3734                 parse_compound_declarators(compound_declaration, &specifiers);
3735         }
3736         if(token.type == T_EOF) {
3737                 errorf(HERE, "EOF while parsing struct");
3738         }
3739         next_token();
3740 }
3741
3742 static type_t *parse_typename(void)
3743 {
3744         declaration_specifiers_t specifiers;
3745         memset(&specifiers, 0, sizeof(specifiers));
3746         parse_declaration_specifiers(&specifiers);
3747         if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3748                 /* TODO: improve error message, user does probably not know what a
3749                  * storage class is...
3750                  */
3751                 errorf(HERE, "typename may not have a storage class");
3752         }
3753
3754         type_t *result = parse_abstract_declarator(specifiers.type);
3755
3756         return result;
3757 }
3758
3759
3760
3761
3762 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3763 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3764                                                           expression_t *left);
3765
3766 typedef struct expression_parser_function_t expression_parser_function_t;
3767 struct expression_parser_function_t {
3768         unsigned                         precedence;
3769         parse_expression_function        parser;
3770         unsigned                         infix_precedence;
3771         parse_expression_infix_function  infix_parser;
3772 };
3773
3774 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3775
3776 /**
3777  * Creates a new invalid expression.
3778  */
3779 static expression_t *create_invalid_expression(void)
3780 {
3781         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
3782         expression->base.source_position = token.source_position;
3783         return expression;
3784 }
3785
3786 /**
3787  * Prints an error message if an expression was expected but not read
3788  */
3789 static expression_t *expected_expression_error(void)
3790 {
3791         /* skip the error message if the error token was read */
3792         if (token.type != T_ERROR) {
3793                 errorf(HERE, "expected expression, got token '%K'", &token);
3794         }
3795         next_token();
3796
3797         return create_invalid_expression();
3798 }
3799
3800 /**
3801  * Parse a string constant.
3802  */
3803 static expression_t *parse_string_const(void)
3804 {
3805         wide_string_t wres;
3806         if (token.type == T_STRING_LITERAL) {
3807                 string_t res = token.v.string;
3808                 next_token();
3809                 while (token.type == T_STRING_LITERAL) {
3810                         res = concat_strings(&res, &token.v.string);
3811                         next_token();
3812                 }
3813                 if (token.type != T_WIDE_STRING_LITERAL) {
3814                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3815                         /* note: that we use type_char_ptr here, which is already the
3816                          * automatic converted type. revert_automatic_type_conversion
3817                          * will construct the array type */
3818                         cnst->base.type    = type_char_ptr;
3819                         cnst->string.value = res;
3820                         return cnst;
3821                 }
3822
3823                 wres = concat_string_wide_string(&res, &token.v.wide_string);
3824         } else {
3825                 wres = token.v.wide_string;
3826         }
3827         next_token();
3828
3829         for (;;) {
3830                 switch (token.type) {
3831                         case T_WIDE_STRING_LITERAL:
3832                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
3833                                 break;
3834
3835                         case T_STRING_LITERAL:
3836                                 wres = concat_wide_string_string(&wres, &token.v.string);
3837                                 break;
3838
3839                         default: {
3840                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3841                                 cnst->base.type         = type_wchar_t_ptr;
3842                                 cnst->wide_string.value = wres;
3843                                 return cnst;
3844                         }
3845                 }
3846                 next_token();
3847         }
3848 }
3849
3850 /**
3851  * Parse an integer constant.
3852  */
3853 static expression_t *parse_int_const(void)
3854 {
3855         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3856         cnst->base.source_position = HERE;
3857         cnst->base.type            = token.datatype;
3858         cnst->conste.v.int_value   = token.v.intvalue;
3859
3860         next_token();
3861
3862         return cnst;
3863 }
3864
3865 /**
3866  * Parse a character constant.
3867  */
3868 static expression_t *parse_character_constant(void)
3869 {
3870         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3871
3872         cnst->base.source_position = HERE;
3873         cnst->base.type            = token.datatype;
3874         cnst->conste.v.character   = token.v.string;
3875
3876         if (cnst->conste.v.character.size != 1) {
3877                 if (warning.multichar && (c_mode & _GNUC)) {
3878                         /* TODO */
3879                         warningf(HERE, "multi-character character constant");
3880                 } else {
3881                         errorf(HERE, "more than 1 characters in character constant");
3882                 }
3883         }
3884         next_token();
3885
3886         return cnst;
3887 }
3888
3889 /**
3890  * Parse a wide character constant.
3891  */
3892 static expression_t *parse_wide_character_constant(void)
3893 {
3894         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3895
3896         cnst->base.source_position    = HERE;
3897         cnst->base.type               = token.datatype;
3898         cnst->conste.v.wide_character = token.v.wide_string;
3899
3900         if (cnst->conste.v.wide_character.size != 1) {
3901                 if (warning.multichar && (c_mode & _GNUC)) {
3902                         /* TODO */
3903                         warningf(HERE, "multi-character character constant");
3904                 } else {
3905                         errorf(HERE, "more than 1 characters in character constant");
3906                 }
3907         }
3908         next_token();
3909
3910         return cnst;
3911 }
3912
3913 /**
3914  * Parse a float constant.
3915  */
3916 static expression_t *parse_float_const(void)
3917 {
3918         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3919         cnst->base.type            = token.datatype;
3920         cnst->conste.v.float_value = token.v.floatvalue;
3921
3922         next_token();
3923
3924         return cnst;
3925 }
3926
3927 static declaration_t *create_implicit_function(symbol_t *symbol,
3928                 const source_position_t source_position)
3929 {
3930         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
3931         ntype->function.return_type            = type_int;
3932         ntype->function.unspecified_parameters = true;
3933
3934         type_t *type = typehash_insert(ntype);
3935         if(type != ntype) {
3936                 free_type(ntype);
3937         }
3938
3939         declaration_t *const declaration    = allocate_declaration_zero();
3940         declaration->storage_class          = STORAGE_CLASS_EXTERN;
3941         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
3942         declaration->type                   = type;
3943         declaration->symbol                 = symbol;
3944         declaration->source_position        = source_position;
3945         declaration->parent_scope           = global_scope;
3946
3947         scope_t *old_scope = scope;
3948         set_scope(global_scope);
3949
3950         environment_push(declaration);
3951         /* prepends the declaration to the global declarations list */
3952         declaration->next   = scope->declarations;
3953         scope->declarations = declaration;
3954
3955         assert(scope == global_scope);
3956         set_scope(old_scope);
3957
3958         return declaration;
3959 }
3960
3961 /**
3962  * Creates a return_type (func)(argument_type) function type if not
3963  * already exists.
3964  *
3965  * @param return_type    the return type
3966  * @param argument_type  the argument type
3967  */
3968 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3969 {
3970         function_parameter_t *parameter
3971                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3972         memset(parameter, 0, sizeof(parameter[0]));
3973         parameter->type = argument_type;
3974
3975         type_t *type               = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3976         type->function.return_type = return_type;
3977         type->function.parameters  = parameter;
3978
3979         type_t *result = typehash_insert(type);
3980         if(result != type) {
3981                 free_type(type);
3982         }
3983
3984         return result;
3985 }
3986
3987 /**
3988  * Creates a function type for some function like builtins.
3989  *
3990  * @param symbol   the symbol describing the builtin
3991  */
3992 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3993 {
3994         switch(symbol->ID) {
3995         case T___builtin_alloca:
3996                 return make_function_1_type(type_void_ptr, type_size_t);
3997         case T___builtin_nan:
3998                 return make_function_1_type(type_double, type_char_ptr);
3999         case T___builtin_nanf:
4000                 return make_function_1_type(type_float, type_char_ptr);
4001         case T___builtin_nand:
4002                 return make_function_1_type(type_long_double, type_char_ptr);
4003         case T___builtin_va_end:
4004                 return make_function_1_type(type_void, type_valist);
4005         default:
4006                 panic("not implemented builtin symbol found");
4007         }
4008 }
4009
4010 /**
4011  * Performs automatic type cast as described in Â§ 6.3.2.1.
4012  *
4013  * @param orig_type  the original type
4014  */
4015 static type_t *automatic_type_conversion(type_t *orig_type)
4016 {
4017         type_t *type = skip_typeref(orig_type);
4018         if(is_type_array(type)) {
4019                 array_type_t *array_type   = &type->array;
4020                 type_t       *element_type = array_type->element_type;
4021                 unsigned      qualifiers   = array_type->type.qualifiers;
4022
4023                 return make_pointer_type(element_type, qualifiers);
4024         }
4025
4026         if(is_type_function(type)) {
4027                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4028         }
4029
4030         return orig_type;
4031 }
4032
4033 /**
4034  * reverts the automatic casts of array to pointer types and function
4035  * to function-pointer types as defined Â§ 6.3.2.1
4036  */
4037 type_t *revert_automatic_type_conversion(const expression_t *expression)
4038 {
4039         switch (expression->kind) {
4040                 case EXPR_REFERENCE: return expression->reference.declaration->type;
4041                 case EXPR_SELECT:    return expression->select.compound_entry->type;
4042
4043                 case EXPR_UNARY_DEREFERENCE: {
4044                         const expression_t *const value = expression->unary.value;
4045                         type_t             *const type  = skip_typeref(value->base.type);
4046                         assert(is_type_pointer(type));
4047                         return type->pointer.points_to;
4048                 }
4049
4050                 case EXPR_BUILTIN_SYMBOL:
4051                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4052
4053                 case EXPR_ARRAY_ACCESS: {
4054                         const expression_t *array_ref = expression->array_access.array_ref;
4055                         type_t             *type_left = skip_typeref(array_ref->base.type);
4056                         if (!is_type_valid(type_left))
4057                                 return type_left;
4058                         assert(is_type_pointer(type_left));
4059                         return type_left->pointer.points_to;
4060                 }
4061
4062                 case EXPR_STRING_LITERAL: {
4063                         size_t size = expression->string.value.size;
4064                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4065                 }
4066
4067                 case EXPR_WIDE_STRING_LITERAL: {
4068                         size_t size = expression->wide_string.value.size;
4069                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4070                 }
4071
4072                 case EXPR_COMPOUND_LITERAL:
4073                         return expression->compound_literal.type;
4074
4075                 default: break;
4076         }
4077
4078         return expression->base.type;
4079 }
4080
4081 static expression_t *parse_reference(void)
4082 {
4083         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4084
4085         reference_expression_t *ref = &expression->reference;
4086         ref->symbol = token.v.symbol;
4087
4088         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4089
4090         source_position_t source_position = token.source_position;
4091         next_token();
4092
4093         if(declaration == NULL) {
4094                 if (! strict_mode && token.type == '(') {
4095                         /* an implicitly defined function */
4096                         if (warning.implicit_function_declaration) {
4097                                 warningf(HERE, "implicit declaration of function '%Y'",
4098                                         ref->symbol);
4099                         }
4100
4101                         declaration = create_implicit_function(ref->symbol,
4102                                                                source_position);
4103                 } else {
4104                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4105                         return create_invalid_expression();
4106                 }
4107         }
4108
4109         type_t *type         = declaration->type;
4110
4111         /* we always do the auto-type conversions; the & and sizeof parser contains
4112          * code to revert this! */
4113         type = automatic_type_conversion(type);
4114
4115         ref->declaration = declaration;
4116         ref->base.type   = type;
4117
4118         /* this declaration is used */
4119         declaration->used = true;
4120
4121         return expression;
4122 }
4123
4124 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4125 {
4126         (void) expression;
4127         (void) dest_type;
4128         /* TODO check if explicit cast is allowed and issue warnings/errors */
4129 }
4130
4131 static expression_t *parse_compound_literal(type_t *type)
4132 {
4133         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4134
4135         parse_initializer_env_t env;
4136         env.type             = type;
4137         env.declaration      = NULL;
4138         env.must_be_constant = false;
4139         initializer_t *initializer = parse_initializer(&env);
4140         type = env.type;
4141
4142         expression->compound_literal.initializer = initializer;
4143         expression->compound_literal.type        = type;
4144         expression->base.type                    = automatic_type_conversion(type);
4145
4146         return expression;
4147 }
4148
4149 /**
4150  * Parse a cast expression.
4151  */
4152 static expression_t *parse_cast(void)
4153 {
4154         source_position_t source_position = token.source_position;
4155
4156         type_t *type  = parse_typename();
4157
4158         expect(')');
4159
4160         if(token.type == '{') {
4161                 return parse_compound_literal(type);
4162         }
4163
4164         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4165         cast->base.source_position = source_position;
4166
4167         expression_t *value = parse_sub_expression(20);
4168
4169         check_cast_allowed(value, type);
4170
4171         cast->base.type   = type;
4172         cast->unary.value = value;
4173
4174         return cast;
4175 end_error:
4176         return create_invalid_expression();
4177 }
4178
4179 /**
4180  * Parse a statement expression.
4181  */
4182 static expression_t *parse_statement_expression(void)
4183 {
4184         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4185
4186         statement_t *statement           = parse_compound_statement();
4187         expression->statement.statement  = statement;
4188         expression->base.source_position = statement->base.source_position;
4189
4190         /* find last statement and use its type */
4191         type_t *type = type_void;
4192         const statement_t *stmt = statement->compound.statements;
4193         if (stmt != NULL) {
4194                 while (stmt->base.next != NULL)
4195                         stmt = stmt->base.next;
4196
4197                 if (stmt->kind == STATEMENT_EXPRESSION) {
4198                         type = stmt->expression.expression->base.type;
4199                 }
4200         } else {
4201                 warningf(expression->base.source_position, "empty statement expression ({})");
4202         }
4203         expression->base.type = type;
4204
4205         expect(')');
4206
4207         return expression;
4208 end_error:
4209         return create_invalid_expression();
4210 }
4211
4212 /**
4213  * Parse a braced expression.
4214  */
4215 static expression_t *parse_brace_expression(void)
4216 {
4217         eat('(');
4218
4219         switch(token.type) {
4220         case '{':
4221                 /* gcc extension: a statement expression */
4222                 return parse_statement_expression();
4223
4224         TYPE_QUALIFIERS
4225         TYPE_SPECIFIERS
4226                 return parse_cast();
4227         case T_IDENTIFIER:
4228                 if(is_typedef_symbol(token.v.symbol)) {
4229                         return parse_cast();
4230                 }
4231         }
4232
4233         expression_t *result = parse_expression();
4234         expect(')');
4235
4236         return result;
4237 end_error:
4238         return create_invalid_expression();
4239 }
4240
4241 static expression_t *parse_function_keyword(void)
4242 {
4243         next_token();
4244         /* TODO */
4245
4246         if (current_function == NULL) {
4247                 errorf(HERE, "'__func__' used outside of a function");
4248         }
4249
4250         expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4251         expression->base.type    = type_char_ptr;
4252
4253         return expression;
4254 }
4255
4256 static expression_t *parse_pretty_function_keyword(void)
4257 {
4258         eat(T___PRETTY_FUNCTION__);
4259         /* TODO */
4260
4261         if (current_function == NULL) {
4262                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4263         }
4264
4265         expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4266         expression->base.type    = type_char_ptr;
4267
4268         return expression;
4269 }
4270
4271 static designator_t *parse_designator(void)
4272 {
4273         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
4274         result->source_position = HERE;
4275
4276         if(token.type != T_IDENTIFIER) {
4277                 parse_error_expected("while parsing member designator",
4278                                      T_IDENTIFIER, 0);
4279                 eat_paren();
4280                 return NULL;
4281         }
4282         result->symbol = token.v.symbol;
4283         next_token();
4284
4285         designator_t *last_designator = result;
4286         while(true) {
4287                 if(token.type == '.') {
4288                         next_token();
4289                         if(token.type != T_IDENTIFIER) {
4290                                 parse_error_expected("while parsing member designator",
4291                                                      T_IDENTIFIER, 0);
4292                                 eat_paren();
4293                                 return NULL;
4294                         }
4295                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
4296                         designator->source_position = HERE;
4297                         designator->symbol          = token.v.symbol;
4298                         next_token();
4299
4300                         last_designator->next = designator;
4301                         last_designator       = designator;
4302                         continue;
4303                 }
4304                 if(token.type == '[') {
4305                         next_token();
4306                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
4307                         designator->source_position = HERE;
4308                         designator->array_index     = parse_expression();
4309                         if(designator->array_index == NULL) {
4310                                 eat_paren();
4311                                 return NULL;
4312                         }
4313                         expect(']');
4314
4315                         last_designator->next = designator;
4316                         last_designator       = designator;
4317                         continue;
4318                 }
4319                 break;
4320         }
4321
4322         return result;
4323 end_error:
4324         return NULL;
4325 }
4326
4327 /**
4328  * Parse the __builtin_offsetof() expression.
4329  */
4330 static expression_t *parse_offsetof(void)
4331 {
4332         eat(T___builtin_offsetof);
4333
4334         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4335         expression->base.type    = type_size_t;
4336
4337         expect('(');
4338         type_t *type = parse_typename();
4339         expect(',');
4340         designator_t *designator = parse_designator();
4341         expect(')');
4342
4343         expression->offsetofe.type       = type;
4344         expression->offsetofe.designator = designator;
4345
4346         type_path_t path;
4347         memset(&path, 0, sizeof(path));
4348         path.top_type = type;
4349         path.path     = NEW_ARR_F(type_path_entry_t, 0);
4350
4351         descend_into_subtype(&path);
4352
4353         if(!walk_designator(&path, designator, true)) {
4354                 return create_invalid_expression();
4355         }
4356
4357         DEL_ARR_F(path.path);
4358
4359         return expression;
4360 end_error:
4361         return create_invalid_expression();
4362 }
4363
4364 /**
4365  * Parses a _builtin_va_start() expression.
4366  */
4367 static expression_t *parse_va_start(void)
4368 {
4369         eat(T___builtin_va_start);
4370
4371         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4372
4373         expect('(');
4374         expression->va_starte.ap = parse_assignment_expression();
4375         expect(',');
4376         expression_t *const expr = parse_assignment_expression();
4377         if (expr->kind == EXPR_REFERENCE) {
4378                 declaration_t *const decl = expr->reference.declaration;
4379                 if (decl == NULL)
4380                         return create_invalid_expression();
4381                 if (decl->parent_scope == &current_function->scope &&
4382                     decl->next == NULL) {
4383                         expression->va_starte.parameter = decl;
4384                         expect(')');
4385                         return expression;
4386                 }
4387         }
4388         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4389 end_error:
4390         return create_invalid_expression();
4391 }
4392
4393 /**
4394  * Parses a _builtin_va_arg() expression.
4395  */
4396 static expression_t *parse_va_arg(void)
4397 {
4398         eat(T___builtin_va_arg);
4399
4400         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4401
4402         expect('(');
4403         expression->va_arge.ap = parse_assignment_expression();
4404         expect(',');
4405         expression->base.type = parse_typename();
4406         expect(')');
4407
4408         return expression;
4409 end_error:
4410         return create_invalid_expression();
4411 }
4412
4413 static expression_t *parse_builtin_symbol(void)
4414 {
4415         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4416
4417         symbol_t *symbol = token.v.symbol;
4418
4419         expression->builtin_symbol.symbol = symbol;
4420         next_token();
4421
4422         type_t *type = get_builtin_symbol_type(symbol);
4423         type = automatic_type_conversion(type);
4424
4425         expression->base.type = type;
4426         return expression;
4427 }
4428
4429 /**
4430  * Parses a __builtin_constant() expression.
4431  */
4432 static expression_t *parse_builtin_constant(void)
4433 {
4434         eat(T___builtin_constant_p);
4435
4436         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4437
4438         expect('(');
4439         expression->builtin_constant.value = parse_assignment_expression();
4440         expect(')');
4441         expression->base.type = type_int;
4442
4443         return expression;
4444 end_error:
4445         return create_invalid_expression();
4446 }
4447
4448 /**
4449  * Parses a __builtin_prefetch() expression.
4450  */
4451 static expression_t *parse_builtin_prefetch(void)
4452 {
4453         eat(T___builtin_prefetch);
4454
4455         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4456
4457         expect('(');
4458         expression->builtin_prefetch.adr = parse_assignment_expression();
4459         if (token.type == ',') {
4460                 next_token();
4461                 expression->builtin_prefetch.rw = parse_assignment_expression();
4462         }
4463         if (token.type == ',') {
4464                 next_token();
4465                 expression->builtin_prefetch.locality = parse_assignment_expression();
4466         }
4467         expect(')');
4468         expression->base.type = type_void;
4469
4470         return expression;
4471 end_error:
4472         return create_invalid_expression();
4473 }
4474
4475 /**
4476  * Parses a __builtin_is_*() compare expression.
4477  */
4478 static expression_t *parse_compare_builtin(void)
4479 {
4480         expression_t *expression;
4481
4482         switch(token.type) {
4483         case T___builtin_isgreater:
4484                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4485                 break;
4486         case T___builtin_isgreaterequal:
4487                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4488                 break;
4489         case T___builtin_isless:
4490                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4491                 break;
4492         case T___builtin_islessequal:
4493                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4494                 break;
4495         case T___builtin_islessgreater:
4496                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4497                 break;
4498         case T___builtin_isunordered:
4499                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4500                 break;
4501         default:
4502                 panic("invalid compare builtin found");
4503                 break;
4504         }
4505         expression->base.source_position = HERE;
4506         next_token();
4507
4508         expect('(');
4509         expression->binary.left = parse_assignment_expression();
4510         expect(',');
4511         expression->binary.right = parse_assignment_expression();
4512         expect(')');
4513
4514         type_t *const orig_type_left  = expression->binary.left->base.type;
4515         type_t *const orig_type_right = expression->binary.right->base.type;
4516
4517         type_t *const type_left  = skip_typeref(orig_type_left);
4518         type_t *const type_right = skip_typeref(orig_type_right);
4519         if(!is_type_float(type_left) && !is_type_float(type_right)) {
4520                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4521                         type_error_incompatible("invalid operands in comparison",
4522                                 expression->base.source_position, orig_type_left, orig_type_right);
4523                 }
4524         } else {
4525                 semantic_comparison(&expression->binary);
4526         }
4527
4528         return expression;
4529 end_error:
4530         return create_invalid_expression();
4531 }
4532
4533 /**
4534  * Parses a __builtin_expect() expression.
4535  */
4536 static expression_t *parse_builtin_expect(void)
4537 {
4538         eat(T___builtin_expect);
4539
4540         expression_t *expression
4541                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4542
4543         expect('(');
4544         expression->binary.left = parse_assignment_expression();
4545         expect(',');
4546         expression->binary.right = parse_constant_expression();
4547         expect(')');
4548
4549         expression->base.type = expression->binary.left->base.type;
4550
4551         return expression;
4552 end_error:
4553         return create_invalid_expression();
4554 }
4555
4556 /**
4557  * Parses a MS assume() expression.
4558  */
4559 static expression_t *parse_assume(void) {
4560         eat(T_assume);
4561
4562         expression_t *expression
4563                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4564
4565         expect('(');
4566         expression->unary.value = parse_assignment_expression();
4567         expect(')');
4568
4569         expression->base.type = type_void;
4570         return expression;
4571 end_error:
4572         return create_invalid_expression();
4573 }
4574
4575 /**
4576  * Parses a primary expression.
4577  */
4578 static expression_t *parse_primary_expression(void)
4579 {
4580         switch (token.type) {
4581                 case T_INTEGER:                  return parse_int_const();
4582                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
4583                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
4584                 case T_FLOATINGPOINT:            return parse_float_const();
4585                 case T_STRING_LITERAL:
4586                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
4587                 case T_IDENTIFIER:               return parse_reference();
4588                 case T___FUNCTION__:
4589                 case T___func__:                 return parse_function_keyword();
4590                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
4591                 case T___builtin_offsetof:       return parse_offsetof();
4592                 case T___builtin_va_start:       return parse_va_start();
4593                 case T___builtin_va_arg:         return parse_va_arg();
4594                 case T___builtin_expect:         return parse_builtin_expect();
4595                 case T___builtin_alloca:
4596                 case T___builtin_nan:
4597                 case T___builtin_nand:
4598                 case T___builtin_nanf:
4599                 case T___builtin_va_end:         return parse_builtin_symbol();
4600                 case T___builtin_isgreater:
4601                 case T___builtin_isgreaterequal:
4602                 case T___builtin_isless:
4603                 case T___builtin_islessequal:
4604                 case T___builtin_islessgreater:
4605                 case T___builtin_isunordered:    return parse_compare_builtin();
4606                 case T___builtin_constant_p:     return parse_builtin_constant();
4607                 case T___builtin_prefetch:       return parse_builtin_prefetch();
4608                 case T_assume:                   return parse_assume();
4609
4610                 case '(':                        return parse_brace_expression();
4611         }
4612
4613         errorf(HERE, "unexpected token %K, expected an expression", &token);
4614         eat_statement();
4615
4616         return create_invalid_expression();
4617 }
4618
4619 /**
4620  * Check if the expression has the character type and issue a warning then.
4621  */
4622 static void check_for_char_index_type(const expression_t *expression) {
4623         type_t       *const type      = expression->base.type;
4624         const type_t *const base_type = skip_typeref(type);
4625
4626         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4627                         warning.char_subscripts) {
4628                 warningf(expression->base.source_position,
4629                         "array subscript has type '%T'", type);
4630         }
4631 }
4632
4633 static expression_t *parse_array_expression(unsigned precedence,
4634                                             expression_t *left)
4635 {
4636         (void) precedence;
4637
4638         eat('[');
4639
4640         expression_t *inside = parse_expression();
4641
4642         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4643
4644         array_access_expression_t *array_access = &expression->array_access;
4645
4646         type_t *const orig_type_left   = left->base.type;
4647         type_t *const orig_type_inside = inside->base.type;
4648
4649         type_t *const type_left   = skip_typeref(orig_type_left);
4650         type_t *const type_inside = skip_typeref(orig_type_inside);
4651
4652         type_t *return_type;
4653         if (is_type_pointer(type_left)) {
4654                 return_type             = type_left->pointer.points_to;
4655                 array_access->array_ref = left;
4656                 array_access->index     = inside;
4657                 check_for_char_index_type(inside);
4658         } else if (is_type_pointer(type_inside)) {
4659                 return_type             = type_inside->pointer.points_to;
4660                 array_access->array_ref = inside;
4661                 array_access->index     = left;
4662                 array_access->flipped   = true;
4663                 check_for_char_index_type(left);
4664         } else {
4665                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4666                         errorf(HERE,
4667                                 "array access on object with non-pointer types '%T', '%T'",
4668                                 orig_type_left, orig_type_inside);
4669                 }
4670                 return_type             = type_error_type;
4671                 array_access->array_ref = create_invalid_expression();
4672         }
4673
4674         if(token.type != ']') {
4675                 parse_error_expected("Problem while parsing array access", ']', 0);
4676                 return expression;
4677         }
4678         next_token();
4679
4680         return_type           = automatic_type_conversion(return_type);
4681         expression->base.type = return_type;
4682
4683         return expression;
4684 }
4685
4686 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4687 {
4688         expression_t *tp_expression = allocate_expression_zero(kind);
4689         tp_expression->base.type    = type_size_t;
4690
4691         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4692                 next_token();
4693                 tp_expression->typeprop.type = parse_typename();
4694                 expect(')');
4695         } else {
4696                 expression_t *expression = parse_sub_expression(precedence);
4697                 expression->base.type    = revert_automatic_type_conversion(expression);
4698
4699                 tp_expression->typeprop.type          = expression->base.type;
4700                 tp_expression->typeprop.tp_expression = expression;
4701         }
4702
4703         return tp_expression;
4704 end_error:
4705         return create_invalid_expression();
4706 }
4707
4708 static expression_t *parse_sizeof(unsigned precedence)
4709 {
4710         eat(T_sizeof);
4711         return parse_typeprop(EXPR_SIZEOF, precedence);
4712 }
4713
4714 static expression_t *parse_alignof(unsigned precedence)
4715 {
4716         eat(T___alignof__);
4717         return parse_typeprop(EXPR_SIZEOF, precedence);
4718 }
4719
4720 static expression_t *parse_select_expression(unsigned precedence,
4721                                              expression_t *compound)
4722 {
4723         (void) precedence;
4724         assert(token.type == '.' || token.type == T_MINUSGREATER);
4725
4726         bool is_pointer = (token.type == T_MINUSGREATER);
4727         next_token();
4728
4729         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
4730         select->select.compound = compound;
4731
4732         if(token.type != T_IDENTIFIER) {
4733                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4734                 return select;
4735         }
4736         symbol_t *symbol      = token.v.symbol;
4737         select->select.symbol = symbol;
4738         next_token();
4739
4740         type_t *const orig_type = compound->base.type;
4741         type_t *const type      = skip_typeref(orig_type);
4742
4743         type_t *type_left = type;
4744         if(is_pointer) {
4745                 if (!is_type_pointer(type)) {
4746                         if (is_type_valid(type)) {
4747                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4748                         }
4749                         return create_invalid_expression();
4750                 }
4751                 type_left = type->pointer.points_to;
4752         }
4753         type_left = skip_typeref(type_left);
4754
4755         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4756             type_left->kind != TYPE_COMPOUND_UNION) {
4757                 if (is_type_valid(type_left)) {
4758                         errorf(HERE, "request for member '%Y' in something not a struct or "
4759                                "union, but '%T'", symbol, type_left);
4760                 }
4761                 return create_invalid_expression();
4762         }
4763
4764         declaration_t *const declaration = type_left->compound.declaration;
4765
4766         if(!declaration->init.is_defined) {
4767                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4768                        symbol, type_left);
4769                 return create_invalid_expression();
4770         }
4771
4772         declaration_t *iter = find_compound_entry(declaration, symbol);
4773         if(iter == NULL) {
4774                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4775                 return create_invalid_expression();
4776         }
4777
4778         /* we always do the auto-type conversions; the & and sizeof parser contains
4779          * code to revert this! */
4780         type_t *expression_type = automatic_type_conversion(iter->type);
4781
4782         select->select.compound_entry = iter;
4783         select->base.type             = expression_type;
4784
4785         if(expression_type->kind == TYPE_BITFIELD) {
4786                 expression_t *extract
4787                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4788                 extract->unary.value = select;
4789                 extract->base.type   = expression_type->bitfield.base;
4790
4791                 return extract;
4792         }
4793
4794         return select;
4795 }
4796
4797 /**
4798  * Parse a call expression, ie. expression '( ... )'.
4799  *
4800  * @param expression  the function address
4801  */
4802 static expression_t *parse_call_expression(unsigned precedence,
4803                                            expression_t *expression)
4804 {
4805         (void) precedence;
4806         expression_t *result = allocate_expression_zero(EXPR_CALL);
4807
4808         call_expression_t *call = &result->call;
4809         call->function          = expression;
4810
4811         type_t *const orig_type = expression->base.type;
4812         type_t *const type      = skip_typeref(orig_type);
4813
4814         function_type_t *function_type = NULL;
4815         if (is_type_pointer(type)) {
4816                 type_t *const to_type = skip_typeref(type->pointer.points_to);
4817
4818                 if (is_type_function(to_type)) {
4819                         function_type   = &to_type->function;
4820                         call->base.type = function_type->return_type;
4821                 }
4822         }
4823
4824         if (function_type == NULL && is_type_valid(type)) {
4825                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4826         }
4827
4828         /* parse arguments */
4829         eat('(');
4830
4831         if(token.type != ')') {
4832                 call_argument_t *last_argument = NULL;
4833
4834                 while(true) {
4835                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4836
4837                         argument->expression = parse_assignment_expression();
4838                         if(last_argument == NULL) {
4839                                 call->arguments = argument;
4840                         } else {
4841                                 last_argument->next = argument;
4842                         }
4843                         last_argument = argument;
4844
4845                         if(token.type != ',')
4846                                 break;
4847                         next_token();
4848                 }
4849         }
4850         expect(')');
4851
4852         if(function_type != NULL) {
4853                 function_parameter_t *parameter = function_type->parameters;
4854                 call_argument_t      *argument  = call->arguments;
4855                 for( ; parameter != NULL && argument != NULL;
4856                                 parameter = parameter->next, argument = argument->next) {
4857                         type_t *expected_type = parameter->type;
4858                         /* TODO report scope in error messages */
4859                         expression_t *const arg_expr = argument->expression;
4860                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4861                         if (res_type == NULL) {
4862                                 /* TODO improve error message */
4863                                 errorf(arg_expr->base.source_position,
4864                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4865                                         arg_expr, arg_expr->base.type, expected_type);
4866                         } else {
4867                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
4868                         }
4869                 }
4870                 /* too few parameters */
4871                 if(parameter != NULL) {
4872                         errorf(HERE, "too few arguments to function '%E'", expression);
4873                 } else if(argument != NULL) {
4874                         /* too many parameters */
4875                         if(!function_type->variadic
4876                                         && !function_type->unspecified_parameters) {
4877                                 errorf(HERE, "too many arguments to function '%E'", expression);
4878                         } else {
4879                                 /* do default promotion */
4880                                 for( ; argument != NULL; argument = argument->next) {
4881                                         type_t *type = argument->expression->base.type;
4882
4883                                         type = skip_typeref(type);
4884                                         if(is_type_integer(type)) {
4885                                                 type = promote_integer(type);
4886                                         } else if(type == type_float) {
4887                                                 type = type_double;
4888                                         }
4889
4890                                         argument->expression
4891                                                 = create_implicit_cast(argument->expression, type);
4892                                 }
4893
4894                                 check_format(&result->call);
4895                         }
4896                 } else {
4897                         check_format(&result->call);
4898                 }
4899         }
4900
4901         return result;
4902 end_error:
4903         return create_invalid_expression();
4904 }
4905
4906 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4907
4908 static bool same_compound_type(const type_t *type1, const type_t *type2)
4909 {
4910         return
4911                 is_type_compound(type1) &&
4912                 type1->kind == type2->kind &&
4913                 type1->compound.declaration == type2->compound.declaration;
4914 }
4915
4916 /**
4917  * Parse a conditional expression, ie. 'expression ? ... : ...'.
4918  *
4919  * @param expression  the conditional expression
4920  */
4921 static expression_t *parse_conditional_expression(unsigned precedence,
4922                                                   expression_t *expression)
4923 {
4924         eat('?');
4925
4926         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4927
4928         conditional_expression_t *conditional = &result->conditional;
4929         conditional->condition = expression;
4930
4931         /* 6.5.15.2 */
4932         type_t *const condition_type_orig = expression->base.type;
4933         type_t *const condition_type      = skip_typeref(condition_type_orig);
4934         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4935                 type_error("expected a scalar type in conditional condition",
4936                            expression->base.source_position, condition_type_orig);
4937         }
4938
4939         expression_t *true_expression = parse_expression();
4940         expect(':');
4941         expression_t *false_expression = parse_sub_expression(precedence);
4942
4943         type_t *const orig_true_type  = true_expression->base.type;
4944         type_t *const orig_false_type = false_expression->base.type;
4945         type_t *const true_type       = skip_typeref(orig_true_type);
4946         type_t *const false_type      = skip_typeref(orig_false_type);
4947
4948         /* 6.5.15.3 */
4949         type_t *result_type;
4950         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4951                 result_type = semantic_arithmetic(true_type, false_type);
4952
4953                 true_expression  = create_implicit_cast(true_expression, result_type);
4954                 false_expression = create_implicit_cast(false_expression, result_type);
4955
4956                 conditional->true_expression  = true_expression;
4957                 conditional->false_expression = false_expression;
4958                 conditional->base.type        = result_type;
4959         } else if (same_compound_type(true_type, false_type) || (
4960             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4961             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4962                 )) {
4963                 /* just take 1 of the 2 types */
4964                 result_type = true_type;
4965         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4966                         && pointers_compatible(true_type, false_type)) {
4967                 /* ok */
4968                 result_type = true_type;
4969         } else if (is_type_pointer(true_type)
4970                         && is_null_pointer_constant(false_expression)) {
4971                 result_type = true_type;
4972         } else if (is_type_pointer(false_type)
4973                         && is_null_pointer_constant(true_expression)) {
4974                 result_type = false_type;
4975         } else {
4976                 /* TODO: one pointer to void*, other some pointer */
4977
4978                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4979                         type_error_incompatible("while parsing conditional",
4980                                                 expression->base.source_position, true_type,
4981                                                 false_type);
4982                 }
4983                 result_type = type_error_type;
4984         }
4985
4986         conditional->true_expression
4987                 = create_implicit_cast(true_expression, result_type);
4988         conditional->false_expression
4989                 = create_implicit_cast(false_expression, result_type);
4990         conditional->base.type = result_type;
4991         return result;
4992 end_error:
4993         return create_invalid_expression();
4994 }
4995
4996 /**
4997  * Parse an extension expression.
4998  */
4999 static expression_t *parse_extension(unsigned precedence)
5000 {
5001         eat(T___extension__);
5002
5003         /* TODO enable extensions */
5004         expression_t *expression = parse_sub_expression(precedence);
5005         /* TODO disable extensions */
5006         return expression;
5007 }
5008
5009 /**
5010  * Parse a __builtin_classify_type() expression.
5011  */
5012 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5013 {
5014         eat(T___builtin_classify_type);
5015
5016         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5017         result->base.type    = type_int;
5018
5019         expect('(');
5020         expression_t *expression = parse_sub_expression(precedence);
5021         expect(')');
5022         result->classify_type.type_expression = expression;
5023
5024         return result;
5025 end_error:
5026         return create_invalid_expression();
5027 }
5028
5029 static void semantic_incdec(unary_expression_t *expression)
5030 {
5031         type_t *const orig_type = expression->value->base.type;
5032         type_t *const type      = skip_typeref(orig_type);
5033         /* TODO !is_type_real && !is_type_pointer */
5034         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5035                 if (is_type_valid(type)) {
5036                         /* TODO: improve error message */
5037                         errorf(HERE, "operation needs an arithmetic or pointer type");
5038                 }
5039                 return;
5040         }
5041
5042         expression->base.type = orig_type;
5043 }
5044
5045 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5046 {
5047         type_t *const orig_type = expression->value->base.type;
5048         type_t *const type      = skip_typeref(orig_type);
5049         if(!is_type_arithmetic(type)) {
5050                 if (is_type_valid(type)) {
5051                         /* TODO: improve error message */
5052                         errorf(HERE, "operation needs an arithmetic type");
5053                 }
5054                 return;
5055         }
5056
5057         expression->base.type = orig_type;
5058 }
5059
5060 static void semantic_unexpr_scalar(unary_expression_t *expression)
5061 {
5062         type_t *const orig_type = expression->value->base.type;
5063         type_t *const type      = skip_typeref(orig_type);
5064         if (!is_type_scalar(type)) {
5065                 if (is_type_valid(type)) {
5066                         errorf(HERE, "operand of ! must be of scalar type");
5067                 }
5068                 return;
5069         }
5070
5071         expression->base.type = orig_type;
5072 }
5073
5074 static void semantic_unexpr_integer(unary_expression_t *expression)
5075 {
5076         type_t *const orig_type = expression->value->base.type;
5077         type_t *const type      = skip_typeref(orig_type);
5078         if (!is_type_integer(type)) {
5079                 if (is_type_valid(type)) {
5080                         errorf(HERE, "operand of ~ must be of integer type");
5081                 }
5082                 return;
5083         }
5084
5085         expression->base.type = orig_type;
5086 }
5087
5088 static void semantic_dereference(unary_expression_t *expression)
5089 {
5090         type_t *const orig_type = expression->value->base.type;
5091         type_t *const type      = skip_typeref(orig_type);
5092         if(!is_type_pointer(type)) {
5093                 if (is_type_valid(type)) {
5094                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5095                 }
5096                 return;
5097         }
5098
5099         type_t *result_type   = type->pointer.points_to;
5100         result_type           = automatic_type_conversion(result_type);
5101         expression->base.type = result_type;
5102 }
5103
5104 /**
5105  * Check the semantic of the address taken expression.
5106  */
5107 static void semantic_take_addr(unary_expression_t *expression)
5108 {
5109         expression_t *value = expression->value;
5110         value->base.type    = revert_automatic_type_conversion(value);
5111
5112         type_t *orig_type = value->base.type;
5113         if(!is_type_valid(orig_type))
5114                 return;
5115
5116         if(value->kind == EXPR_REFERENCE) {
5117                 declaration_t *const declaration = value->reference.declaration;
5118                 if(declaration != NULL) {
5119                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5120                                 errorf(expression->base.source_position,
5121                                         "address of register variable '%Y' requested",
5122                                         declaration->symbol);
5123                         }
5124                         declaration->address_taken = 1;
5125                 }
5126         }
5127
5128         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5129 }
5130
5131 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
5132 static expression_t *parse_##unexpression_type(unsigned precedence)            \
5133 {                                                                              \
5134         eat(token_type);                                                           \
5135                                                                                    \
5136         expression_t *unary_expression                                             \
5137                 = allocate_expression_zero(unexpression_type);                         \
5138         unary_expression->base.source_position = HERE;                             \
5139         unary_expression->unary.value = parse_sub_expression(precedence);          \
5140                                                                                    \
5141         sfunc(&unary_expression->unary);                                           \
5142                                                                                    \
5143         return unary_expression;                                                   \
5144 }
5145
5146 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5147                                semantic_unexpr_arithmetic)
5148 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5149                                semantic_unexpr_arithmetic)
5150 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5151                                semantic_unexpr_scalar)
5152 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5153                                semantic_dereference)
5154 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5155                                semantic_take_addr)
5156 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5157                                semantic_unexpr_integer)
5158 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
5159                                semantic_incdec)
5160 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5161                                semantic_incdec)
5162
5163 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5164                                                sfunc)                         \
5165 static expression_t *parse_##unexpression_type(unsigned precedence,           \
5166                                                expression_t *left)            \
5167 {                                                                             \
5168         (void) precedence;                                                        \
5169         eat(token_type);                                                          \
5170                                                                               \
5171         expression_t *unary_expression                                            \
5172                 = allocate_expression_zero(unexpression_type);                        \
5173         unary_expression->unary.value = left;                                     \
5174                                                                                   \
5175         sfunc(&unary_expression->unary);                                          \
5176                                                                               \
5177         return unary_expression;                                                  \
5178 }
5179
5180 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5181                                        EXPR_UNARY_POSTFIX_INCREMENT,
5182                                        semantic_incdec)
5183 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5184                                        EXPR_UNARY_POSTFIX_DECREMENT,
5185                                        semantic_incdec)
5186
5187 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5188 {
5189         /* TODO: handle complex + imaginary types */
5190
5191         /* Â§ 6.3.1.8 Usual arithmetic conversions */
5192         if(type_left == type_long_double || type_right == type_long_double) {
5193                 return type_long_double;
5194         } else if(type_left == type_double || type_right == type_double) {
5195                 return type_double;
5196         } else if(type_left == type_float || type_right == type_float) {
5197                 return type_float;
5198         }
5199
5200         type_right = promote_integer(type_right);
5201         type_left  = promote_integer(type_left);
5202
5203         if(type_left == type_right)
5204                 return type_left;
5205
5206         bool signed_left  = is_type_signed(type_left);
5207         bool signed_right = is_type_signed(type_right);
5208         int  rank_left    = get_rank(type_left);
5209         int  rank_right   = get_rank(type_right);
5210         if(rank_left < rank_right) {
5211                 if(signed_left == signed_right || !signed_right) {
5212                         return type_right;
5213                 } else {
5214                         return type_left;
5215                 }
5216         } else {
5217                 if(signed_left == signed_right || !signed_left) {
5218                         return type_left;
5219                 } else {
5220                         return type_right;
5221                 }
5222         }
5223 }
5224
5225 /**
5226  * Check the semantic restrictions for a binary expression.
5227  */
5228 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5229 {
5230         expression_t *const left            = expression->left;
5231         expression_t *const right           = expression->right;
5232         type_t       *const orig_type_left  = left->base.type;
5233         type_t       *const orig_type_right = right->base.type;
5234         type_t       *const type_left       = skip_typeref(orig_type_left);
5235         type_t       *const type_right      = skip_typeref(orig_type_right);
5236
5237         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5238                 /* TODO: improve error message */
5239                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5240                         errorf(HERE, "operation needs arithmetic types");
5241                 }
5242                 return;
5243         }
5244
5245         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5246         expression->left      = create_implicit_cast(left, arithmetic_type);
5247         expression->right     = create_implicit_cast(right, arithmetic_type);
5248         expression->base.type = arithmetic_type;
5249 }
5250
5251 static void semantic_shift_op(binary_expression_t *expression)
5252 {
5253         expression_t *const left            = expression->left;
5254         expression_t *const right           = expression->right;
5255         type_t       *const orig_type_left  = left->base.type;
5256         type_t       *const orig_type_right = right->base.type;
5257         type_t       *      type_left       = skip_typeref(orig_type_left);
5258         type_t       *      type_right      = skip_typeref(orig_type_right);
5259
5260         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5261                 /* TODO: improve error message */
5262                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5263                         errorf(HERE, "operation needs integer types");
5264                 }
5265                 return;
5266         }
5267
5268         type_left  = promote_integer(type_left);
5269         type_right = promote_integer(type_right);
5270
5271         expression->left      = create_implicit_cast(left, type_left);
5272         expression->right     = create_implicit_cast(right, type_right);
5273         expression->base.type = type_left;
5274 }
5275
5276 static void semantic_add(binary_expression_t *expression)
5277 {
5278         expression_t *const left            = expression->left;
5279         expression_t *const right           = expression->right;
5280         type_t       *const orig_type_left  = left->base.type;
5281         type_t       *const orig_type_right = right->base.type;
5282         type_t       *const type_left       = skip_typeref(orig_type_left);
5283         type_t       *const type_right      = skip_typeref(orig_type_right);
5284
5285         /* Â§ 5.6.5 */
5286         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5287                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5288                 expression->left  = create_implicit_cast(left, arithmetic_type);
5289                 expression->right = create_implicit_cast(right, arithmetic_type);
5290                 expression->base.type = arithmetic_type;
5291                 return;
5292         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5293                 expression->base.type = type_left;
5294         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5295                 expression->base.type = type_right;
5296         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5297                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5298         }
5299 }
5300
5301 static void semantic_sub(binary_expression_t *expression)
5302 {
5303         expression_t *const left            = expression->left;
5304         expression_t *const right           = expression->right;
5305         type_t       *const orig_type_left  = left->base.type;
5306         type_t       *const orig_type_right = right->base.type;
5307         type_t       *const type_left       = skip_typeref(orig_type_left);
5308         type_t       *const type_right      = skip_typeref(orig_type_right);
5309
5310         /* Â§ 5.6.5 */
5311         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5312                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5313                 expression->left        = create_implicit_cast(left, arithmetic_type);
5314                 expression->right       = create_implicit_cast(right, arithmetic_type);
5315                 expression->base.type =  arithmetic_type;
5316                 return;
5317         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5318                 expression->base.type = type_left;
5319         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5320                 if(!pointers_compatible(type_left, type_right)) {
5321                         errorf(HERE,
5322                                "pointers to incompatible objects to binary '-' ('%T', '%T')",
5323                                orig_type_left, orig_type_right);
5324                 } else {
5325                         expression->base.type = type_ptrdiff_t;
5326                 }
5327         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5328                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5329                        orig_type_left, orig_type_right);
5330         }
5331 }
5332
5333 /**
5334  * Check the semantics of comparison expressions.
5335  *
5336  * @param expression   The expression to check.
5337  */
5338 static void semantic_comparison(binary_expression_t *expression)
5339 {
5340         expression_t *left            = expression->left;
5341         expression_t *right           = expression->right;
5342         type_t       *orig_type_left  = left->base.type;
5343         type_t       *orig_type_right = right->base.type;
5344
5345         type_t *type_left  = skip_typeref(orig_type_left);
5346         type_t *type_right = skip_typeref(orig_type_right);
5347
5348         /* TODO non-arithmetic types */
5349         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5350                 if (warning.sign_compare &&
5351                     (expression->base.kind != EXPR_BINARY_EQUAL &&
5352                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5353                     (is_type_signed(type_left) != is_type_signed(type_right))) {
5354                         warningf(expression->base.source_position,
5355                                  "comparison between signed and unsigned");
5356                 }
5357                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5358                 expression->left        = create_implicit_cast(left, arithmetic_type);
5359                 expression->right       = create_implicit_cast(right, arithmetic_type);
5360                 expression->base.type   = arithmetic_type;
5361                 if (warning.float_equal &&
5362                     (expression->base.kind == EXPR_BINARY_EQUAL ||
5363                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5364                     is_type_float(arithmetic_type)) {
5365                         warningf(expression->base.source_position,
5366                                  "comparing floating point with == or != is unsafe");
5367                 }
5368         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5369                 /* TODO check compatibility */
5370         } else if (is_type_pointer(type_left)) {
5371                 expression->right = create_implicit_cast(right, type_left);
5372         } else if (is_type_pointer(type_right)) {
5373                 expression->left = create_implicit_cast(left, type_right);
5374         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5375                 type_error_incompatible("invalid operands in comparison",
5376                                         expression->base.source_position,
5377                                         type_left, type_right);
5378         }
5379         expression->base.type = type_int;
5380 }
5381
5382 static void semantic_arithmetic_assign(binary_expression_t *expression)
5383 {
5384         expression_t *left            = expression->left;
5385         expression_t *right           = expression->right;
5386         type_t       *orig_type_left  = left->base.type;
5387         type_t       *orig_type_right = right->base.type;
5388
5389         type_t *type_left  = skip_typeref(orig_type_left);
5390         type_t *type_right = skip_typeref(orig_type_right);
5391
5392         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5393                 /* TODO: improve error message */
5394                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5395                         errorf(HERE, "operation needs arithmetic types");
5396                 }
5397                 return;
5398         }
5399
5400         /* combined instructions are tricky. We can't create an implicit cast on
5401          * the left side, because we need the uncasted form for the store.
5402          * The ast2firm pass has to know that left_type must be right_type
5403          * for the arithmetic operation and create a cast by itself */
5404         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5405         expression->right       = create_implicit_cast(right, arithmetic_type);
5406         expression->base.type   = type_left;
5407 }
5408
5409 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5410 {
5411         expression_t *const left            = expression->left;
5412         expression_t *const right           = expression->right;
5413         type_t       *const orig_type_left  = left->base.type;
5414         type_t       *const orig_type_right = right->base.type;
5415         type_t       *const type_left       = skip_typeref(orig_type_left);
5416         type_t       *const type_right      = skip_typeref(orig_type_right);
5417
5418         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5419                 /* combined instructions are tricky. We can't create an implicit cast on
5420                  * the left side, because we need the uncasted form for the store.
5421                  * The ast2firm pass has to know that left_type must be right_type
5422                  * for the arithmetic operation and create a cast by itself */
5423                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5424                 expression->right     = create_implicit_cast(right, arithmetic_type);
5425                 expression->base.type = type_left;
5426         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5427                 expression->base.type = type_left;
5428         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5429                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5430         }
5431 }
5432
5433 /**
5434  * Check the semantic restrictions of a logical expression.
5435  */
5436 static void semantic_logical_op(binary_expression_t *expression)
5437 {
5438         expression_t *const left            = expression->left;
5439         expression_t *const right           = expression->right;
5440         type_t       *const orig_type_left  = left->base.type;
5441         type_t       *const orig_type_right = right->base.type;
5442         type_t       *const type_left       = skip_typeref(orig_type_left);
5443         type_t       *const type_right      = skip_typeref(orig_type_right);
5444
5445         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5446                 /* TODO: improve error message */
5447                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5448                         errorf(HERE, "operation needs scalar types");
5449                 }
5450                 return;
5451         }
5452
5453         expression->base.type = type_int;
5454 }
5455
5456 /**
5457  * Checks if a compound type has constant fields.
5458  */
5459 static bool has_const_fields(const compound_type_t *type)
5460 {
5461         const scope_t       *scope       = &type->declaration->scope;
5462         const declaration_t *declaration = scope->declarations;
5463
5464         for (; declaration != NULL; declaration = declaration->next) {
5465                 if (declaration->namespc != NAMESPACE_NORMAL)
5466                         continue;
5467
5468                 const type_t *decl_type = skip_typeref(declaration->type);
5469                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5470                         return true;
5471         }
5472         /* TODO */
5473         return false;
5474 }
5475
5476 /**
5477  * Check the semantic restrictions of a binary assign expression.
5478  */
5479 static void semantic_binexpr_assign(binary_expression_t *expression)
5480 {
5481         expression_t *left           = expression->left;
5482         type_t       *orig_type_left = left->base.type;
5483
5484         type_t *type_left = revert_automatic_type_conversion(left);
5485         type_left         = skip_typeref(orig_type_left);
5486
5487         /* must be a modifiable lvalue */
5488         if (is_type_array(type_left)) {
5489                 errorf(HERE, "cannot assign to arrays ('%E')", left);
5490                 return;
5491         }
5492         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5493                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5494                        orig_type_left);
5495                 return;
5496         }
5497         if(is_type_incomplete(type_left)) {
5498                 errorf(HERE,
5499                        "left-hand side of assignment '%E' has incomplete type '%T'",
5500                        left, orig_type_left);
5501                 return;
5502         }
5503         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5504                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5505                        left, orig_type_left);
5506                 return;
5507         }
5508
5509         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5510                                                  "assignment");
5511         if (res_type == NULL) {
5512                 errorf(expression->base.source_position,
5513                         "cannot assign to '%T' from '%T'",
5514                         orig_type_left, expression->right->base.type);
5515         } else {
5516                 expression->right = create_implicit_cast(expression->right, res_type);
5517         }
5518
5519         expression->base.type = orig_type_left;
5520 }
5521
5522 /**
5523  * Determine if the outermost operation (or parts thereof) of the given
5524  * expression has no effect in order to generate a warning about this fact.
5525  * Therefore in some cases this only examines some of the operands of the
5526  * expression (see comments in the function and examples below).
5527  * Examples:
5528  *   f() + 23;    // warning, because + has no effect
5529  *   x || f();    // no warning, because x controls execution of f()
5530  *   x ? y : f(); // warning, because y has no effect
5531  *   (void)x;     // no warning to be able to suppress the warning
5532  * This function can NOT be used for an "expression has definitely no effect"-
5533  * analysis. */
5534 static bool expression_has_effect(const expression_t *const expr)
5535 {
5536         switch (expr->kind) {
5537                 case EXPR_UNKNOWN:                   break;
5538                 case EXPR_INVALID:                   return true; /* do NOT warn */
5539                 case EXPR_REFERENCE:                 return false;
5540                 case EXPR_CONST:                     return false;
5541                 case EXPR_CHARACTER_CONSTANT:        return false;
5542                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
5543                 case EXPR_STRING_LITERAL:            return false;
5544                 case EXPR_WIDE_STRING_LITERAL:       return false;
5545
5546                 case EXPR_CALL: {
5547                         const call_expression_t *const call = &expr->call;
5548                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5549                                 return true;
5550
5551                         switch (call->function->builtin_symbol.symbol->ID) {
5552                                 case T___builtin_va_end: return true;
5553                                 default:                 return false;
5554                         }
5555                 }
5556
5557                 /* Generate the warning if either the left or right hand side of a
5558                  * conditional expression has no effect */
5559                 case EXPR_CONDITIONAL: {
5560                         const conditional_expression_t *const cond = &expr->conditional;
5561                         return
5562                                 expression_has_effect(cond->true_expression) &&
5563                                 expression_has_effect(cond->false_expression);
5564                 }
5565
5566                 case EXPR_SELECT:                    return false;
5567                 case EXPR_ARRAY_ACCESS:              return false;
5568                 case EXPR_SIZEOF:                    return false;
5569                 case EXPR_CLASSIFY_TYPE:             return false;
5570                 case EXPR_ALIGNOF:                   return false;
5571
5572                 case EXPR_FUNCTION:                  return false;
5573                 case EXPR_PRETTY_FUNCTION:           return false;
5574                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
5575                 case EXPR_BUILTIN_CONSTANT_P:        return false;
5576                 case EXPR_BUILTIN_PREFETCH:          return true;
5577                 case EXPR_OFFSETOF:                  return false;
5578                 case EXPR_VA_START:                  return true;
5579                 case EXPR_VA_ARG:                    return true;
5580                 case EXPR_STATEMENT:                 return true; // TODO
5581                 case EXPR_COMPOUND_LITERAL:          return false;
5582
5583                 case EXPR_UNARY_NEGATE:              return false;
5584                 case EXPR_UNARY_PLUS:                return false;
5585                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
5586                 case EXPR_UNARY_NOT:                 return false;
5587                 case EXPR_UNARY_DEREFERENCE:         return false;
5588                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
5589                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
5590                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
5591                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
5592                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
5593
5594                 /* Treat void casts as if they have an effect in order to being able to
5595                  * suppress the warning */
5596                 case EXPR_UNARY_CAST: {
5597                         type_t *const type = skip_typeref(expr->base.type);
5598                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
5599                 }
5600
5601                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
5602                 case EXPR_UNARY_ASSUME:              return true;
5603                 case EXPR_UNARY_BITFIELD_EXTRACT:    return false;
5604
5605                 case EXPR_BINARY_ADD:                return false;
5606                 case EXPR_BINARY_SUB:                return false;
5607                 case EXPR_BINARY_MUL:                return false;
5608                 case EXPR_BINARY_DIV:                return false;
5609                 case EXPR_BINARY_MOD:                return false;
5610                 case EXPR_BINARY_EQUAL:              return false;
5611                 case EXPR_BINARY_NOTEQUAL:           return false;
5612                 case EXPR_BINARY_LESS:               return false;
5613                 case EXPR_BINARY_LESSEQUAL:          return false;
5614                 case EXPR_BINARY_GREATER:            return false;
5615                 case EXPR_BINARY_GREATEREQUAL:       return false;
5616                 case EXPR_BINARY_BITWISE_AND:        return false;
5617                 case EXPR_BINARY_BITWISE_OR:         return false;
5618                 case EXPR_BINARY_BITWISE_XOR:        return false;
5619                 case EXPR_BINARY_SHIFTLEFT:          return false;
5620                 case EXPR_BINARY_SHIFTRIGHT:         return false;
5621                 case EXPR_BINARY_ASSIGN:             return true;
5622                 case EXPR_BINARY_MUL_ASSIGN:         return true;
5623                 case EXPR_BINARY_DIV_ASSIGN:         return true;
5624                 case EXPR_BINARY_MOD_ASSIGN:         return true;
5625                 case EXPR_BINARY_ADD_ASSIGN:         return true;
5626                 case EXPR_BINARY_SUB_ASSIGN:         return true;
5627                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
5628                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
5629                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5630                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5631                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
5632
5633                 /* Only examine the right hand side of && and ||, because the left hand
5634                  * side already has the effect of controlling the execution of the right
5635                  * hand side */
5636                 case EXPR_BINARY_LOGICAL_AND:
5637                 case EXPR_BINARY_LOGICAL_OR:
5638                 /* Only examine the right hand side of a comma expression, because the left
5639                  * hand side has a separate warning */
5640                 case EXPR_BINARY_COMMA:
5641                         return expression_has_effect(expr->binary.right);
5642
5643                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
5644                 case EXPR_BINARY_ISGREATER:          return false;
5645                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
5646                 case EXPR_BINARY_ISLESS:             return false;
5647                 case EXPR_BINARY_ISLESSEQUAL:        return false;
5648                 case EXPR_BINARY_ISLESSGREATER:      return false;
5649                 case EXPR_BINARY_ISUNORDERED:        return false;
5650         }
5651
5652         panic("unexpected expression");
5653 }
5654
5655 static void semantic_comma(binary_expression_t *expression)
5656 {
5657         if (warning.unused_value) {
5658                 const expression_t *const left = expression->left;
5659                 if (!expression_has_effect(left)) {
5660                         warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5661                 }
5662         }
5663         expression->base.type = expression->right->base.type;
5664 }
5665
5666 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
5667 static expression_t *parse_##binexpression_type(unsigned precedence,      \
5668                                                 expression_t *left)       \
5669 {                                                                         \
5670         eat(token_type);                                                      \
5671         source_position_t pos = HERE;                                         \
5672                                                                           \
5673         expression_t *right = parse_sub_expression(precedence + lr);          \
5674                                                                           \
5675         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5676         binexpr->base.source_position = pos;                                  \
5677         binexpr->binary.left  = left;                                         \
5678         binexpr->binary.right = right;                                        \
5679         sfunc(&binexpr->binary);                                              \
5680                                                                           \
5681         return binexpr;                                                       \
5682 }
5683
5684 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
5685 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
5686 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
5687 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
5688 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
5689 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
5690 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
5691 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
5692 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
5693
5694 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
5695                       semantic_comparison, 1)
5696 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5697                       semantic_comparison, 1)
5698 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
5699                       semantic_comparison, 1)
5700 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
5701                       semantic_comparison, 1)
5702
5703 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5704                       semantic_binexpr_arithmetic, 1)
5705 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5706                       semantic_binexpr_arithmetic, 1)
5707 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5708                       semantic_binexpr_arithmetic, 1)
5709 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5710                       semantic_logical_op, 1)
5711 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5712                       semantic_logical_op, 1)
5713 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5714                       semantic_shift_op, 1)
5715 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5716                       semantic_shift_op, 1)
5717 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5718                       semantic_arithmetic_addsubb_assign, 0)
5719 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5720                       semantic_arithmetic_addsubb_assign, 0)
5721 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5722                       semantic_arithmetic_assign, 0)
5723 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5724                       semantic_arithmetic_assign, 0)
5725 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5726                       semantic_arithmetic_assign, 0)
5727 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5728                       semantic_arithmetic_assign, 0)
5729 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5730                       semantic_arithmetic_assign, 0)
5731 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5732                       semantic_arithmetic_assign, 0)
5733 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5734                       semantic_arithmetic_assign, 0)
5735 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5736                       semantic_arithmetic_assign, 0)
5737
5738 static expression_t *parse_sub_expression(unsigned precedence)
5739 {
5740         if(token.type < 0) {
5741                 return expected_expression_error();
5742         }
5743
5744         expression_parser_function_t *parser
5745                 = &expression_parsers[token.type];
5746         source_position_t             source_position = token.source_position;
5747         expression_t                 *left;
5748
5749         if(parser->parser != NULL) {
5750                 left = parser->parser(parser->precedence);
5751         } else {
5752                 left = parse_primary_expression();
5753         }
5754         assert(left != NULL);
5755         left->base.source_position = source_position;
5756
5757         while(true) {
5758                 if(token.type < 0) {
5759                         return expected_expression_error();
5760                 }
5761
5762                 parser = &expression_parsers[token.type];
5763                 if(parser->infix_parser == NULL)
5764                         break;
5765                 if(parser->infix_precedence < precedence)
5766                         break;
5767
5768                 left = parser->infix_parser(parser->infix_precedence, left);
5769
5770                 assert(left != NULL);
5771                 assert(left->kind != EXPR_UNKNOWN);
5772                 left->base.source_position = source_position;
5773         }
5774
5775         return left;
5776 }
5777
5778 /**
5779  * Parse an expression.
5780  */
5781 static expression_t *parse_expression(void)
5782 {
5783         return parse_sub_expression(1);
5784 }
5785
5786 /**
5787  * Register a parser for a prefix-like operator with given precedence.
5788  *
5789  * @param parser      the parser function
5790  * @param token_type  the token type of the prefix token
5791  * @param precedence  the precedence of the operator
5792  */
5793 static void register_expression_parser(parse_expression_function parser,
5794                                        int token_type, unsigned precedence)
5795 {
5796         expression_parser_function_t *entry = &expression_parsers[token_type];
5797
5798         if(entry->parser != NULL) {
5799                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5800                 panic("trying to register multiple expression parsers for a token");
5801         }
5802         entry->parser     = parser;
5803         entry->precedence = precedence;
5804 }
5805
5806 /**
5807  * Register a parser for an infix operator with given precedence.
5808  *
5809  * @param parser      the parser function
5810  * @param token_type  the token type of the infix operator
5811  * @param precedence  the precedence of the operator
5812  */
5813 static void register_infix_parser(parse_expression_infix_function parser,
5814                 int token_type, unsigned precedence)
5815 {
5816         expression_parser_function_t *entry = &expression_parsers[token_type];
5817
5818         if(entry->infix_parser != NULL) {
5819                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5820                 panic("trying to register multiple infix expression parsers for a "
5821                       "token");
5822         }
5823         entry->infix_parser     = parser;
5824         entry->infix_precedence = precedence;
5825 }
5826
5827 /**
5828  * Initialize the expression parsers.
5829  */
5830 static void init_expression_parsers(void)
5831 {
5832         memset(&expression_parsers, 0, sizeof(expression_parsers));
5833
5834         register_infix_parser(parse_array_expression,         '[',              30);
5835         register_infix_parser(parse_call_expression,          '(',              30);
5836         register_infix_parser(parse_select_expression,        '.',              30);
5837         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
5838         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5839                                                               T_PLUSPLUS,       30);
5840         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5841                                                               T_MINUSMINUS,     30);
5842
5843         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
5844         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
5845         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
5846         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
5847         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
5848         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
5849         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
5850         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
5851         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
5852         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
5853         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
5854         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
5855         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5856                                                     T_EXCLAMATIONMARKEQUAL, 13);
5857         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
5858         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
5859         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
5860         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
5861         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
5862         register_infix_parser(parse_conditional_expression,   '?',               7);
5863         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
5864         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
5865         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
5866         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
5867         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
5868         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
5869         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5870                                                                 T_LESSLESSEQUAL, 2);
5871         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5872                                                           T_GREATERGREATEREQUAL, 2);
5873         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5874                                                                      T_ANDEQUAL, 2);
5875         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5876                                                                     T_PIPEEQUAL, 2);
5877         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5878                                                                    T_CARETEQUAL, 2);
5879
5880         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
5881
5882         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
5883         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
5884         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
5885         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
5886         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
5887         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
5888         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5889                                                                   T_PLUSPLUS,   25);
5890         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5891                                                                   T_MINUSMINUS, 25);
5892         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
5893         register_expression_parser(parse_alignof,                T___alignof__, 25);
5894         register_expression_parser(parse_extension,            T___extension__, 25);
5895         register_expression_parser(parse_builtin_classify_type,
5896                                                      T___builtin_classify_type, 25);
5897 }
5898
5899 /**
5900  * Parse a asm statement constraints specification.
5901  */
5902 static asm_constraint_t *parse_asm_constraints(void)
5903 {
5904         asm_constraint_t *result = NULL;
5905         asm_constraint_t *last   = NULL;
5906
5907         while(token.type == T_STRING_LITERAL || token.type == '[') {
5908                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5909                 memset(constraint, 0, sizeof(constraint[0]));
5910
5911                 if(token.type == '[') {
5912                         eat('[');
5913                         if(token.type != T_IDENTIFIER) {
5914                                 parse_error_expected("while parsing asm constraint",
5915                                                      T_IDENTIFIER, 0);
5916                                 return NULL;
5917                         }
5918                         constraint->symbol = token.v.symbol;
5919
5920                         expect(']');
5921                 }
5922
5923                 constraint->constraints = parse_string_literals();
5924                 expect('(');
5925                 constraint->expression = parse_expression();
5926                 expect(')');
5927
5928                 if(last != NULL) {
5929                         last->next = constraint;
5930                 } else {
5931                         result = constraint;
5932                 }
5933                 last = constraint;
5934
5935                 if(token.type != ',')
5936                         break;
5937                 eat(',');
5938         }
5939
5940         return result;
5941 end_error:
5942         return NULL;
5943 }
5944
5945 /**
5946  * Parse a asm statement clobber specification.
5947  */
5948 static asm_clobber_t *parse_asm_clobbers(void)
5949 {
5950         asm_clobber_t *result = NULL;
5951         asm_clobber_t *last   = NULL;
5952
5953         while(token.type == T_STRING_LITERAL) {
5954                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5955                 clobber->clobber       = parse_string_literals();
5956
5957                 if(last != NULL) {
5958                         last->next = clobber;
5959                 } else {
5960                         result = clobber;
5961                 }
5962                 last = clobber;
5963
5964                 if(token.type != ',')
5965                         break;
5966                 eat(',');
5967         }
5968
5969         return result;
5970 }
5971
5972 /**
5973  * Parse an asm statement.
5974  */
5975 static statement_t *parse_asm_statement(void)
5976 {
5977         eat(T_asm);
5978
5979         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
5980         statement->base.source_position = token.source_position;
5981
5982         asm_statement_t *asm_statement = &statement->asms;
5983
5984         if(token.type == T_volatile) {
5985                 next_token();
5986                 asm_statement->is_volatile = true;
5987         }
5988
5989         expect('(');
5990         asm_statement->asm_text = parse_string_literals();
5991
5992         if(token.type != ':')
5993                 goto end_of_asm;
5994         eat(':');
5995
5996         asm_statement->inputs = parse_asm_constraints();
5997         if(token.type != ':')
5998                 goto end_of_asm;
5999         eat(':');
6000
6001         asm_statement->outputs = parse_asm_constraints();
6002         if(token.type != ':')
6003                 goto end_of_asm;
6004         eat(':');
6005
6006         asm_statement->clobbers = parse_asm_clobbers();
6007
6008 end_of_asm:
6009         expect(')');
6010         expect(';');
6011         return statement;
6012 end_error:
6013         return NULL;
6014 }
6015
6016 /**
6017  * Parse a case statement.
6018  */
6019 static statement_t *parse_case_statement(void)
6020 {
6021         eat(T_case);
6022
6023         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6024
6025         statement->base.source_position  = token.source_position;
6026         statement->case_label.expression = parse_expression();
6027
6028         if (c_mode & _GNUC) {
6029                 if (token.type == T_DOTDOTDOT) {
6030                         next_token();
6031                         statement->case_label.end_range = parse_expression();
6032                 }
6033         }
6034
6035         expect(':');
6036
6037         if (! is_constant_expression(statement->case_label.expression)) {
6038                 errorf(statement->base.source_position,
6039                         "case label does not reduce to an integer constant");
6040         } else {
6041                 /* TODO: check if the case label is already known */
6042                 if (current_switch != NULL) {
6043                         /* link all cases into the switch statement */
6044                         if (current_switch->last_case == NULL) {
6045                                 current_switch->first_case =
6046                                 current_switch->last_case  = &statement->case_label;
6047                         } else {
6048                                 current_switch->last_case->next = &statement->case_label;
6049                         }
6050                 } else {
6051                         errorf(statement->base.source_position,
6052                                 "case label not within a switch statement");
6053                 }
6054         }
6055         statement->case_label.statement = parse_statement();
6056
6057         return statement;
6058 end_error:
6059         return NULL;
6060 }
6061
6062 /**
6063  * Finds an existing default label of a switch statement.
6064  */
6065 static case_label_statement_t *
6066 find_default_label(const switch_statement_t *statement)
6067 {
6068         case_label_statement_t *label = statement->first_case;
6069         for ( ; label != NULL; label = label->next) {
6070                 if (label->expression == NULL)
6071                         return label;
6072         }
6073         return NULL;
6074 }
6075
6076 /**
6077  * Parse a default statement.
6078  */
6079 static statement_t *parse_default_statement(void)
6080 {
6081         eat(T_default);
6082
6083         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6084
6085         statement->base.source_position = token.source_position;
6086
6087         expect(':');
6088         if (current_switch != NULL) {
6089                 const case_label_statement_t *def_label = find_default_label(current_switch);
6090                 if (def_label != NULL) {
6091                         errorf(HERE, "multiple default labels in one switch");
6092                         errorf(def_label->base.source_position,
6093                                 "this is the first default label");
6094                 } else {
6095                         /* link all cases into the switch statement */
6096                         if (current_switch->last_case == NULL) {
6097                                 current_switch->first_case =
6098                                         current_switch->last_case  = &statement->case_label;
6099                         } else {
6100                                 current_switch->last_case->next = &statement->case_label;
6101                         }
6102                 }
6103         } else {
6104                 errorf(statement->base.source_position,
6105                         "'default' label not within a switch statement");
6106         }
6107         statement->case_label.statement = parse_statement();
6108
6109         return statement;
6110 end_error:
6111         return NULL;
6112 }
6113
6114 /**
6115  * Return the declaration for a given label symbol or create a new one.
6116  */
6117 static declaration_t *get_label(symbol_t *symbol)
6118 {
6119         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6120         assert(current_function != NULL);
6121         /* if we found a label in the same function, then we already created the
6122          * declaration */
6123         if(candidate != NULL
6124                         && candidate->parent_scope == &current_function->scope) {
6125                 return candidate;
6126         }
6127
6128         /* otherwise we need to create a new one */
6129         declaration_t *const declaration = allocate_declaration_zero();
6130         declaration->namespc       = NAMESPACE_LABEL;
6131         declaration->symbol        = symbol;
6132
6133         label_push(declaration);
6134
6135         return declaration;
6136 }
6137
6138 /**
6139  * Parse a label statement.
6140  */
6141 static statement_t *parse_label_statement(void)
6142 {
6143         assert(token.type == T_IDENTIFIER);
6144         symbol_t *symbol = token.v.symbol;
6145         next_token();
6146
6147         declaration_t *label = get_label(symbol);
6148
6149         /* if source position is already set then the label is defined twice,
6150          * otherwise it was just mentioned in a goto so far */
6151         if(label->source_position.input_name != NULL) {
6152                 errorf(HERE, "duplicate label '%Y'", symbol);
6153                 errorf(label->source_position, "previous definition of '%Y' was here",
6154                        symbol);
6155         } else {
6156                 label->source_position = token.source_position;
6157         }
6158
6159         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6160
6161         statement->base.source_position = token.source_position;
6162         statement->label.label          = label;
6163
6164         eat(':');
6165
6166         if(token.type == '}') {
6167                 /* TODO only warn? */
6168                 errorf(HERE, "label at end of compound statement");
6169                 return statement;
6170         } else {
6171                 if (token.type == ';') {
6172                         /* eat an empty statement here, to avoid the warning about an empty
6173                          * after a label.  label:; is commonly used to have a label before
6174                          * a }. */
6175                         next_token();
6176                 } else {
6177                         statement->label.statement = parse_statement();
6178                 }
6179         }
6180
6181         /* remember the labels's in a list for later checking */
6182         if (label_last == NULL) {
6183                 label_first = &statement->label;
6184         } else {
6185                 label_last->next = &statement->label;
6186         }
6187         label_last = &statement->label;
6188
6189         return statement;
6190 }
6191
6192 /**
6193  * Parse an if statement.
6194  */
6195 static statement_t *parse_if(void)
6196 {
6197         eat(T_if);
6198
6199         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
6200         statement->base.source_position = token.source_position;
6201
6202         expect('(');
6203         statement->ifs.condition = parse_expression();
6204         expect(')');
6205
6206         statement->ifs.true_statement = parse_statement();
6207         if(token.type == T_else) {
6208                 next_token();
6209                 statement->ifs.false_statement = parse_statement();
6210         }
6211
6212         return statement;
6213 end_error:
6214         return NULL;
6215 }
6216
6217 /**
6218  * Parse a switch statement.
6219  */
6220 static statement_t *parse_switch(void)
6221 {
6222         eat(T_switch);
6223
6224         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
6225         statement->base.source_position = token.source_position;
6226
6227         expect('(');
6228         expression_t *const expr = parse_expression();
6229         type_t       *      type = skip_typeref(expr->base.type);
6230         if (is_type_integer(type)) {
6231                 type = promote_integer(type);
6232         } else if (is_type_valid(type)) {
6233                 errorf(expr->base.source_position,
6234                        "switch quantity is not an integer, but '%T'", type);
6235                 type = type_error_type;
6236         }
6237         statement->switchs.expression = create_implicit_cast(expr, type);
6238         expect(')');
6239
6240         switch_statement_t *rem = current_switch;
6241         current_switch          = &statement->switchs;
6242         statement->switchs.body = parse_statement();
6243         current_switch          = rem;
6244
6245         if (warning.switch_default
6246                         && find_default_label(&statement->switchs) == NULL) {
6247                 warningf(statement->base.source_position, "switch has no default case");
6248         }
6249
6250         return statement;
6251 end_error:
6252         return NULL;
6253 }
6254
6255 static statement_t *parse_loop_body(statement_t *const loop)
6256 {
6257         statement_t *const rem = current_loop;
6258         current_loop = loop;
6259
6260         statement_t *const body = parse_statement();
6261
6262         current_loop = rem;
6263         return body;
6264 }
6265
6266 /**
6267  * Parse a while statement.
6268  */
6269 static statement_t *parse_while(void)
6270 {
6271         eat(T_while);
6272
6273         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
6274         statement->base.source_position = token.source_position;
6275
6276         expect('(');
6277         statement->whiles.condition = parse_expression();
6278         expect(')');
6279
6280         statement->whiles.body = parse_loop_body(statement);
6281
6282         return statement;
6283 end_error:
6284         return NULL;
6285 }
6286
6287 /**
6288  * Parse a do statement.
6289  */
6290 static statement_t *parse_do(void)
6291 {
6292         eat(T_do);
6293
6294         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6295
6296         statement->base.source_position = token.source_position;
6297
6298         statement->do_while.body = parse_loop_body(statement);
6299
6300         expect(T_while);
6301         expect('(');
6302         statement->do_while.condition = parse_expression();
6303         expect(')');
6304         expect(';');
6305
6306         return statement;
6307 end_error:
6308         return NULL;
6309 }
6310
6311 /**
6312  * Parse a for statement.
6313  */
6314 static statement_t *parse_for(void)
6315 {
6316         eat(T_for);
6317
6318         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
6319         statement->base.source_position = token.source_position;
6320
6321         int      top        = environment_top();
6322         scope_t *last_scope = scope;
6323         set_scope(&statement->fors.scope);
6324
6325         expect('(');
6326
6327         if(token.type != ';') {
6328                 if(is_declaration_specifier(&token, false)) {
6329                         parse_declaration(record_declaration);
6330                 } else {
6331                         expression_t *const init = parse_expression();
6332                         statement->fors.initialisation = init;
6333                         if (warning.unused_value  && !expression_has_effect(init)) {
6334                                 warningf(init->base.source_position,
6335                                          "initialisation of 'for'-statement has no effect");
6336                         }
6337                         expect(';');
6338                 }
6339         } else {
6340                 expect(';');
6341         }
6342
6343         if(token.type != ';') {
6344                 statement->fors.condition = parse_expression();
6345         }
6346         expect(';');
6347         if(token.type != ')') {
6348                 expression_t *const step = parse_expression();
6349                 statement->fors.step = step;
6350                 if (warning.unused_value  && !expression_has_effect(step)) {
6351                         warningf(step->base.source_position,
6352                                  "step of 'for'-statement has no effect");
6353                 }
6354         }
6355         expect(')');
6356         statement->fors.body = parse_loop_body(statement);
6357
6358         assert(scope == &statement->fors.scope);
6359         set_scope(last_scope);
6360         environment_pop_to(top);
6361
6362         return statement;
6363
6364 end_error:
6365         assert(scope == &statement->fors.scope);
6366         set_scope(last_scope);
6367         environment_pop_to(top);
6368
6369         return NULL;
6370 }
6371
6372 /**
6373  * Parse a goto statement.
6374  */
6375 static statement_t *parse_goto(void)
6376 {
6377         eat(T_goto);
6378
6379         if(token.type != T_IDENTIFIER) {
6380                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6381                 eat_statement();
6382                 return NULL;
6383         }
6384         symbol_t *symbol = token.v.symbol;
6385         next_token();
6386
6387         declaration_t *label = get_label(symbol);
6388
6389         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
6390         statement->base.source_position = token.source_position;
6391
6392         statement->gotos.label = label;
6393
6394         /* remember the goto's in a list for later checking */
6395         if (goto_last == NULL) {
6396                 goto_first = &statement->gotos;
6397         } else {
6398                 goto_last->next = &statement->gotos;
6399         }
6400         goto_last = &statement->gotos;
6401
6402         expect(';');
6403
6404         return statement;
6405 end_error:
6406         return NULL;
6407 }
6408
6409 /**
6410  * Parse a continue statement.
6411  */
6412 static statement_t *parse_continue(void)
6413 {
6414         statement_t *statement;
6415         if (current_loop == NULL) {
6416                 errorf(HERE, "continue statement not within loop");
6417                 statement = NULL;
6418         } else {
6419                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6420
6421                 statement->base.source_position = token.source_position;
6422         }
6423
6424         eat(T_continue);
6425         expect(';');
6426
6427         return statement;
6428 end_error:
6429         return NULL;
6430 }
6431
6432 /**
6433  * Parse a break statement.
6434  */
6435 static statement_t *parse_break(void)
6436 {
6437         statement_t *statement;
6438         if (current_switch == NULL && current_loop == NULL) {
6439                 errorf(HERE, "break statement not within loop or switch");
6440                 statement = NULL;
6441         } else {
6442                 statement = allocate_statement_zero(STATEMENT_BREAK);
6443
6444                 statement->base.source_position = token.source_position;
6445         }
6446
6447         eat(T_break);
6448         expect(';');
6449
6450         return statement;
6451 end_error:
6452         return NULL;
6453 }
6454
6455 /**
6456  * Check if a given declaration represents a local variable.
6457  */
6458 static bool is_local_var_declaration(const declaration_t *declaration) {
6459         switch ((storage_class_tag_t) declaration->storage_class) {
6460         case STORAGE_CLASS_AUTO:
6461         case STORAGE_CLASS_REGISTER: {
6462                 const type_t *type = skip_typeref(declaration->type);
6463                 if(is_type_function(type)) {
6464                         return false;
6465                 } else {
6466                         return true;
6467                 }
6468         }
6469         default:
6470                 return false;
6471         }
6472 }
6473
6474 /**
6475  * Check if a given declaration represents a variable.
6476  */
6477 static bool is_var_declaration(const declaration_t *declaration) {
6478         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6479                 return false;
6480
6481         const type_t *type = skip_typeref(declaration->type);
6482         return !is_type_function(type);
6483 }
6484
6485 /**
6486  * Check if a given expression represents a local variable.
6487  */
6488 static bool is_local_variable(const expression_t *expression)
6489 {
6490         if (expression->base.kind != EXPR_REFERENCE) {
6491                 return false;
6492         }
6493         const declaration_t *declaration = expression->reference.declaration;
6494         return is_local_var_declaration(declaration);
6495 }
6496
6497 /**
6498  * Check if a given expression represents a local variable and
6499  * return its declaration then, else return NULL.
6500  */
6501 declaration_t *expr_is_variable(const expression_t *expression)
6502 {
6503         if (expression->base.kind != EXPR_REFERENCE) {
6504                 return NULL;
6505         }
6506         declaration_t *declaration = expression->reference.declaration;
6507         if (is_var_declaration(declaration))
6508                 return declaration;
6509         return NULL;
6510 }
6511
6512 /**
6513  * Parse a return statement.
6514  */
6515 static statement_t *parse_return(void)
6516 {
6517         eat(T_return);
6518
6519         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
6520         statement->base.source_position = token.source_position;
6521
6522         expression_t *return_value = NULL;
6523         if(token.type != ';') {
6524                 return_value = parse_expression();
6525         }
6526         expect(';');
6527
6528         const type_t *const func_type = current_function->type;
6529         assert(is_type_function(func_type));
6530         type_t *const return_type = skip_typeref(func_type->function.return_type);
6531
6532         if(return_value != NULL) {
6533                 type_t *return_value_type = skip_typeref(return_value->base.type);
6534
6535                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6536                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6537                         warningf(statement->base.source_position,
6538                                  "'return' with a value, in function returning void");
6539                         return_value = NULL;
6540                 } else {
6541                         type_t *const res_type = semantic_assign(return_type,
6542                                 return_value, "'return'");
6543                         if (res_type == NULL) {
6544                                 errorf(statement->base.source_position,
6545                                        "cannot return something of type '%T' in function returning '%T'",
6546                                        return_value->base.type, return_type);
6547                         } else {
6548                                 return_value = create_implicit_cast(return_value, res_type);
6549                         }
6550                 }
6551                 /* check for returning address of a local var */
6552                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6553                         const expression_t *expression = return_value->unary.value;
6554                         if (is_local_variable(expression)) {
6555                                 warningf(statement->base.source_position,
6556                                          "function returns address of local variable");
6557                         }
6558                 }
6559         } else {
6560                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6561                         warningf(statement->base.source_position,
6562                                  "'return' without value, in function returning non-void");
6563                 }
6564         }
6565         statement->returns.value = return_value;
6566
6567         return statement;
6568 end_error:
6569         return NULL;
6570 }
6571
6572 /**
6573  * Parse a declaration statement.
6574  */
6575 static statement_t *parse_declaration_statement(void)
6576 {
6577         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6578
6579         statement->base.source_position = token.source_position;
6580
6581         declaration_t *before = last_declaration;
6582         parse_declaration(record_declaration);
6583
6584         if(before == NULL) {
6585                 statement->declaration.declarations_begin = scope->declarations;
6586         } else {
6587                 statement->declaration.declarations_begin = before->next;
6588         }
6589         statement->declaration.declarations_end = last_declaration;
6590
6591         return statement;
6592 }
6593
6594 /**
6595  * Parse an expression statement, ie. expr ';'.
6596  */
6597 static statement_t *parse_expression_statement(void)
6598 {
6599         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6600
6601         statement->base.source_position  = token.source_position;
6602         expression_t *const expr         = parse_expression();
6603         statement->expression.expression = expr;
6604
6605         if (warning.unused_value  && !expression_has_effect(expr)) {
6606                 warningf(expr->base.source_position, "statement has no effect");
6607         }
6608
6609         expect(';');
6610
6611         return statement;
6612 end_error:
6613         return NULL;
6614 }
6615
6616 /**
6617  * Parse a statement.
6618  */
6619 static statement_t *parse_statement(void)
6620 {
6621         statement_t   *statement = NULL;
6622
6623         /* declaration or statement */
6624         switch(token.type) {
6625         case T_asm:
6626                 statement = parse_asm_statement();
6627                 break;
6628
6629         case T_case:
6630                 statement = parse_case_statement();
6631                 break;
6632
6633         case T_default:
6634                 statement = parse_default_statement();
6635                 break;
6636
6637         case '{':
6638                 statement = parse_compound_statement();
6639                 break;
6640
6641         case T_if:
6642                 statement = parse_if();
6643                 break;
6644
6645         case T_switch:
6646                 statement = parse_switch();
6647                 break;
6648
6649         case T_while:
6650                 statement = parse_while();
6651                 break;
6652
6653         case T_do:
6654                 statement = parse_do();
6655                 break;
6656
6657         case T_for:
6658                 statement = parse_for();
6659                 break;
6660
6661         case T_goto:
6662                 statement = parse_goto();
6663                 break;
6664
6665         case T_continue:
6666                 statement = parse_continue();
6667                 break;
6668
6669         case T_break:
6670                 statement = parse_break();
6671                 break;
6672
6673         case T_return:
6674                 statement = parse_return();
6675                 break;
6676
6677         case ';':
6678                 if (warning.empty_statement) {
6679                         warningf(HERE, "statement is empty");
6680                 }
6681                 next_token();
6682                 statement = NULL;
6683                 break;
6684
6685         case T_IDENTIFIER:
6686                 if(look_ahead(1)->type == ':') {
6687                         statement = parse_label_statement();
6688                         break;
6689                 }
6690
6691                 if(is_typedef_symbol(token.v.symbol)) {
6692                         statement = parse_declaration_statement();
6693                         break;
6694                 }
6695
6696                 statement = parse_expression_statement();
6697                 break;
6698
6699         case T___extension__:
6700                 /* this can be a prefix to a declaration or an expression statement */
6701                 /* we simply eat it now and parse the rest with tail recursion */
6702                 do {
6703                         next_token();
6704                 } while(token.type == T___extension__);
6705                 statement = parse_statement();
6706                 break;
6707
6708         DECLARATION_START
6709                 statement = parse_declaration_statement();
6710                 break;
6711
6712         default:
6713                 statement = parse_expression_statement();
6714                 break;
6715         }
6716
6717         assert(statement == NULL
6718                         || statement->base.source_position.input_name != NULL);
6719
6720         return statement;
6721 }
6722
6723 /**
6724  * Parse a compound statement.
6725  */
6726 static statement_t *parse_compound_statement(void)
6727 {
6728         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6729
6730         statement->base.source_position = token.source_position;
6731
6732         eat('{');
6733
6734         int      top        = environment_top();
6735         scope_t *last_scope = scope;
6736         set_scope(&statement->compound.scope);
6737
6738         statement_t *last_statement = NULL;
6739
6740         while(token.type != '}' && token.type != T_EOF) {
6741                 statement_t *sub_statement = parse_statement();
6742                 if(sub_statement == NULL)
6743                         continue;
6744
6745                 if(last_statement != NULL) {
6746                         last_statement->base.next = sub_statement;
6747                 } else {
6748                         statement->compound.statements = sub_statement;
6749                 }
6750
6751                 while(sub_statement->base.next != NULL)
6752                         sub_statement = sub_statement->base.next;
6753
6754                 last_statement = sub_statement;
6755         }
6756
6757         if(token.type == '}') {
6758                 next_token();
6759         } else {
6760                 errorf(statement->base.source_position,
6761                        "end of file while looking for closing '}'");
6762         }
6763
6764         assert(scope == &statement->compound.scope);
6765         set_scope(last_scope);
6766         environment_pop_to(top);
6767
6768         return statement;
6769 }
6770
6771 /**
6772  * Initialize builtin types.
6773  */
6774 static void initialize_builtin_types(void)
6775 {
6776         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
6777         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
6778         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
6779         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
6780         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
6781         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6782         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
6783         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
6784
6785         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
6786         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6787         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
6788         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
6789 }
6790
6791 /**
6792  * Check for unused global static functions and variables
6793  */
6794 static void check_unused_globals(void)
6795 {
6796         if (!warning.unused_function && !warning.unused_variable)
6797                 return;
6798
6799         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6800                 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6801                         continue;
6802
6803                 type_t *const type = decl->type;
6804                 const char *s;
6805                 if (is_type_function(skip_typeref(type))) {
6806                         if (!warning.unused_function || decl->is_inline)
6807                                 continue;
6808
6809                         s = (decl->init.statement != NULL ? "defined" : "declared");
6810                 } else {
6811                         if (!warning.unused_variable)
6812                                 continue;
6813
6814                         s = "defined";
6815                 }
6816
6817                 warningf(decl->source_position, "'%#T' %s but not used",
6818                         type, decl->symbol, s);
6819         }
6820 }
6821
6822 /**
6823  * Parse a translation unit.
6824  */
6825 static translation_unit_t *parse_translation_unit(void)
6826 {
6827         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6828
6829         assert(global_scope == NULL);
6830         global_scope = &unit->scope;
6831
6832         assert(scope == NULL);
6833         set_scope(&unit->scope);
6834
6835         initialize_builtin_types();
6836
6837         while(token.type != T_EOF) {
6838                 if (token.type == ';') {
6839                         /* TODO error in strict mode */
6840                         warningf(HERE, "stray ';' outside of function");
6841                         next_token();
6842                 } else {
6843                         parse_external_declaration();
6844                 }
6845         }
6846
6847         assert(scope == &unit->scope);
6848         scope          = NULL;
6849         last_declaration = NULL;
6850
6851         assert(global_scope == &unit->scope);
6852         check_unused_globals();
6853         global_scope = NULL;
6854
6855         return unit;
6856 }
6857
6858 /**
6859  * Parse the input.
6860  *
6861  * @return  the translation unit or NULL if errors occurred.
6862  */
6863 translation_unit_t *parse(void)
6864 {
6865         environment_stack = NEW_ARR_F(stack_entry_t, 0);
6866         label_stack       = NEW_ARR_F(stack_entry_t, 0);
6867         diagnostic_count  = 0;
6868         error_count       = 0;
6869         warning_count     = 0;
6870
6871         type_set_output(stderr);
6872         ast_set_output(stderr);
6873
6874         lookahead_bufpos = 0;
6875         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6876                 next_token();
6877         }
6878         translation_unit_t *unit = parse_translation_unit();
6879
6880         DEL_ARR_F(environment_stack);
6881         DEL_ARR_F(label_stack);
6882
6883         if(error_count > 0)
6884                 return NULL;
6885
6886         return unit;
6887 }
6888
6889 /**
6890  * Initialize the parser.
6891  */
6892 void init_parser(void)
6893 {
6894         if(c_mode & _MS) {
6895                 /* add predefined symbols for extended-decl-modifier */
6896                 sym_align      = symbol_table_insert("align");
6897                 sym_allocate   = symbol_table_insert("allocate");
6898                 sym_dllimport  = symbol_table_insert("dllimport");
6899                 sym_dllexport  = symbol_table_insert("dllexport");
6900                 sym_naked      = symbol_table_insert("naked");
6901                 sym_noinline   = symbol_table_insert("noinline");
6902                 sym_noreturn   = symbol_table_insert("noreturn");
6903                 sym_nothrow    = symbol_table_insert("nothrow");
6904                 sym_novtable   = symbol_table_insert("novtable");
6905                 sym_property   = symbol_table_insert("property");
6906                 sym_get        = symbol_table_insert("get");
6907                 sym_put        = symbol_table_insert("put");
6908                 sym_selectany  = symbol_table_insert("selectany");
6909                 sym_thread     = symbol_table_insert("thread");
6910                 sym_uuid       = symbol_table_insert("uuid");
6911                 sym_deprecated = symbol_table_insert("deprecated");
6912         }
6913         init_expression_parsers();
6914         obstack_init(&temp_obst);
6915
6916         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6917         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6918 }
6919
6920 /**
6921  * Terminate the parser.
6922  */
6923 void exit_parser(void)
6924 {
6925         obstack_free(&temp_obst, NULL);
6926 }