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