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