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