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