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