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