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