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