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