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