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