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