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