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