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