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