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