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