b0031ea30b2fd9d3f06deb9799c2446adb15ac03
[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         } else {
4667                 /* parse function body */
4668                 int            label_stack_top      = label_top();
4669                 declaration_t *old_current_function = current_function;
4670                 current_function                    = declaration;
4671
4672                 declaration->init.statement = parse_compound_statement(false);
4673                 first_err = true;
4674                 check_labels();
4675                 check_declarations();
4676
4677                 assert(current_function == declaration);
4678                 current_function = old_current_function;
4679                 label_pop_to(label_stack_top);
4680         }
4681
4682         assert(scope == &declaration->scope);
4683         set_scope(last_scope);
4684         environment_pop_to(top);
4685 }
4686
4687 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4688                                   source_position_t *source_position)
4689 {
4690         type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4691
4692         type->bitfield.base_type = base_type;
4693         type->bitfield.size      = size;
4694
4695         return type;
4696 }
4697
4698 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4699                                           symbol_t *symbol)
4700 {
4701         declaration_t *iter = compound_declaration->scope.declarations;
4702         for( ; iter != NULL; iter = iter->next) {
4703                 if (iter->namespc != NAMESPACE_NORMAL)
4704                         continue;
4705
4706                 if (iter->symbol == NULL) {
4707                         type_t *type = skip_typeref(iter->type);
4708                         if (is_type_compound(type)) {
4709                                 declaration_t *result
4710                                         = find_compound_entry(type->compound.declaration, symbol);
4711                                 if (result != NULL)
4712                                         return result;
4713                         }
4714                         continue;
4715                 }
4716
4717                 if (iter->symbol == symbol) {
4718                         return iter;
4719                 }
4720         }
4721
4722         return NULL;
4723 }
4724
4725 static void parse_compound_declarators(declaration_t *struct_declaration,
4726                 const declaration_specifiers_t *specifiers)
4727 {
4728         declaration_t *last_declaration = struct_declaration->scope.declarations;
4729         if (last_declaration != NULL) {
4730                 while(last_declaration->next != NULL) {
4731                         last_declaration = last_declaration->next;
4732                 }
4733         }
4734
4735         while(1) {
4736                 declaration_t *declaration;
4737
4738                 if (token.type == ':') {
4739                         source_position_t source_position = *HERE;
4740                         next_token();
4741
4742                         type_t *base_type = specifiers->type;
4743                         expression_t *size = parse_constant_expression();
4744
4745                         if (!is_type_integer(skip_typeref(base_type))) {
4746                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
4747                                        base_type);
4748                         }
4749
4750                         type_t *type = make_bitfield_type(base_type, size, &source_position);
4751
4752                         declaration                         = allocate_declaration_zero();
4753                         declaration->namespc                = NAMESPACE_NORMAL;
4754                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
4755                         declaration->storage_class          = STORAGE_CLASS_NONE;
4756                         declaration->source_position        = source_position;
4757                         declaration->modifiers              = specifiers->modifiers;
4758                         declaration->type                   = type;
4759                 } else {
4760                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4761
4762                         type_t *orig_type = declaration->type;
4763                         type_t *type      = skip_typeref(orig_type);
4764
4765                         if (token.type == ':') {
4766                                 source_position_t source_position = *HERE;
4767                                 next_token();
4768                                 expression_t *size = parse_constant_expression();
4769
4770                                 if (!is_type_integer(type)) {
4771                                         errorf(HERE, "bitfield base type '%T' is not an "
4772                                                "integer type", orig_type);
4773                                 }
4774
4775                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4776                                 declaration->type = bitfield_type;
4777                         } else {
4778                                 /* TODO we ignore arrays for now... what is missing is a check
4779                                  * that they're at the end of the struct */
4780                                 if (is_type_incomplete(type) && !is_type_array(type)) {
4781                                         errorf(HERE,
4782                                                "compound member '%Y' has incomplete type '%T'",
4783                                                declaration->symbol, orig_type);
4784                                 } else if (is_type_function(type)) {
4785                                         errorf(HERE, "compound member '%Y' must not have function "
4786                                                "type '%T'", declaration->symbol, orig_type);
4787                                 }
4788                         }
4789                 }
4790
4791                 /* make sure we don't define a symbol multiple times */
4792                 symbol_t *symbol = declaration->symbol;
4793                 if (symbol != NULL) {
4794                         declaration_t *prev_decl
4795                                 = find_compound_entry(struct_declaration, symbol);
4796
4797                         if (prev_decl != NULL) {
4798                                 assert(prev_decl->symbol == symbol);
4799                                 errorf(&declaration->source_position,
4800                                        "multiple declarations of symbol '%Y' (declared %P)",
4801                                        symbol, &prev_decl->source_position);
4802                         }
4803                 }
4804
4805                 /* append declaration */
4806                 if (last_declaration != NULL) {
4807                         last_declaration->next = declaration;
4808                 } else {
4809                         struct_declaration->scope.declarations = declaration;
4810                 }
4811                 last_declaration = declaration;
4812
4813                 if (token.type != ',')
4814                         break;
4815                 next_token();
4816         }
4817         expect(';');
4818
4819 end_error:
4820         ;
4821 }
4822
4823 static void parse_compound_type_entries(declaration_t *compound_declaration)
4824 {
4825         eat('{');
4826         add_anchor_token('}');
4827
4828         while(token.type != '}' && token.type != T_EOF) {
4829                 declaration_specifiers_t specifiers;
4830                 memset(&specifiers, 0, sizeof(specifiers));
4831                 parse_declaration_specifiers(&specifiers);
4832
4833                 parse_compound_declarators(compound_declaration, &specifiers);
4834         }
4835         rem_anchor_token('}');
4836
4837         if (token.type == T_EOF) {
4838                 errorf(HERE, "EOF while parsing struct");
4839         }
4840         next_token();
4841 }
4842
4843 static type_t *parse_typename(void)
4844 {
4845         declaration_specifiers_t specifiers;
4846         memset(&specifiers, 0, sizeof(specifiers));
4847         parse_declaration_specifiers(&specifiers);
4848         if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4849                 /* TODO: improve error message, user does probably not know what a
4850                  * storage class is...
4851                  */
4852                 errorf(HERE, "typename may not have a storage class");
4853         }
4854
4855         type_t *result = parse_abstract_declarator(specifiers.type);
4856
4857         return result;
4858 }
4859
4860
4861
4862
4863 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4864 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4865                                                           expression_t *left);
4866
4867 typedef struct expression_parser_function_t expression_parser_function_t;
4868 struct expression_parser_function_t {
4869         unsigned                         precedence;
4870         parse_expression_function        parser;
4871         unsigned                         infix_precedence;
4872         parse_expression_infix_function  infix_parser;
4873 };
4874
4875 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4876
4877 /**
4878  * Prints an error message if an expression was expected but not read
4879  */
4880 static expression_t *expected_expression_error(void)
4881 {
4882         /* skip the error message if the error token was read */
4883         if (token.type != T_ERROR) {
4884                 errorf(HERE, "expected expression, got token '%K'", &token);
4885         }
4886         next_token();
4887
4888         return create_invalid_expression();
4889 }
4890
4891 /**
4892  * Parse a string constant.
4893  */
4894 static expression_t *parse_string_const(void)
4895 {
4896         wide_string_t wres;
4897         if (token.type == T_STRING_LITERAL) {
4898                 string_t res = token.v.string;
4899                 next_token();
4900                 while (token.type == T_STRING_LITERAL) {
4901                         res = concat_strings(&res, &token.v.string);
4902                         next_token();
4903                 }
4904                 if (token.type != T_WIDE_STRING_LITERAL) {
4905                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4906                         /* note: that we use type_char_ptr here, which is already the
4907                          * automatic converted type. revert_automatic_type_conversion
4908                          * will construct the array type */
4909                         cnst->base.type    = type_char_ptr;
4910                         cnst->string.value = res;
4911                         return cnst;
4912                 }
4913
4914                 wres = concat_string_wide_string(&res, &token.v.wide_string);
4915         } else {
4916                 wres = token.v.wide_string;
4917         }
4918         next_token();
4919
4920         for (;;) {
4921                 switch (token.type) {
4922                         case T_WIDE_STRING_LITERAL:
4923                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
4924                                 break;
4925
4926                         case T_STRING_LITERAL:
4927                                 wres = concat_wide_string_string(&wres, &token.v.string);
4928                                 break;
4929
4930                         default: {
4931                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4932                                 cnst->base.type         = type_wchar_t_ptr;
4933                                 cnst->wide_string.value = wres;
4934                                 return cnst;
4935                         }
4936                 }
4937                 next_token();
4938         }
4939 }
4940
4941 /**
4942  * Parse an integer constant.
4943  */
4944 static expression_t *parse_int_const(void)
4945 {
4946         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
4947         cnst->base.source_position = *HERE;
4948         cnst->base.type            = token.datatype;
4949         cnst->conste.v.int_value   = token.v.intvalue;
4950
4951         next_token();
4952
4953         return cnst;
4954 }
4955
4956 /**
4957  * Parse a character constant.
4958  */
4959 static expression_t *parse_character_constant(void)
4960 {
4961         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4962
4963         cnst->base.source_position = *HERE;
4964         cnst->base.type            = token.datatype;
4965         cnst->conste.v.character   = token.v.string;
4966
4967         if (cnst->conste.v.character.size != 1) {
4968                 if (warning.multichar && (c_mode & _GNUC)) {
4969                         /* TODO */
4970                         warningf(HERE, "multi-character character constant");
4971                 } else {
4972                         errorf(HERE, "more than 1 characters in character constant");
4973                 }
4974         }
4975         next_token();
4976
4977         return cnst;
4978 }
4979
4980 /**
4981  * Parse a wide character constant.
4982  */
4983 static expression_t *parse_wide_character_constant(void)
4984 {
4985         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4986
4987         cnst->base.source_position    = *HERE;
4988         cnst->base.type               = token.datatype;
4989         cnst->conste.v.wide_character = token.v.wide_string;
4990
4991         if (cnst->conste.v.wide_character.size != 1) {
4992                 if (warning.multichar && (c_mode & _GNUC)) {
4993                         /* TODO */
4994                         warningf(HERE, "multi-character character constant");
4995                 } else {
4996                         errorf(HERE, "more than 1 characters in character constant");
4997                 }
4998         }
4999         next_token();
5000
5001         return cnst;
5002 }
5003
5004 /**
5005  * Parse a float constant.
5006  */
5007 static expression_t *parse_float_const(void)
5008 {
5009         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5010         cnst->base.type            = token.datatype;
5011         cnst->conste.v.float_value = token.v.floatvalue;
5012
5013         next_token();
5014
5015         return cnst;
5016 }
5017
5018 static declaration_t *create_implicit_function(symbol_t *symbol,
5019                 const source_position_t *source_position)
5020 {
5021         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
5022         ntype->function.return_type            = type_int;
5023         ntype->function.unspecified_parameters = true;
5024
5025         type_t *type = typehash_insert(ntype);
5026         if (type != ntype) {
5027                 free_type(ntype);
5028         }
5029
5030         declaration_t *const declaration    = allocate_declaration_zero();
5031         declaration->storage_class          = STORAGE_CLASS_EXTERN;
5032         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5033         declaration->type                   = type;
5034         declaration->symbol                 = symbol;
5035         declaration->source_position        = *source_position;
5036
5037         bool strict_prototypes_old = warning.strict_prototypes;
5038         warning.strict_prototypes  = false;
5039         record_declaration(declaration);
5040         warning.strict_prototypes = strict_prototypes_old;
5041
5042         return declaration;
5043 }
5044
5045 /**
5046  * Creates a return_type (func)(argument_type) function type if not
5047  * already exists.
5048  */
5049 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5050                                     type_t *argument_type2)
5051 {
5052         function_parameter_t *parameter2
5053                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5054         memset(parameter2, 0, sizeof(parameter2[0]));
5055         parameter2->type = argument_type2;
5056
5057         function_parameter_t *parameter1
5058                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5059         memset(parameter1, 0, sizeof(parameter1[0]));
5060         parameter1->type = argument_type1;
5061         parameter1->next = parameter2;
5062
5063         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5064         type->function.return_type = return_type;
5065         type->function.parameters  = parameter1;
5066
5067         type_t *result = typehash_insert(type);
5068         if (result != type) {
5069                 free_type(type);
5070         }
5071
5072         return result;
5073 }
5074
5075 /**
5076  * Creates a return_type (func)(argument_type) function type if not
5077  * already exists.
5078  *
5079  * @param return_type    the return type
5080  * @param argument_type  the argument type
5081  */
5082 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5083 {
5084         function_parameter_t *parameter
5085                 = obstack_alloc(type_obst, sizeof(parameter[0]));
5086         memset(parameter, 0, sizeof(parameter[0]));
5087         parameter->type = argument_type;
5088
5089         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5090         type->function.return_type = return_type;
5091         type->function.parameters  = parameter;
5092
5093         type_t *result = typehash_insert(type);
5094         if (result != type) {
5095                 free_type(type);
5096         }
5097
5098         return result;
5099 }
5100
5101 static type_t *make_function_0_type(type_t *return_type)
5102 {
5103         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5104         type->function.return_type = return_type;
5105         type->function.parameters  = NULL;
5106
5107         type_t *result = typehash_insert(type);
5108         if (result != type) {
5109                 free_type(type);
5110         }
5111
5112         return result;
5113 }
5114
5115 /**
5116  * Creates a function type for some function like builtins.
5117  *
5118  * @param symbol   the symbol describing the builtin
5119  */
5120 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5121 {
5122         switch(symbol->ID) {
5123         case T___builtin_alloca:
5124                 return make_function_1_type(type_void_ptr, type_size_t);
5125         case T___builtin_huge_val:
5126                 return make_function_0_type(type_double);
5127         case T___builtin_nan:
5128                 return make_function_1_type(type_double, type_char_ptr);
5129         case T___builtin_nanf:
5130                 return make_function_1_type(type_float, type_char_ptr);
5131         case T___builtin_nand:
5132                 return make_function_1_type(type_long_double, type_char_ptr);
5133         case T___builtin_va_end:
5134                 return make_function_1_type(type_void, type_valist);
5135         case T___builtin_expect:
5136                 return make_function_2_type(type_long, type_long, type_long);
5137         default:
5138                 internal_errorf(HERE, "not implemented builtin symbol found");
5139         }
5140 }
5141
5142 /**
5143  * Performs automatic type cast as described in Â§ 6.3.2.1.
5144  *
5145  * @param orig_type  the original type
5146  */
5147 static type_t *automatic_type_conversion(type_t *orig_type)
5148 {
5149         type_t *type = skip_typeref(orig_type);
5150         if (is_type_array(type)) {
5151                 array_type_t *array_type   = &type->array;
5152                 type_t       *element_type = array_type->element_type;
5153                 unsigned      qualifiers   = array_type->base.qualifiers;
5154
5155                 return make_pointer_type(element_type, qualifiers);
5156         }
5157
5158         if (is_type_function(type)) {
5159                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5160         }
5161
5162         return orig_type;
5163 }
5164
5165 /**
5166  * reverts the automatic casts of array to pointer types and function
5167  * to function-pointer types as defined Â§ 6.3.2.1
5168  */
5169 type_t *revert_automatic_type_conversion(const expression_t *expression)
5170 {
5171         switch (expression->kind) {
5172                 case EXPR_REFERENCE: return expression->reference.declaration->type;
5173                 case EXPR_SELECT:    return expression->select.compound_entry->type;
5174
5175                 case EXPR_UNARY_DEREFERENCE: {
5176                         const expression_t *const value = expression->unary.value;
5177                         type_t             *const type  = skip_typeref(value->base.type);
5178                         assert(is_type_pointer(type));
5179                         return type->pointer.points_to;
5180                 }
5181
5182                 case EXPR_BUILTIN_SYMBOL:
5183                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5184
5185                 case EXPR_ARRAY_ACCESS: {
5186                         const expression_t *array_ref = expression->array_access.array_ref;
5187                         type_t             *type_left = skip_typeref(array_ref->base.type);
5188                         if (!is_type_valid(type_left))
5189                                 return type_left;
5190                         assert(is_type_pointer(type_left));
5191                         return type_left->pointer.points_to;
5192                 }
5193
5194                 case EXPR_STRING_LITERAL: {
5195                         size_t size = expression->string.value.size;
5196                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5197                 }
5198
5199                 case EXPR_WIDE_STRING_LITERAL: {
5200                         size_t size = expression->wide_string.value.size;
5201                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5202                 }
5203
5204                 case EXPR_COMPOUND_LITERAL:
5205                         return expression->compound_literal.type;
5206
5207                 default: break;
5208         }
5209
5210         return expression->base.type;
5211 }
5212
5213 static expression_t *parse_reference(void)
5214 {
5215         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5216
5217         reference_expression_t *ref = &expression->reference;
5218         symbol_t *const symbol = token.v.symbol;
5219
5220         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5221
5222         source_position_t source_position = token.source_position;
5223         next_token();
5224
5225         if (declaration == NULL) {
5226                 if (! strict_mode && token.type == '(') {
5227                         /* an implicitly defined function */
5228                         if (warning.implicit_function_declaration) {
5229                                 warningf(HERE, "implicit declaration of function '%Y'",
5230                                         symbol);
5231                         }
5232
5233                         declaration = create_implicit_function(symbol,
5234                                                                &source_position);
5235                 } else {
5236                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
5237                         return create_invalid_expression();
5238                 }
5239         }
5240
5241         type_t *type         = declaration->type;
5242
5243         /* we always do the auto-type conversions; the & and sizeof parser contains
5244          * code to revert this! */
5245         type = automatic_type_conversion(type);
5246
5247         ref->declaration = declaration;
5248         ref->base.type   = type;
5249
5250         /* this declaration is used */
5251         declaration->used = true;
5252
5253         /* check for deprecated functions */
5254         if (declaration->deprecated != 0) {
5255                 const char *prefix = "";
5256                 if (is_type_function(declaration->type))
5257                         prefix = "function ";
5258
5259                 if (declaration->deprecated_string != NULL) {
5260                         warningf(&source_position,
5261                                 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5262                                 declaration->deprecated_string);
5263                 } else {
5264                         warningf(&source_position,
5265                                 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5266                 }
5267         }
5268
5269         return expression;
5270 }
5271
5272 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5273 {
5274         (void) expression;
5275         (void) dest_type;
5276         /* TODO check if explicit cast is allowed and issue warnings/errors */
5277 }
5278
5279 static expression_t *parse_compound_literal(type_t *type)
5280 {
5281         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5282
5283         parse_initializer_env_t env;
5284         env.type             = type;
5285         env.declaration      = NULL;
5286         env.must_be_constant = false;
5287         initializer_t *initializer = parse_initializer(&env);
5288         type = env.type;
5289
5290         expression->compound_literal.initializer = initializer;
5291         expression->compound_literal.type        = type;
5292         expression->base.type                    = automatic_type_conversion(type);
5293
5294         return expression;
5295 }
5296
5297 /**
5298  * Parse a cast expression.
5299  */
5300 static expression_t *parse_cast(void)
5301 {
5302         source_position_t source_position = token.source_position;
5303
5304         type_t *type  = parse_typename();
5305
5306         /* matching add_anchor_token() is at call site */
5307         rem_anchor_token(')');
5308         expect(')');
5309
5310         if (token.type == '{') {
5311                 return parse_compound_literal(type);
5312         }
5313
5314         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5315         cast->base.source_position = source_position;
5316
5317         expression_t *value = parse_sub_expression(20);
5318
5319         check_cast_allowed(value, type);
5320
5321         cast->base.type   = type;
5322         cast->unary.value = value;
5323
5324         return cast;
5325 end_error:
5326         return create_invalid_expression();
5327 }
5328
5329 /**
5330  * Parse a statement expression.
5331  */
5332 static expression_t *parse_statement_expression(void)
5333 {
5334         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5335
5336         statement_t *statement           = parse_compound_statement(true);
5337         expression->statement.statement  = statement;
5338         expression->base.source_position = statement->base.source_position;
5339
5340         /* find last statement and use its type */
5341         type_t *type = type_void;
5342         const statement_t *stmt = statement->compound.statements;
5343         if (stmt != NULL) {
5344                 while (stmt->base.next != NULL)
5345                         stmt = stmt->base.next;
5346
5347                 if (stmt->kind == STATEMENT_EXPRESSION) {
5348                         type = stmt->expression.expression->base.type;
5349                 }
5350         } else {
5351                 warningf(&expression->base.source_position, "empty statement expression ({})");
5352         }
5353         expression->base.type = type;
5354
5355         expect(')');
5356
5357         return expression;
5358 end_error:
5359         return create_invalid_expression();
5360 }
5361
5362 /**
5363  * Parse a braced expression.
5364  */
5365 static expression_t *parse_brace_expression(void)
5366 {
5367         eat('(');
5368         add_anchor_token(')');
5369
5370         switch(token.type) {
5371         case '{':
5372                 /* gcc extension: a statement expression */
5373                 return parse_statement_expression();
5374
5375         TYPE_QUALIFIERS
5376         TYPE_SPECIFIERS
5377                 return parse_cast();
5378         case T_IDENTIFIER:
5379                 if (is_typedef_symbol(token.v.symbol)) {
5380                         return parse_cast();
5381                 }
5382         }
5383
5384         expression_t *result = parse_expression();
5385         rem_anchor_token(')');
5386         expect(')');
5387
5388         return result;
5389 end_error:
5390         return create_invalid_expression();
5391 }
5392
5393 static expression_t *parse_function_keyword(void)
5394 {
5395         next_token();
5396         /* TODO */
5397
5398         if (current_function == NULL) {
5399                 errorf(HERE, "'__func__' used outside of a function");
5400         }
5401
5402         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5403         expression->base.type     = type_char_ptr;
5404         expression->funcname.kind = FUNCNAME_FUNCTION;
5405
5406         return expression;
5407 }
5408
5409 static expression_t *parse_pretty_function_keyword(void)
5410 {
5411         eat(T___PRETTY_FUNCTION__);
5412
5413         if (current_function == NULL) {
5414                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5415         }
5416
5417         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5418         expression->base.type     = type_char_ptr;
5419         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5420
5421         return expression;
5422 }
5423
5424 static expression_t *parse_funcsig_keyword(void)
5425 {
5426         eat(T___FUNCSIG__);
5427
5428         if (current_function == NULL) {
5429                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5430         }
5431
5432         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5433         expression->base.type     = type_char_ptr;
5434         expression->funcname.kind = FUNCNAME_FUNCSIG;
5435
5436         return expression;
5437 }
5438
5439 static expression_t *parse_funcdname_keyword(void)
5440 {
5441         eat(T___FUNCDNAME__);
5442
5443         if (current_function == NULL) {
5444                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5445         }
5446
5447         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5448         expression->base.type     = type_char_ptr;
5449         expression->funcname.kind = FUNCNAME_FUNCDNAME;
5450
5451         return expression;
5452 }
5453
5454 static designator_t *parse_designator(void)
5455 {
5456         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
5457         result->source_position = *HERE;
5458
5459         if (token.type != T_IDENTIFIER) {
5460                 parse_error_expected("while parsing member designator",
5461                                      T_IDENTIFIER, NULL);
5462                 return NULL;
5463         }
5464         result->symbol = token.v.symbol;
5465         next_token();
5466
5467         designator_t *last_designator = result;
5468         while(true) {
5469                 if (token.type == '.') {
5470                         next_token();
5471                         if (token.type != T_IDENTIFIER) {
5472                                 parse_error_expected("while parsing member designator",
5473                                                      T_IDENTIFIER, NULL);
5474                                 return NULL;
5475                         }
5476                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5477                         designator->source_position = *HERE;
5478                         designator->symbol          = token.v.symbol;
5479                         next_token();
5480
5481                         last_designator->next = designator;
5482                         last_designator       = designator;
5483                         continue;
5484                 }
5485                 if (token.type == '[') {
5486                         next_token();
5487                         add_anchor_token(']');
5488                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5489                         designator->source_position = *HERE;
5490                         designator->array_index     = parse_expression();
5491                         rem_anchor_token(']');
5492                         expect(']');
5493                         if (designator->array_index == NULL) {
5494                                 return NULL;
5495                         }
5496
5497                         last_designator->next = designator;
5498                         last_designator       = designator;
5499                         continue;
5500                 }
5501                 break;
5502         }
5503
5504         return result;
5505 end_error:
5506         return NULL;
5507 }
5508
5509 /**
5510  * Parse the __builtin_offsetof() expression.
5511  */
5512 static expression_t *parse_offsetof(void)
5513 {
5514         eat(T___builtin_offsetof);
5515
5516         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5517         expression->base.type    = type_size_t;
5518
5519         expect('(');
5520         add_anchor_token(',');
5521         type_t *type = parse_typename();
5522         rem_anchor_token(',');
5523         expect(',');
5524         add_anchor_token(')');
5525         designator_t *designator = parse_designator();
5526         rem_anchor_token(')');
5527         expect(')');
5528
5529         expression->offsetofe.type       = type;
5530         expression->offsetofe.designator = designator;
5531
5532         type_path_t path;
5533         memset(&path, 0, sizeof(path));
5534         path.top_type = type;
5535         path.path     = NEW_ARR_F(type_path_entry_t, 0);
5536
5537         descend_into_subtype(&path);
5538
5539         if (!walk_designator(&path, designator, true)) {
5540                 return create_invalid_expression();
5541         }
5542
5543         DEL_ARR_F(path.path);
5544
5545         return expression;
5546 end_error:
5547         return create_invalid_expression();
5548 }
5549
5550 /**
5551  * Parses a _builtin_va_start() expression.
5552  */
5553 static expression_t *parse_va_start(void)
5554 {
5555         eat(T___builtin_va_start);
5556
5557         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5558
5559         expect('(');
5560         add_anchor_token(',');
5561         expression->va_starte.ap = parse_assignment_expression();
5562         rem_anchor_token(',');
5563         expect(',');
5564         expression_t *const expr = parse_assignment_expression();
5565         if (expr->kind == EXPR_REFERENCE) {
5566                 declaration_t *const decl = expr->reference.declaration;
5567                 if (decl == NULL)
5568                         return create_invalid_expression();
5569                 if (decl->parent_scope == &current_function->scope &&
5570                     decl->next == NULL) {
5571                         expression->va_starte.parameter = decl;
5572                         expect(')');
5573                         return expression;
5574                 }
5575         }
5576         errorf(&expr->base.source_position,
5577                "second argument of 'va_start' must be last parameter of the current function");
5578 end_error:
5579         return create_invalid_expression();
5580 }
5581
5582 /**
5583  * Parses a _builtin_va_arg() expression.
5584  */
5585 static expression_t *parse_va_arg(void)
5586 {
5587         eat(T___builtin_va_arg);
5588
5589         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5590
5591         expect('(');
5592         expression->va_arge.ap = parse_assignment_expression();
5593         expect(',');
5594         expression->base.type = parse_typename();
5595         expect(')');
5596
5597         return expression;
5598 end_error:
5599         return create_invalid_expression();
5600 }
5601
5602 static expression_t *parse_builtin_symbol(void)
5603 {
5604         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5605
5606         symbol_t *symbol = token.v.symbol;
5607
5608         expression->builtin_symbol.symbol = symbol;
5609         next_token();
5610
5611         type_t *type = get_builtin_symbol_type(symbol);
5612         type = automatic_type_conversion(type);
5613
5614         expression->base.type = type;
5615         return expression;
5616 }
5617
5618 /**
5619  * Parses a __builtin_constant() expression.
5620  */
5621 static expression_t *parse_builtin_constant(void)
5622 {
5623         eat(T___builtin_constant_p);
5624
5625         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5626
5627         expect('(');
5628         add_anchor_token(')');
5629         expression->builtin_constant.value = parse_assignment_expression();
5630         rem_anchor_token(')');
5631         expect(')');
5632         expression->base.type = type_int;
5633
5634         return expression;
5635 end_error:
5636         return create_invalid_expression();
5637 }
5638
5639 /**
5640  * Parses a __builtin_prefetch() expression.
5641  */
5642 static expression_t *parse_builtin_prefetch(void)
5643 {
5644         eat(T___builtin_prefetch);
5645
5646         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5647
5648         expect('(');
5649         add_anchor_token(')');
5650         expression->builtin_prefetch.adr = parse_assignment_expression();
5651         if (token.type == ',') {
5652                 next_token();
5653                 expression->builtin_prefetch.rw = parse_assignment_expression();
5654         }
5655         if (token.type == ',') {
5656                 next_token();
5657                 expression->builtin_prefetch.locality = parse_assignment_expression();
5658         }
5659         rem_anchor_token(')');
5660         expect(')');
5661         expression->base.type = type_void;
5662
5663         return expression;
5664 end_error:
5665         return create_invalid_expression();
5666 }
5667
5668 /**
5669  * Parses a __builtin_is_*() compare expression.
5670  */
5671 static expression_t *parse_compare_builtin(void)
5672 {
5673         expression_t *expression;
5674
5675         switch(token.type) {
5676         case T___builtin_isgreater:
5677                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5678                 break;
5679         case T___builtin_isgreaterequal:
5680                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5681                 break;
5682         case T___builtin_isless:
5683                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5684                 break;
5685         case T___builtin_islessequal:
5686                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5687                 break;
5688         case T___builtin_islessgreater:
5689                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5690                 break;
5691         case T___builtin_isunordered:
5692                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5693                 break;
5694         default:
5695                 internal_errorf(HERE, "invalid compare builtin found");
5696                 break;
5697         }
5698         expression->base.source_position = *HERE;
5699         next_token();
5700
5701         expect('(');
5702         expression->binary.left = parse_assignment_expression();
5703         expect(',');
5704         expression->binary.right = parse_assignment_expression();
5705         expect(')');
5706
5707         type_t *const orig_type_left  = expression->binary.left->base.type;
5708         type_t *const orig_type_right = expression->binary.right->base.type;
5709
5710         type_t *const type_left  = skip_typeref(orig_type_left);
5711         type_t *const type_right = skip_typeref(orig_type_right);
5712         if (!is_type_float(type_left) && !is_type_float(type_right)) {
5713                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5714                         type_error_incompatible("invalid operands in comparison",
5715                                 &expression->base.source_position, orig_type_left, orig_type_right);
5716                 }
5717         } else {
5718                 semantic_comparison(&expression->binary);
5719         }
5720
5721         return expression;
5722 end_error:
5723         return create_invalid_expression();
5724 }
5725
5726 #if 0
5727 /**
5728  * Parses a __builtin_expect() expression.
5729  */
5730 static expression_t *parse_builtin_expect(void)
5731 {
5732         eat(T___builtin_expect);
5733
5734         expression_t *expression
5735                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5736
5737         expect('(');
5738         expression->binary.left = parse_assignment_expression();
5739         expect(',');
5740         expression->binary.right = parse_constant_expression();
5741         expect(')');
5742
5743         expression->base.type = expression->binary.left->base.type;
5744
5745         return expression;
5746 end_error:
5747         return create_invalid_expression();
5748 }
5749 #endif
5750
5751 /**
5752  * Parses a MS assume() expression.
5753  */
5754 static expression_t *parse_assume(void) {
5755         eat(T__assume);
5756
5757         expression_t *expression
5758                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5759
5760         expect('(');
5761         add_anchor_token(')');
5762         expression->unary.value = parse_assignment_expression();
5763         rem_anchor_token(')');
5764         expect(')');
5765
5766         expression->base.type = type_void;
5767         return expression;
5768 end_error:
5769         return create_invalid_expression();
5770 }
5771
5772 /**
5773  * Parse a microsoft __noop expression.
5774  */
5775 static expression_t *parse_noop_expression(void) {
5776         source_position_t source_position = *HERE;
5777         eat(T___noop);
5778
5779         if (token.type == '(') {
5780                 /* parse arguments */
5781                 eat('(');
5782                 add_anchor_token(')');
5783                 add_anchor_token(',');
5784
5785                 if (token.type != ')') {
5786                         while(true) {
5787                                 (void)parse_assignment_expression();
5788                                 if (token.type != ',')
5789                                         break;
5790                                 next_token();
5791                         }
5792                 }
5793         }
5794         rem_anchor_token(',');
5795         rem_anchor_token(')');
5796         expect(')');
5797
5798         /* the result is a (int)0 */
5799         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5800         cnst->base.source_position = source_position;
5801         cnst->base.type            = type_int;
5802         cnst->conste.v.int_value   = 0;
5803         cnst->conste.is_ms_noop    = true;
5804
5805         return cnst;
5806
5807 end_error:
5808         return create_invalid_expression();
5809 }
5810
5811 /**
5812  * Parses a primary expression.
5813  */
5814 static expression_t *parse_primary_expression(void)
5815 {
5816         switch (token.type) {
5817                 case T_INTEGER:                  return parse_int_const();
5818                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
5819                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
5820                 case T_FLOATINGPOINT:            return parse_float_const();
5821                 case T_STRING_LITERAL:
5822                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
5823                 case T_IDENTIFIER:               return parse_reference();
5824                 case T___FUNCTION__:
5825                 case T___func__:                 return parse_function_keyword();
5826                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
5827                 case T___FUNCSIG__:              return parse_funcsig_keyword();
5828                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
5829                 case T___builtin_offsetof:       return parse_offsetof();
5830                 case T___builtin_va_start:       return parse_va_start();
5831                 case T___builtin_va_arg:         return parse_va_arg();
5832                 case T___builtin_expect:
5833                 case T___builtin_alloca:
5834                 case T___builtin_nan:
5835                 case T___builtin_nand:
5836                 case T___builtin_nanf:
5837                 case T___builtin_huge_val:
5838                 case T___builtin_va_end:         return parse_builtin_symbol();
5839                 case T___builtin_isgreater:
5840                 case T___builtin_isgreaterequal:
5841                 case T___builtin_isless:
5842                 case T___builtin_islessequal:
5843                 case T___builtin_islessgreater:
5844                 case T___builtin_isunordered:    return parse_compare_builtin();
5845                 case T___builtin_constant_p:     return parse_builtin_constant();
5846                 case T___builtin_prefetch:       return parse_builtin_prefetch();
5847                 case T__assume:                  return parse_assume();
5848
5849                 case '(':                        return parse_brace_expression();
5850                 case T___noop:                   return parse_noop_expression();
5851         }
5852
5853         errorf(HERE, "unexpected token %K, expected an expression", &token);
5854         return create_invalid_expression();
5855 }
5856
5857 /**
5858  * Check if the expression has the character type and issue a warning then.
5859  */
5860 static void check_for_char_index_type(const expression_t *expression) {
5861         type_t       *const type      = expression->base.type;
5862         const type_t *const base_type = skip_typeref(type);
5863
5864         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5865                         warning.char_subscripts) {
5866                 warningf(&expression->base.source_position,
5867                          "array subscript has type '%T'", type);
5868         }
5869 }
5870
5871 static expression_t *parse_array_expression(unsigned precedence,
5872                                             expression_t *left)
5873 {
5874         (void) precedence;
5875
5876         eat('[');
5877         add_anchor_token(']');
5878
5879         expression_t *inside = parse_expression();
5880
5881         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5882
5883         array_access_expression_t *array_access = &expression->array_access;
5884
5885         type_t *const orig_type_left   = left->base.type;
5886         type_t *const orig_type_inside = inside->base.type;
5887
5888         type_t *const type_left   = skip_typeref(orig_type_left);
5889         type_t *const type_inside = skip_typeref(orig_type_inside);
5890
5891         type_t *return_type;
5892         if (is_type_pointer(type_left)) {
5893                 return_type             = type_left->pointer.points_to;
5894                 array_access->array_ref = left;
5895                 array_access->index     = inside;
5896                 check_for_char_index_type(inside);
5897         } else if (is_type_pointer(type_inside)) {
5898                 return_type             = type_inside->pointer.points_to;
5899                 array_access->array_ref = inside;
5900                 array_access->index     = left;
5901                 array_access->flipped   = true;
5902                 check_for_char_index_type(left);
5903         } else {
5904                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5905                         errorf(HERE,
5906                                 "array access on object with non-pointer types '%T', '%T'",
5907                                 orig_type_left, orig_type_inside);
5908                 }
5909                 return_type             = type_error_type;
5910                 array_access->array_ref = create_invalid_expression();
5911         }
5912
5913         rem_anchor_token(']');
5914         if (token.type != ']') {
5915                 parse_error_expected("Problem while parsing array access", ']', NULL);
5916                 return expression;
5917         }
5918         next_token();
5919
5920         return_type           = automatic_type_conversion(return_type);
5921         expression->base.type = return_type;
5922
5923         return expression;
5924 }
5925
5926 static expression_t *parse_typeprop(expression_kind_t const kind,
5927                                     source_position_t const pos,
5928                                     unsigned const precedence)
5929 {
5930         expression_t *tp_expression = allocate_expression_zero(kind);
5931         tp_expression->base.type            = type_size_t;
5932         tp_expression->base.source_position = pos;
5933
5934         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5935
5936         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5937                 next_token();
5938                 add_anchor_token(')');
5939                 type_t* const orig_type = parse_typename();
5940                 tp_expression->typeprop.type = orig_type;
5941
5942                 type_t const* const type = skip_typeref(orig_type);
5943                 char const* const wrong_type =
5944                         is_type_incomplete(type)    ? "incomplete"          :
5945                         type->kind == TYPE_FUNCTION ? "function designator" :
5946                         type->kind == TYPE_BITFIELD ? "bitfield"            :
5947                         NULL;
5948                 if (wrong_type != NULL) {
5949                         errorf(&pos, "operand of %s expression must not be %s type '%T'",
5950                                what, wrong_type, type);
5951                 }
5952
5953                 rem_anchor_token(')');
5954                 expect(')');
5955         } else {
5956                 expression_t *expression = parse_sub_expression(precedence);
5957
5958                 type_t* const orig_type = revert_automatic_type_conversion(expression);
5959                 expression->base.type = orig_type;
5960
5961                 type_t const* const type = skip_typeref(orig_type);
5962                 char const* const wrong_type =
5963                         is_type_incomplete(type)    ? "incomplete"          :
5964                         type->kind == TYPE_FUNCTION ? "function designator" :
5965                         type->kind == TYPE_BITFIELD ? "bitfield"            :
5966                         NULL;
5967                 if (wrong_type != NULL) {
5968                         errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5969                 }
5970
5971                 tp_expression->typeprop.type          = expression->base.type;
5972                 tp_expression->typeprop.tp_expression = expression;
5973         }
5974
5975         return tp_expression;
5976 end_error:
5977         return create_invalid_expression();
5978 }
5979
5980 static expression_t *parse_sizeof(unsigned precedence)
5981 {
5982         source_position_t pos = *HERE;
5983         eat(T_sizeof);
5984         return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5985 }
5986
5987 static expression_t *parse_alignof(unsigned precedence)
5988 {
5989         source_position_t pos = *HERE;
5990         eat(T___alignof__);
5991         return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5992 }
5993
5994 static expression_t *parse_select_expression(unsigned precedence,
5995                                              expression_t *compound)
5996 {
5997         (void) precedence;
5998         assert(token.type == '.' || token.type == T_MINUSGREATER);
5999
6000         bool is_pointer = (token.type == T_MINUSGREATER);
6001         next_token();
6002
6003         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
6004         select->select.compound = compound;
6005
6006         if (token.type != T_IDENTIFIER) {
6007                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6008                 return select;
6009         }
6010         symbol_t *symbol      = token.v.symbol;
6011         select->select.symbol = symbol;
6012         next_token();
6013
6014         type_t *const orig_type = compound->base.type;
6015         type_t *const type      = skip_typeref(orig_type);
6016
6017         type_t *type_left = type;
6018         if (is_pointer) {
6019                 if (!is_type_pointer(type)) {
6020                         if (is_type_valid(type)) {
6021                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6022                         }
6023                         return create_invalid_expression();
6024                 }
6025                 type_left = type->pointer.points_to;
6026         }
6027         type_left = skip_typeref(type_left);
6028
6029         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6030             type_left->kind != TYPE_COMPOUND_UNION) {
6031                 if (is_type_valid(type_left)) {
6032                         errorf(HERE, "request for member '%Y' in something not a struct or "
6033                                "union, but '%T'", symbol, type_left);
6034                 }
6035                 return create_invalid_expression();
6036         }
6037
6038         declaration_t *const declaration = type_left->compound.declaration;
6039
6040         if (!declaration->init.complete) {
6041                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6042                        symbol, type_left);
6043                 return create_invalid_expression();
6044         }
6045
6046         declaration_t *iter = find_compound_entry(declaration, symbol);
6047         if (iter == NULL) {
6048                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6049                 return create_invalid_expression();
6050         }
6051
6052         /* we always do the auto-type conversions; the & and sizeof parser contains
6053          * code to revert this! */
6054         type_t *expression_type = automatic_type_conversion(iter->type);
6055
6056         select->select.compound_entry = iter;
6057         select->base.type             = expression_type;
6058
6059         type_t *skipped = skip_typeref(iter->type);
6060         if (skipped->kind == TYPE_BITFIELD) {
6061                 select->base.type = skipped->bitfield.base_type;
6062         }
6063
6064         return select;
6065 }
6066
6067 static void check_call_argument(const function_parameter_t *parameter,
6068                                 call_argument_t *argument)
6069 {
6070         type_t         *expected_type      = parameter->type;
6071         type_t         *expected_type_skip = skip_typeref(expected_type);
6072         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
6073         expression_t   *arg_expr           = argument->expression;
6074
6075         /* handle transparent union gnu extension */
6076         if (is_type_union(expected_type_skip)
6077                         && (expected_type_skip->base.modifiers
6078                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6079                 declaration_t  *union_decl = expected_type_skip->compound.declaration;
6080
6081                 declaration_t *declaration = union_decl->scope.declarations;
6082                 type_t        *best_type   = NULL;
6083                 for ( ; declaration != NULL; declaration = declaration->next) {
6084                         type_t *decl_type = declaration->type;
6085                         error = semantic_assign(decl_type, arg_expr);
6086                         if (error == ASSIGN_ERROR_INCOMPATIBLE
6087                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6088                                 continue;
6089
6090                         if (error == ASSIGN_SUCCESS) {
6091                                 best_type = decl_type;
6092                         } else if (best_type == NULL) {
6093                                 best_type = decl_type;
6094                         }
6095                 }
6096
6097                 if (best_type != NULL) {
6098                         expected_type = best_type;
6099                 }
6100         }
6101
6102         error                = semantic_assign(expected_type, arg_expr);
6103         argument->expression = create_implicit_cast(argument->expression,
6104                                                     expected_type);
6105
6106         /* TODO report exact scope in error messages (like "in 3rd parameter") */
6107         report_assign_error(error, expected_type, arg_expr,     "function call",
6108                             &arg_expr->base.source_position);
6109 }
6110
6111 /**
6112  * Parse a call expression, ie. expression '( ... )'.
6113  *
6114  * @param expression  the function address
6115  */
6116 static expression_t *parse_call_expression(unsigned precedence,
6117                                            expression_t *expression)
6118 {
6119         (void) precedence;
6120         expression_t *result = allocate_expression_zero(EXPR_CALL);
6121         result->base.source_position = expression->base.source_position;
6122
6123         call_expression_t *call = &result->call;
6124         call->function          = expression;
6125
6126         type_t *const orig_type = expression->base.type;
6127         type_t *const type      = skip_typeref(orig_type);
6128
6129         function_type_t *function_type = NULL;
6130         if (is_type_pointer(type)) {
6131                 type_t *const to_type = skip_typeref(type->pointer.points_to);
6132
6133                 if (is_type_function(to_type)) {
6134                         function_type   = &to_type->function;
6135                         call->base.type = function_type->return_type;
6136                 }
6137         }
6138
6139         if (function_type == NULL && is_type_valid(type)) {
6140                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6141         }
6142
6143         /* parse arguments */
6144         eat('(');
6145         add_anchor_token(')');
6146         add_anchor_token(',');
6147
6148         if (token.type != ')') {
6149                 call_argument_t *last_argument = NULL;
6150
6151                 while(true) {
6152                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6153
6154                         argument->expression = parse_assignment_expression();
6155                         if (last_argument == NULL) {
6156                                 call->arguments = argument;
6157                         } else {
6158                                 last_argument->next = argument;
6159                         }
6160                         last_argument = argument;
6161
6162                         if (token.type != ',')
6163                                 break;
6164                         next_token();
6165                 }
6166         }
6167         rem_anchor_token(',');
6168         rem_anchor_token(')');
6169         expect(')');
6170
6171         if (function_type == NULL)
6172                 return result;
6173
6174         function_parameter_t *parameter = function_type->parameters;
6175         call_argument_t      *argument  = call->arguments;
6176         if (!function_type->unspecified_parameters) {
6177                 for( ; parameter != NULL && argument != NULL;
6178                                 parameter = parameter->next, argument = argument->next) {
6179                         check_call_argument(parameter, argument);
6180                 }
6181
6182                 if (parameter != NULL) {
6183                         errorf(HERE, "too few arguments to function '%E'", expression);
6184                 } else if (argument != NULL && !function_type->variadic) {
6185                         errorf(HERE, "too many arguments to function '%E'", expression);
6186                 }
6187         }
6188
6189         /* do default promotion */
6190         for( ; argument != NULL; argument = argument->next) {
6191                 type_t *type = argument->expression->base.type;
6192
6193                 type = get_default_promoted_type(type);
6194
6195                 argument->expression
6196                         = create_implicit_cast(argument->expression, type);
6197         }
6198
6199         check_format(&result->call);
6200
6201         return result;
6202 end_error:
6203         return create_invalid_expression();
6204 }
6205
6206 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6207
6208 static bool same_compound_type(const type_t *type1, const type_t *type2)
6209 {
6210         return
6211                 is_type_compound(type1) &&
6212                 type1->kind == type2->kind &&
6213                 type1->compound.declaration == type2->compound.declaration;
6214 }
6215
6216 /**
6217  * Parse a conditional expression, ie. 'expression ? ... : ...'.
6218  *
6219  * @param expression  the conditional expression
6220  */
6221 static expression_t *parse_conditional_expression(unsigned precedence,
6222                                                   expression_t *expression)
6223 {
6224         eat('?');
6225         add_anchor_token(':');
6226
6227         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6228
6229         conditional_expression_t *conditional = &result->conditional;
6230         conditional->condition = expression;
6231
6232         /* 6.5.15.2 */
6233         type_t *const condition_type_orig = expression->base.type;
6234         type_t *const condition_type      = skip_typeref(condition_type_orig);
6235         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6236                 type_error("expected a scalar type in conditional condition",
6237                            &expression->base.source_position, condition_type_orig);
6238         }
6239
6240         expression_t *true_expression = parse_expression();
6241         rem_anchor_token(':');
6242         expect(':');
6243         expression_t *false_expression = parse_sub_expression(precedence);
6244
6245         type_t *const orig_true_type  = true_expression->base.type;
6246         type_t *const orig_false_type = false_expression->base.type;
6247         type_t *const true_type       = skip_typeref(orig_true_type);
6248         type_t *const false_type      = skip_typeref(orig_false_type);
6249
6250         /* 6.5.15.3 */
6251         type_t *result_type;
6252         if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6253                 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6254                 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6255                     || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6256                         warningf(&expression->base.source_position,
6257                                         "ISO C forbids conditional expression with only one void side");
6258                 }
6259                 result_type = type_void;
6260         } else if (is_type_arithmetic(true_type)
6261                    && is_type_arithmetic(false_type)) {
6262                 result_type = semantic_arithmetic(true_type, false_type);
6263
6264                 true_expression  = create_implicit_cast(true_expression, result_type);
6265                 false_expression = create_implicit_cast(false_expression, result_type);
6266
6267                 conditional->true_expression  = true_expression;
6268                 conditional->false_expression = false_expression;
6269                 conditional->base.type        = result_type;
6270         } else if (same_compound_type(true_type, false_type)) {
6271                 /* just take 1 of the 2 types */
6272                 result_type = true_type;
6273         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6274                 type_t *pointer_type;
6275                 type_t *other_type;
6276                 expression_t *other_expression;
6277                 if (is_type_pointer(true_type) &&
6278                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6279                         pointer_type     = true_type;
6280                         other_type       = false_type;
6281                         other_expression = false_expression;
6282                 } else {
6283                         pointer_type     = false_type;
6284                         other_type       = true_type;
6285                         other_expression = true_expression;
6286                 }
6287
6288                 if (is_null_pointer_constant(other_expression)) {
6289                         result_type = pointer_type;
6290                 } else if (is_type_pointer(other_type)) {
6291                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6292                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
6293
6294                         type_t *to;
6295                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6296                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6297                                 to = type_void;
6298                         } else if (types_compatible(get_unqualified_type(to1),
6299                                                     get_unqualified_type(to2))) {
6300                                 to = to1;
6301                         } else {
6302                                 warningf(&expression->base.source_position,
6303                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
6304                                         true_type, false_type);
6305                                 to = type_void;
6306                         }
6307
6308                         type_t *const copy = duplicate_type(to);
6309                         copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6310
6311                         type_t *const type = typehash_insert(copy);
6312                         if (type != copy)
6313                                 free_type(copy);
6314
6315                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6316                 } else if (is_type_integer(other_type)) {
6317                         warningf(&expression->base.source_position,
6318                                         "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6319                         result_type = pointer_type;
6320                 } else {
6321                         type_error_incompatible("while parsing conditional",
6322                                         &expression->base.source_position, true_type, false_type);
6323                         result_type = type_error_type;
6324                 }
6325         } else {
6326                 /* TODO: one pointer to void*, other some pointer */
6327
6328                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6329                         type_error_incompatible("while parsing conditional",
6330                                                 &expression->base.source_position, true_type,
6331                                                 false_type);
6332                 }
6333                 result_type = type_error_type;
6334         }
6335
6336         conditional->true_expression
6337                 = create_implicit_cast(true_expression, result_type);
6338         conditional->false_expression
6339                 = create_implicit_cast(false_expression, result_type);
6340         conditional->base.type = result_type;
6341         return result;
6342 end_error:
6343         return create_invalid_expression();
6344 }
6345
6346 /**
6347  * Parse an extension expression.
6348  */
6349 static expression_t *parse_extension(unsigned precedence)
6350 {
6351         eat(T___extension__);
6352
6353         /* TODO enable extensions */
6354         expression_t *expression = parse_sub_expression(precedence);
6355         /* TODO disable extensions */
6356         return expression;
6357 }
6358
6359 /**
6360  * Parse a __builtin_classify_type() expression.
6361  */
6362 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6363 {
6364         eat(T___builtin_classify_type);
6365
6366         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6367         result->base.type    = type_int;
6368
6369         expect('(');
6370         add_anchor_token(')');
6371         expression_t *expression = parse_sub_expression(precedence);
6372         rem_anchor_token(')');
6373         expect(')');
6374         result->classify_type.type_expression = expression;
6375
6376         return result;
6377 end_error:
6378         return create_invalid_expression();
6379 }
6380
6381 static void check_pointer_arithmetic(const source_position_t *source_position,
6382                                      type_t *pointer_type,
6383                                      type_t *orig_pointer_type)
6384 {
6385         type_t *points_to = pointer_type->pointer.points_to;
6386         points_to = skip_typeref(points_to);
6387
6388         if (is_type_incomplete(points_to) &&
6389                         (! (c_mode & _GNUC)
6390                          || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6391                 errorf(source_position,
6392                            "arithmetic with pointer to incomplete type '%T' not allowed",
6393                            orig_pointer_type);
6394         } else if (is_type_function(points_to)) {
6395                 errorf(source_position,
6396                            "arithmetic with pointer to function type '%T' not allowed",
6397                            orig_pointer_type);
6398         }
6399 }
6400
6401 static void semantic_incdec(unary_expression_t *expression)
6402 {
6403         type_t *const orig_type = expression->value->base.type;
6404         type_t *const type      = skip_typeref(orig_type);
6405         if (is_type_pointer(type)) {
6406                 check_pointer_arithmetic(&expression->base.source_position,
6407                                          type, orig_type);
6408         } else if (!is_type_real(type) && is_type_valid(type)) {
6409                 /* TODO: improve error message */
6410                 errorf(HERE, "operation needs an arithmetic or pointer type");
6411         }
6412         expression->base.type = orig_type;
6413 }
6414
6415 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6416 {
6417         type_t *const orig_type = expression->value->base.type;
6418         type_t *const type      = skip_typeref(orig_type);
6419         if (!is_type_arithmetic(type)) {
6420                 if (is_type_valid(type)) {
6421                         /* TODO: improve error message */
6422                         errorf(HERE, "operation needs an arithmetic type");
6423                 }
6424                 return;
6425         }
6426
6427         expression->base.type = orig_type;
6428 }
6429
6430 static void semantic_unexpr_scalar(unary_expression_t *expression)
6431 {
6432         type_t *const orig_type = expression->value->base.type;
6433         type_t *const type      = skip_typeref(orig_type);
6434         if (!is_type_scalar(type)) {
6435                 if (is_type_valid(type)) {
6436                         errorf(HERE, "operand of ! must be of scalar type");
6437                 }
6438                 return;
6439         }
6440
6441         expression->base.type = orig_type;
6442 }
6443
6444 static void semantic_unexpr_integer(unary_expression_t *expression)
6445 {
6446         type_t *const orig_type = expression->value->base.type;
6447         type_t *const type      = skip_typeref(orig_type);
6448         if (!is_type_integer(type)) {
6449                 if (is_type_valid(type)) {
6450                         errorf(HERE, "operand of ~ must be of integer type");
6451                 }
6452                 return;
6453         }
6454
6455         expression->base.type = orig_type;
6456 }
6457
6458 static void semantic_dereference(unary_expression_t *expression)
6459 {
6460         type_t *const orig_type = expression->value->base.type;
6461         type_t *const type      = skip_typeref(orig_type);
6462         if (!is_type_pointer(type)) {
6463                 if (is_type_valid(type)) {
6464                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6465                 }
6466                 return;
6467         }
6468
6469         type_t *result_type   = type->pointer.points_to;
6470         result_type           = automatic_type_conversion(result_type);
6471         expression->base.type = result_type;
6472 }
6473
6474 static void set_address_taken(expression_t *expression, bool may_be_register)
6475 {
6476         if (expression->kind != EXPR_REFERENCE)
6477                 return;
6478
6479         declaration_t *const declaration = expression->reference.declaration;
6480         /* happens for parse errors */
6481         if (declaration == NULL)
6482                 return;
6483
6484         if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6485                 errorf(&expression->base.source_position,
6486                                 "address of register variable '%Y' requested",
6487                                 declaration->symbol);
6488         } else {
6489                 declaration->address_taken = 1;
6490         }
6491 }
6492
6493 /**
6494  * Check the semantic of the address taken expression.
6495  */
6496 static void semantic_take_addr(unary_expression_t *expression)
6497 {
6498         expression_t *value = expression->value;
6499         value->base.type    = revert_automatic_type_conversion(value);
6500
6501         type_t *orig_type = value->base.type;
6502         if (!is_type_valid(orig_type))
6503                 return;
6504
6505         set_address_taken(value, false);
6506
6507         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6508 }
6509
6510 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
6511 static expression_t *parse_##unexpression_type(unsigned precedence)            \
6512 {                                                                              \
6513         eat(token_type);                                                           \
6514                                                                                    \
6515         expression_t *unary_expression                                             \
6516                 = allocate_expression_zero(unexpression_type);                         \
6517         unary_expression->base.source_position = *HERE;                            \
6518         unary_expression->unary.value = parse_sub_expression(precedence);          \
6519                                                                                    \
6520         sfunc(&unary_expression->unary);                                           \
6521                                                                                    \
6522         return unary_expression;                                                   \
6523 }
6524
6525 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6526                                semantic_unexpr_arithmetic)
6527 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6528                                semantic_unexpr_arithmetic)
6529 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6530                                semantic_unexpr_scalar)
6531 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6532                                semantic_dereference)
6533 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6534                                semantic_take_addr)
6535 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6536                                semantic_unexpr_integer)
6537 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
6538                                semantic_incdec)
6539 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6540                                semantic_incdec)
6541
6542 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6543                                                sfunc)                         \
6544 static expression_t *parse_##unexpression_type(unsigned precedence,           \
6545                                                expression_t *left)            \
6546 {                                                                             \
6547         (void) precedence;                                                        \
6548         eat(token_type);                                                          \
6549                                                                               \
6550         expression_t *unary_expression                                            \
6551                 = allocate_expression_zero(unexpression_type);                        \
6552         unary_expression->unary.value = left;                                     \
6553                                                                                   \
6554         sfunc(&unary_expression->unary);                                          \
6555                                                                               \
6556         return unary_expression;                                                  \
6557 }
6558
6559 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6560                                        EXPR_UNARY_POSTFIX_INCREMENT,
6561                                        semantic_incdec)
6562 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6563                                        EXPR_UNARY_POSTFIX_DECREMENT,
6564                                        semantic_incdec)
6565
6566 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6567 {
6568         /* TODO: handle complex + imaginary types */
6569
6570         /* Â§ 6.3.1.8 Usual arithmetic conversions */
6571         if (type_left == type_long_double || type_right == type_long_double) {
6572                 return type_long_double;
6573         } else if (type_left == type_double || type_right == type_double) {
6574                 return type_double;
6575         } else if (type_left == type_float || type_right == type_float) {
6576                 return type_float;
6577         }
6578
6579         type_right = promote_integer(type_right);
6580         type_left  = promote_integer(type_left);
6581
6582         if (type_left == type_right)
6583                 return type_left;
6584
6585         bool signed_left  = is_type_signed(type_left);
6586         bool signed_right = is_type_signed(type_right);
6587         int  rank_left    = get_rank(type_left);
6588         int  rank_right   = get_rank(type_right);
6589         if (rank_left < rank_right) {
6590                 if (signed_left == signed_right || !signed_right) {
6591                         return type_right;
6592                 } else {
6593                         return type_left;
6594                 }
6595         } else {
6596                 if (signed_left == signed_right || !signed_left) {
6597                         return type_left;
6598                 } else {
6599                         return type_right;
6600                 }
6601         }
6602 }
6603
6604 /**
6605  * Check the semantic restrictions for a binary expression.
6606  */
6607 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6608 {
6609         expression_t *const left            = expression->left;
6610         expression_t *const right           = expression->right;
6611         type_t       *const orig_type_left  = left->base.type;
6612         type_t       *const orig_type_right = right->base.type;
6613         type_t       *const type_left       = skip_typeref(orig_type_left);
6614         type_t       *const type_right      = skip_typeref(orig_type_right);
6615
6616         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6617                 /* TODO: improve error message */
6618                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6619                         errorf(HERE, "operation needs arithmetic types");
6620                 }
6621                 return;
6622         }
6623
6624         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6625         expression->left      = create_implicit_cast(left, arithmetic_type);
6626         expression->right     = create_implicit_cast(right, arithmetic_type);
6627         expression->base.type = arithmetic_type;
6628 }
6629
6630 static void semantic_shift_op(binary_expression_t *expression)
6631 {
6632         expression_t *const left            = expression->left;
6633         expression_t *const right           = expression->right;
6634         type_t       *const orig_type_left  = left->base.type;
6635         type_t       *const orig_type_right = right->base.type;
6636         type_t       *      type_left       = skip_typeref(orig_type_left);
6637         type_t       *      type_right      = skip_typeref(orig_type_right);
6638
6639         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6640                 /* TODO: improve error message */
6641                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6642                         errorf(HERE, "operation needs integer types");
6643                 }
6644                 return;
6645         }
6646
6647         type_left  = promote_integer(type_left);
6648         type_right = promote_integer(type_right);
6649
6650         expression->left      = create_implicit_cast(left, type_left);
6651         expression->right     = create_implicit_cast(right, type_right);
6652         expression->base.type = type_left;
6653 }
6654
6655 static void semantic_add(binary_expression_t *expression)
6656 {
6657         expression_t *const left            = expression->left;
6658         expression_t *const right           = expression->right;
6659         type_t       *const orig_type_left  = left->base.type;
6660         type_t       *const orig_type_right = right->base.type;
6661         type_t       *const type_left       = skip_typeref(orig_type_left);
6662         type_t       *const type_right      = skip_typeref(orig_type_right);
6663
6664         /* Â§ 6.5.6 */
6665         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6666                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6667                 expression->left  = create_implicit_cast(left, arithmetic_type);
6668                 expression->right = create_implicit_cast(right, arithmetic_type);
6669                 expression->base.type = arithmetic_type;
6670                 return;
6671         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6672                 check_pointer_arithmetic(&expression->base.source_position,
6673                                          type_left, orig_type_left);
6674                 expression->base.type = type_left;
6675         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6676                 check_pointer_arithmetic(&expression->base.source_position,
6677                                          type_right, orig_type_right);
6678                 expression->base.type = type_right;
6679         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6680                 errorf(&expression->base.source_position,
6681                        "invalid operands to binary + ('%T', '%T')",
6682                        orig_type_left, orig_type_right);
6683         }
6684 }
6685
6686 static void semantic_sub(binary_expression_t *expression)
6687 {
6688         expression_t *const left            = expression->left;
6689         expression_t *const right           = expression->right;
6690         type_t       *const orig_type_left  = left->base.type;
6691         type_t       *const orig_type_right = right->base.type;
6692         type_t       *const type_left       = skip_typeref(orig_type_left);
6693         type_t       *const type_right      = skip_typeref(orig_type_right);
6694
6695         /* Â§ 5.6.5 */
6696         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6697                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6698                 expression->left        = create_implicit_cast(left, arithmetic_type);
6699                 expression->right       = create_implicit_cast(right, arithmetic_type);
6700                 expression->base.type =  arithmetic_type;
6701                 return;
6702         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6703                 check_pointer_arithmetic(&expression->base.source_position,
6704                                          type_left, orig_type_left);
6705                 expression->base.type = type_left;
6706         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6707                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6708                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6709                 if (!types_compatible(unqual_left, unqual_right)) {
6710                         errorf(&expression->base.source_position,
6711                                "subtracting pointers to incompatible types '%T' and '%T'",
6712                                orig_type_left, orig_type_right);
6713                 } else if (!is_type_object(unqual_left)) {
6714                         if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6715                                 warningf(&expression->base.source_position,
6716                                          "subtracting pointers to void");
6717                         } else {
6718                                 errorf(&expression->base.source_position,
6719                                        "subtracting pointers to non-object types '%T'",
6720                                        orig_type_left);
6721                         }
6722                 }
6723                 expression->base.type = type_ptrdiff_t;
6724         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6725                 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6726                        orig_type_left, orig_type_right);
6727         }
6728 }
6729
6730 /**
6731  * Check the semantics of comparison expressions.
6732  *
6733  * @param expression   The expression to check.
6734  */
6735 static void semantic_comparison(binary_expression_t *expression)
6736 {
6737         expression_t *left            = expression->left;
6738         expression_t *right           = expression->right;
6739         type_t       *orig_type_left  = left->base.type;
6740         type_t       *orig_type_right = right->base.type;
6741
6742         type_t *type_left  = skip_typeref(orig_type_left);
6743         type_t *type_right = skip_typeref(orig_type_right);
6744
6745         /* TODO non-arithmetic types */
6746         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6747                 /* test for signed vs unsigned compares */
6748                 if (warning.sign_compare &&
6749                     (expression->base.kind != EXPR_BINARY_EQUAL &&
6750                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6751                     (is_type_signed(type_left) != is_type_signed(type_right))) {
6752
6753                         /* check if 1 of the operands is a constant, in this case we just
6754                          * check wether we can safely represent the resulting constant in
6755                          * the type of the other operand. */
6756                         expression_t *const_expr = NULL;
6757                         expression_t *other_expr = NULL;
6758
6759                         if (is_constant_expression(left)) {
6760                                 const_expr = left;
6761                                 other_expr = right;
6762                         } else if (is_constant_expression(right)) {
6763                                 const_expr = right;
6764                                 other_expr = left;
6765                         }
6766
6767                         if (const_expr != NULL) {
6768                                 type_t *other_type = skip_typeref(other_expr->base.type);
6769                                 long    val        = fold_constant(const_expr);
6770                                 /* TODO: check if val can be represented by other_type */
6771                                 (void) other_type;
6772                                 (void) val;
6773                         }
6774                         warningf(&expression->base.source_position,
6775                                  "comparison between signed and unsigned");
6776                 }
6777                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6778                 expression->left        = create_implicit_cast(left, arithmetic_type);
6779                 expression->right       = create_implicit_cast(right, arithmetic_type);
6780                 expression->base.type   = arithmetic_type;
6781                 if (warning.float_equal &&
6782                     (expression->base.kind == EXPR_BINARY_EQUAL ||
6783                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6784                     is_type_float(arithmetic_type)) {
6785                         warningf(&expression->base.source_position,
6786                                  "comparing floating point with == or != is unsafe");
6787                 }
6788         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6789                 /* TODO check compatibility */
6790         } else if (is_type_pointer(type_left)) {
6791                 expression->right = create_implicit_cast(right, type_left);
6792         } else if (is_type_pointer(type_right)) {
6793                 expression->left = create_implicit_cast(left, type_right);
6794         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6795                 type_error_incompatible("invalid operands in comparison",
6796                                         &expression->base.source_position,
6797                                         type_left, type_right);
6798         }
6799         expression->base.type = type_int;
6800 }
6801
6802 /**
6803  * Checks if a compound type has constant fields.
6804  */
6805 static bool has_const_fields(const compound_type_t *type)
6806 {
6807         const scope_t       *scope       = &type->declaration->scope;
6808         const declaration_t *declaration = scope->declarations;
6809
6810         for (; declaration != NULL; declaration = declaration->next) {
6811                 if (declaration->namespc != NAMESPACE_NORMAL)
6812                         continue;
6813
6814                 const type_t *decl_type = skip_typeref(declaration->type);
6815                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6816                         return true;
6817         }
6818         /* TODO */
6819         return false;
6820 }
6821
6822 static bool is_lvalue(const expression_t *expression)
6823 {
6824         switch (expression->kind) {
6825         case EXPR_REFERENCE:
6826         case EXPR_ARRAY_ACCESS:
6827         case EXPR_SELECT:
6828         case EXPR_UNARY_DEREFERENCE:
6829                 return true;
6830
6831         default:
6832                 return false;
6833         }
6834 }
6835
6836 static bool is_valid_assignment_lhs(expression_t const* const left)
6837 {
6838         type_t *const orig_type_left = revert_automatic_type_conversion(left);
6839         type_t *const type_left      = skip_typeref(orig_type_left);
6840
6841         if (!is_lvalue(left)) {
6842                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6843                        left);
6844                 return false;
6845         }
6846
6847         if (is_type_array(type_left)) {
6848                 errorf(HERE, "cannot assign to arrays ('%E')", left);
6849                 return false;
6850         }
6851         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6852                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6853                        orig_type_left);
6854                 return false;
6855         }
6856         if (is_type_incomplete(type_left)) {
6857                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6858                        left, orig_type_left);
6859                 return false;
6860         }
6861         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6862                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6863                        left, orig_type_left);
6864                 return false;
6865         }
6866
6867         return true;
6868 }
6869
6870 static void semantic_arithmetic_assign(binary_expression_t *expression)
6871 {
6872         expression_t *left            = expression->left;
6873         expression_t *right           = expression->right;
6874         type_t       *orig_type_left  = left->base.type;
6875         type_t       *orig_type_right = right->base.type;
6876
6877         if (!is_valid_assignment_lhs(left))
6878                 return;
6879
6880         type_t *type_left  = skip_typeref(orig_type_left);
6881         type_t *type_right = skip_typeref(orig_type_right);
6882
6883         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6884                 /* TODO: improve error message */
6885                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6886                         errorf(HERE, "operation needs arithmetic types");
6887                 }
6888                 return;
6889         }
6890
6891         /* combined instructions are tricky. We can't create an implicit cast on
6892          * the left side, because we need the uncasted form for the store.
6893          * The ast2firm pass has to know that left_type must be right_type
6894          * for the arithmetic operation and create a cast by itself */
6895         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6896         expression->right       = create_implicit_cast(right, arithmetic_type);
6897         expression->base.type   = type_left;
6898 }
6899
6900 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6901 {
6902         expression_t *const left            = expression->left;
6903         expression_t *const right           = expression->right;
6904         type_t       *const orig_type_left  = left->base.type;
6905         type_t       *const orig_type_right = right->base.type;
6906         type_t       *const type_left       = skip_typeref(orig_type_left);
6907         type_t       *const type_right      = skip_typeref(orig_type_right);
6908
6909         if (!is_valid_assignment_lhs(left))
6910                 return;
6911
6912         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6913                 /* combined instructions are tricky. We can't create an implicit cast on
6914                  * the left side, because we need the uncasted form for the store.
6915                  * The ast2firm pass has to know that left_type must be right_type
6916                  * for the arithmetic operation and create a cast by itself */
6917                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6918                 expression->right     = create_implicit_cast(right, arithmetic_type);
6919                 expression->base.type = type_left;
6920         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6921                 check_pointer_arithmetic(&expression->base.source_position,
6922                                          type_left, orig_type_left);
6923                 expression->base.type = type_left;
6924         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6925                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6926         }
6927 }
6928
6929 /**
6930  * Check the semantic restrictions of a logical expression.
6931  */
6932 static void semantic_logical_op(binary_expression_t *expression)
6933 {
6934         expression_t *const left            = expression->left;
6935         expression_t *const right           = expression->right;
6936         type_t       *const orig_type_left  = left->base.type;
6937         type_t       *const orig_type_right = right->base.type;
6938         type_t       *const type_left       = skip_typeref(orig_type_left);
6939         type_t       *const type_right      = skip_typeref(orig_type_right);
6940
6941         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6942                 /* TODO: improve error message */
6943                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6944                         errorf(HERE, "operation needs scalar types");
6945                 }
6946                 return;
6947         }
6948
6949         expression->base.type = type_int;
6950 }
6951
6952 /**
6953  * Check the semantic restrictions of a binary assign expression.
6954  */
6955 static void semantic_binexpr_assign(binary_expression_t *expression)
6956 {
6957         expression_t *left           = expression->left;
6958         type_t       *orig_type_left = left->base.type;
6959
6960         type_t *type_left = revert_automatic_type_conversion(left);
6961         type_left         = skip_typeref(orig_type_left);
6962
6963         if (!is_valid_assignment_lhs(left))
6964                 return;
6965
6966         assign_error_t error = semantic_assign(orig_type_left, expression->right);
6967         report_assign_error(error, orig_type_left, expression->right,
6968                         "assignment", &left->base.source_position);
6969         expression->right = create_implicit_cast(expression->right, orig_type_left);
6970         expression->base.type = orig_type_left;
6971 }
6972
6973 /**
6974  * Determine if the outermost operation (or parts thereof) of the given
6975  * expression has no effect in order to generate a warning about this fact.
6976  * Therefore in some cases this only examines some of the operands of the
6977  * expression (see comments in the function and examples below).
6978  * Examples:
6979  *   f() + 23;    // warning, because + has no effect
6980  *   x || f();    // no warning, because x controls execution of f()
6981  *   x ? y : f(); // warning, because y has no effect
6982  *   (void)x;     // no warning to be able to suppress the warning
6983  * This function can NOT be used for an "expression has definitely no effect"-
6984  * analysis. */
6985 static bool expression_has_effect(const expression_t *const expr)
6986 {
6987         switch (expr->kind) {
6988                 case EXPR_UNKNOWN:                   break;
6989                 case EXPR_INVALID:                   return true; /* do NOT warn */
6990                 case EXPR_REFERENCE:                 return false;
6991                 /* suppress the warning for microsoft __noop operations */
6992                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
6993                 case EXPR_CHARACTER_CONSTANT:        return false;
6994                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
6995                 case EXPR_STRING_LITERAL:            return false;
6996                 case EXPR_WIDE_STRING_LITERAL:       return false;
6997
6998                 case EXPR_CALL: {
6999                         const call_expression_t *const call = &expr->call;
7000                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7001                                 return true;
7002
7003                         switch (call->function->builtin_symbol.symbol->ID) {
7004                                 case T___builtin_va_end: return true;
7005                                 default:                 return false;
7006                         }
7007                 }
7008
7009                 /* Generate the warning if either the left or right hand side of a
7010                  * conditional expression has no effect */
7011                 case EXPR_CONDITIONAL: {
7012                         const conditional_expression_t *const cond = &expr->conditional;
7013                         return
7014                                 expression_has_effect(cond->true_expression) &&
7015                                 expression_has_effect(cond->false_expression);
7016                 }
7017
7018                 case EXPR_SELECT:                    return false;
7019                 case EXPR_ARRAY_ACCESS:              return false;
7020                 case EXPR_SIZEOF:                    return false;
7021                 case EXPR_CLASSIFY_TYPE:             return false;
7022                 case EXPR_ALIGNOF:                   return false;
7023
7024                 case EXPR_FUNCNAME:                  return false;
7025                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
7026                 case EXPR_BUILTIN_CONSTANT_P:        return false;
7027                 case EXPR_BUILTIN_PREFETCH:          return true;
7028                 case EXPR_OFFSETOF:                  return false;
7029                 case EXPR_VA_START:                  return true;
7030                 case EXPR_VA_ARG:                    return true;
7031                 case EXPR_STATEMENT:                 return true; // TODO
7032                 case EXPR_COMPOUND_LITERAL:          return false;
7033
7034                 case EXPR_UNARY_NEGATE:              return false;
7035                 case EXPR_UNARY_PLUS:                return false;
7036                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
7037                 case EXPR_UNARY_NOT:                 return false;
7038                 case EXPR_UNARY_DEREFERENCE:         return false;
7039                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
7040                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
7041                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
7042                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
7043                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
7044
7045                 /* Treat void casts as if they have an effect in order to being able to
7046                  * suppress the warning */
7047                 case EXPR_UNARY_CAST: {
7048                         type_t *const type = skip_typeref(expr->base.type);
7049                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
7050                 }
7051
7052                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
7053                 case EXPR_UNARY_ASSUME:              return true;
7054
7055                 case EXPR_BINARY_ADD:                return false;
7056                 case EXPR_BINARY_SUB:                return false;
7057                 case EXPR_BINARY_MUL:                return false;
7058                 case EXPR_BINARY_DIV:                return false;
7059                 case EXPR_BINARY_MOD:                return false;
7060                 case EXPR_BINARY_EQUAL:              return false;
7061                 case EXPR_BINARY_NOTEQUAL:           return false;
7062                 case EXPR_BINARY_LESS:               return false;
7063                 case EXPR_BINARY_LESSEQUAL:          return false;
7064                 case EXPR_BINARY_GREATER:            return false;
7065                 case EXPR_BINARY_GREATEREQUAL:       return false;
7066                 case EXPR_BINARY_BITWISE_AND:        return false;
7067                 case EXPR_BINARY_BITWISE_OR:         return false;
7068                 case EXPR_BINARY_BITWISE_XOR:        return false;
7069                 case EXPR_BINARY_SHIFTLEFT:          return false;
7070                 case EXPR_BINARY_SHIFTRIGHT:         return false;
7071                 case EXPR_BINARY_ASSIGN:             return true;
7072                 case EXPR_BINARY_MUL_ASSIGN:         return true;
7073                 case EXPR_BINARY_DIV_ASSIGN:         return true;
7074                 case EXPR_BINARY_MOD_ASSIGN:         return true;
7075                 case EXPR_BINARY_ADD_ASSIGN:         return true;
7076                 case EXPR_BINARY_SUB_ASSIGN:         return true;
7077                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
7078                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
7079                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7080                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7081                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
7082
7083                 /* Only examine the right hand side of && and ||, because the left hand
7084                  * side already has the effect of controlling the execution of the right
7085                  * hand side */
7086                 case EXPR_BINARY_LOGICAL_AND:
7087                 case EXPR_BINARY_LOGICAL_OR:
7088                 /* Only examine the right hand side of a comma expression, because the left
7089                  * hand side has a separate warning */
7090                 case EXPR_BINARY_COMMA:
7091                         return expression_has_effect(expr->binary.right);
7092
7093                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
7094                 case EXPR_BINARY_ISGREATER:          return false;
7095                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
7096                 case EXPR_BINARY_ISLESS:             return false;
7097                 case EXPR_BINARY_ISLESSEQUAL:        return false;
7098                 case EXPR_BINARY_ISLESSGREATER:      return false;
7099                 case EXPR_BINARY_ISUNORDERED:        return false;
7100         }
7101
7102         internal_errorf(HERE, "unexpected expression");
7103 }
7104
7105 static void semantic_comma(binary_expression_t *expression)
7106 {
7107         if (warning.unused_value) {
7108                 const expression_t *const left = expression->left;
7109                 if (!expression_has_effect(left)) {
7110                         warningf(&left->base.source_position,
7111                                  "left-hand operand of comma expression has no effect");
7112                 }
7113         }
7114         expression->base.type = expression->right->base.type;
7115 }
7116
7117 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
7118 static expression_t *parse_##binexpression_type(unsigned precedence,      \
7119                                                 expression_t *left)       \
7120 {                                                                         \
7121         eat(token_type);                                                      \
7122         source_position_t pos = *HERE;                                        \
7123                                                                           \
7124         expression_t *right = parse_sub_expression(precedence + lr);          \
7125                                                                           \
7126         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7127         binexpr->base.source_position = pos;                                  \
7128         binexpr->binary.left  = left;                                         \
7129         binexpr->binary.right = right;                                        \
7130         sfunc(&binexpr->binary);                                              \
7131                                                                           \
7132         return binexpr;                                                       \
7133 }
7134
7135 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
7136 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
7137 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
7138 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
7139 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
7140 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
7141 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
7142 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
7143 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
7144
7145 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
7146                       semantic_comparison, 1)
7147 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7148                       semantic_comparison, 1)
7149 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
7150                       semantic_comparison, 1)
7151 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
7152                       semantic_comparison, 1)
7153
7154 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7155                       semantic_binexpr_arithmetic, 1)
7156 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7157                       semantic_binexpr_arithmetic, 1)
7158 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7159                       semantic_binexpr_arithmetic, 1)
7160 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7161                       semantic_logical_op, 1)
7162 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7163                       semantic_logical_op, 1)
7164 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7165                       semantic_shift_op, 1)
7166 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7167                       semantic_shift_op, 1)
7168 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7169                       semantic_arithmetic_addsubb_assign, 0)
7170 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7171                       semantic_arithmetic_addsubb_assign, 0)
7172 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7173                       semantic_arithmetic_assign, 0)
7174 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7175                       semantic_arithmetic_assign, 0)
7176 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7177                       semantic_arithmetic_assign, 0)
7178 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7179                       semantic_arithmetic_assign, 0)
7180 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7181                       semantic_arithmetic_assign, 0)
7182 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7183                       semantic_arithmetic_assign, 0)
7184 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7185                       semantic_arithmetic_assign, 0)
7186 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7187                       semantic_arithmetic_assign, 0)
7188
7189 static expression_t *parse_sub_expression(unsigned precedence)
7190 {
7191         if (token.type < 0) {
7192                 return expected_expression_error();
7193         }
7194
7195         expression_parser_function_t *parser
7196                 = &expression_parsers[token.type];
7197         source_position_t             source_position = token.source_position;
7198         expression_t                 *left;
7199
7200         if (parser->parser != NULL) {
7201                 left = parser->parser(parser->precedence);
7202         } else {
7203                 left = parse_primary_expression();
7204         }
7205         assert(left != NULL);
7206         left->base.source_position = source_position;
7207
7208         while(true) {
7209                 if (token.type < 0) {
7210                         return expected_expression_error();
7211                 }
7212
7213                 parser = &expression_parsers[token.type];
7214                 if (parser->infix_parser == NULL)
7215                         break;
7216                 if (parser->infix_precedence < precedence)
7217                         break;
7218
7219                 left = parser->infix_parser(parser->infix_precedence, left);
7220
7221                 assert(left != NULL);
7222                 assert(left->kind != EXPR_UNKNOWN);
7223                 left->base.source_position = source_position;
7224         }
7225
7226         return left;
7227 }
7228
7229 /**
7230  * Parse an expression.
7231  */
7232 static expression_t *parse_expression(void)
7233 {
7234         return parse_sub_expression(1);
7235 }
7236
7237 /**
7238  * Register a parser for a prefix-like operator with given precedence.
7239  *
7240  * @param parser      the parser function
7241  * @param token_type  the token type of the prefix token
7242  * @param precedence  the precedence of the operator
7243  */
7244 static void register_expression_parser(parse_expression_function parser,
7245                                        int token_type, unsigned precedence)
7246 {
7247         expression_parser_function_t *entry = &expression_parsers[token_type];
7248
7249         if (entry->parser != NULL) {
7250                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7251                 panic("trying to register multiple expression parsers for a token");
7252         }
7253         entry->parser     = parser;
7254         entry->precedence = precedence;
7255 }
7256
7257 /**
7258  * Register a parser for an infix operator with given precedence.
7259  *
7260  * @param parser      the parser function
7261  * @param token_type  the token type of the infix operator
7262  * @param precedence  the precedence of the operator
7263  */
7264 static void register_infix_parser(parse_expression_infix_function parser,
7265                 int token_type, unsigned precedence)
7266 {
7267         expression_parser_function_t *entry = &expression_parsers[token_type];
7268
7269         if (entry->infix_parser != NULL) {
7270                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7271                 panic("trying to register multiple infix expression parsers for a "
7272                       "token");
7273         }
7274         entry->infix_parser     = parser;
7275         entry->infix_precedence = precedence;
7276 }
7277
7278 /**
7279  * Initialize the expression parsers.
7280  */
7281 static void init_expression_parsers(void)
7282 {
7283         memset(&expression_parsers, 0, sizeof(expression_parsers));
7284
7285         register_infix_parser(parse_array_expression,         '[',              30);
7286         register_infix_parser(parse_call_expression,          '(',              30);
7287         register_infix_parser(parse_select_expression,        '.',              30);
7288         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
7289         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7290                                                               T_PLUSPLUS,       30);
7291         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7292                                                               T_MINUSMINUS,     30);
7293
7294         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              17);
7295         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              17);
7296         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              17);
7297         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              16);
7298         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              16);
7299         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       15);
7300         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 15);
7301         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
7302         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
7303         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
7304         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
7305         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
7306         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7307                                                     T_EXCLAMATIONMARKEQUAL, 13);
7308         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
7309         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
7310         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
7311         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
7312         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
7313         register_infix_parser(parse_conditional_expression,   '?',               7);
7314         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
7315         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
7316         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
7317         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
7318         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
7319         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
7320         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7321                                                                 T_LESSLESSEQUAL, 2);
7322         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7323                                                           T_GREATERGREATEREQUAL, 2);
7324         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7325                                                                      T_ANDEQUAL, 2);
7326         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7327                                                                     T_PIPEEQUAL, 2);
7328         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7329                                                                    T_CARETEQUAL, 2);
7330
7331         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
7332
7333         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
7334         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
7335         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
7336         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
7337         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
7338         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
7339         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7340                                                                   T_PLUSPLUS,   25);
7341         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7342                                                                   T_MINUSMINUS, 25);
7343         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
7344         register_expression_parser(parse_alignof,                T___alignof__, 25);
7345         register_expression_parser(parse_extension,            T___extension__, 25);
7346         register_expression_parser(parse_builtin_classify_type,
7347                                                      T___builtin_classify_type, 25);
7348 }
7349
7350 /**
7351  * Parse a asm statement arguments specification.
7352  */
7353 static asm_argument_t *parse_asm_arguments(bool is_out)
7354 {
7355         asm_argument_t *result = NULL;
7356         asm_argument_t *last   = NULL;
7357
7358         while (token.type == T_STRING_LITERAL || token.type == '[') {
7359                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7360                 memset(argument, 0, sizeof(argument[0]));
7361
7362                 if (token.type == '[') {
7363                         eat('[');
7364                         if (token.type != T_IDENTIFIER) {
7365                                 parse_error_expected("while parsing asm argument",
7366                                                      T_IDENTIFIER, NULL);
7367                                 return NULL;
7368                         }
7369                         argument->symbol = token.v.symbol;
7370
7371                         expect(']');
7372                 }
7373
7374                 argument->constraints = parse_string_literals();
7375                 expect('(');
7376                 expression_t *expression = parse_expression();
7377                 argument->expression     = expression;
7378                 if (is_out && !is_lvalue(expression)) {
7379                         errorf(&expression->base.source_position,
7380                                "asm output argument is not an lvalue");
7381                 }
7382                 expect(')');
7383
7384                 set_address_taken(expression, true);
7385
7386                 if (last != NULL) {
7387                         last->next = argument;
7388                 } else {
7389                         result = argument;
7390                 }
7391                 last = argument;
7392
7393                 if (token.type != ',')
7394                         break;
7395                 eat(',');
7396         }
7397
7398         return result;
7399 end_error:
7400         return NULL;
7401 }
7402
7403 /**
7404  * Parse a asm statement clobber specification.
7405  */
7406 static asm_clobber_t *parse_asm_clobbers(void)
7407 {
7408         asm_clobber_t *result = NULL;
7409         asm_clobber_t *last   = NULL;
7410
7411         while(token.type == T_STRING_LITERAL) {
7412                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7413                 clobber->clobber       = parse_string_literals();
7414
7415                 if (last != NULL) {
7416                         last->next = clobber;
7417                 } else {
7418                         result = clobber;
7419                 }
7420                 last = clobber;
7421
7422                 if (token.type != ',')
7423                         break;
7424                 eat(',');
7425         }
7426
7427         return result;
7428 }
7429
7430 /**
7431  * Parse an asm statement.
7432  */
7433 static statement_t *parse_asm_statement(void)
7434 {
7435         eat(T_asm);
7436
7437         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
7438         statement->base.source_position = token.source_position;
7439
7440         asm_statement_t *asm_statement = &statement->asms;
7441
7442         if (token.type == T_volatile) {
7443                 next_token();
7444                 asm_statement->is_volatile = true;
7445         }
7446
7447         expect('(');
7448         add_anchor_token(')');
7449         add_anchor_token(':');
7450         asm_statement->asm_text = parse_string_literals();
7451
7452         if (token.type != ':') {
7453                 rem_anchor_token(':');
7454                 goto end_of_asm;
7455         }
7456         eat(':');
7457
7458         asm_statement->outputs = parse_asm_arguments(true);
7459         if (token.type != ':') {
7460                 rem_anchor_token(':');
7461                 goto end_of_asm;
7462         }
7463         eat(':');
7464
7465         asm_statement->inputs = parse_asm_arguments(false);
7466         if (token.type != ':') {
7467                 rem_anchor_token(':');
7468                 goto end_of_asm;
7469         }
7470         rem_anchor_token(':');
7471         eat(':');
7472
7473         asm_statement->clobbers = parse_asm_clobbers();
7474
7475 end_of_asm:
7476         rem_anchor_token(')');
7477         expect(')');
7478         expect(';');
7479         return statement;
7480 end_error:
7481         return create_invalid_statement();
7482 }
7483
7484 /**
7485  * Parse a case statement.
7486  */
7487 static statement_t *parse_case_statement(void)
7488 {
7489         eat(T_case);
7490
7491         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7492
7493         statement->base.source_position  = token.source_position;
7494         statement->case_label.expression = parse_expression();
7495
7496         if (c_mode & _GNUC) {
7497                 if (token.type == T_DOTDOTDOT) {
7498                         next_token();
7499                         statement->case_label.end_range = parse_expression();
7500                 }
7501         }
7502
7503         expect(':');
7504
7505         if (! is_constant_expression(statement->case_label.expression)) {
7506                 errorf(&statement->base.source_position,
7507                        "case label does not reduce to an integer constant");
7508         } else {
7509                 /* TODO: check if the case label is already known */
7510                 if (current_switch != NULL) {
7511                         /* link all cases into the switch statement */
7512                         if (current_switch->last_case == NULL) {
7513                                 current_switch->first_case =
7514                                 current_switch->last_case  = &statement->case_label;
7515                         } else {
7516                                 current_switch->last_case->next = &statement->case_label;
7517                         }
7518                 } else {
7519                         errorf(&statement->base.source_position,
7520                                "case label not within a switch statement");
7521                 }
7522         }
7523         statement->case_label.statement = parse_statement();
7524
7525         return statement;
7526 end_error:
7527         return create_invalid_statement();
7528 }
7529
7530 /**
7531  * Finds an existing default label of a switch statement.
7532  */
7533 static case_label_statement_t *
7534 find_default_label(const switch_statement_t *statement)
7535 {
7536         case_label_statement_t *label = statement->first_case;
7537         for ( ; label != NULL; label = label->next) {
7538                 if (label->expression == NULL)
7539                         return label;
7540         }
7541         return NULL;
7542 }
7543
7544 /**
7545  * Parse a default statement.
7546  */
7547 static statement_t *parse_default_statement(void)
7548 {
7549         eat(T_default);
7550
7551         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7552
7553         statement->base.source_position = token.source_position;
7554
7555         expect(':');
7556         if (current_switch != NULL) {
7557                 const case_label_statement_t *def_label = find_default_label(current_switch);
7558                 if (def_label != NULL) {
7559                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7560                                &def_label->base.source_position);
7561                 } else {
7562                         /* link all cases into the switch statement */
7563                         if (current_switch->last_case == NULL) {
7564                                 current_switch->first_case =
7565                                         current_switch->last_case  = &statement->case_label;
7566                         } else {
7567                                 current_switch->last_case->next = &statement->case_label;
7568                         }
7569                 }
7570         } else {
7571                 errorf(&statement->base.source_position,
7572                         "'default' label not within a switch statement");
7573         }
7574         statement->case_label.statement = parse_statement();
7575
7576         return statement;
7577 end_error:
7578         return create_invalid_statement();
7579 }
7580
7581 /**
7582  * Return the declaration for a given label symbol or create a new one.
7583  */
7584 static declaration_t *get_label(symbol_t *symbol)
7585 {
7586         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7587         assert(current_function != NULL);
7588         /* if we found a label in the same function, then we already created the
7589          * declaration */
7590         if (candidate != NULL
7591                         && candidate->parent_scope == &current_function->scope) {
7592                 return candidate;
7593         }
7594
7595         /* otherwise we need to create a new one */
7596         declaration_t *const declaration = allocate_declaration_zero();
7597         declaration->namespc       = NAMESPACE_LABEL;
7598         declaration->symbol        = symbol;
7599
7600         label_push(declaration);
7601
7602         return declaration;
7603 }
7604
7605 /**
7606  * Parse a label statement.
7607  */
7608 static statement_t *parse_label_statement(void)
7609 {
7610         assert(token.type == T_IDENTIFIER);
7611         symbol_t *symbol = token.v.symbol;
7612         next_token();
7613
7614         declaration_t *label = get_label(symbol);
7615
7616         /* if source position is already set then the label is defined twice,
7617          * otherwise it was just mentioned in a goto so far */
7618         if (label->source_position.input_name != NULL) {
7619                 errorf(HERE, "duplicate label '%Y' (declared %P)",
7620                        symbol, &label->source_position);
7621         } else {
7622                 label->source_position = token.source_position;
7623         }
7624
7625         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7626
7627         statement->base.source_position = token.source_position;
7628         statement->label.label          = label;
7629
7630         eat(':');
7631
7632         if (token.type == '}') {
7633                 /* TODO only warn? */
7634                 if (false) {
7635                         warningf(HERE, "label at end of compound statement");
7636                         statement->label.statement = create_empty_statement();
7637                 } else {
7638                         errorf(HERE, "label at end of compound statement");
7639                         statement->label.statement = create_invalid_statement();
7640                 }
7641                 return statement;
7642         } else {
7643                 if (token.type == ';') {
7644                         /* eat an empty statement here, to avoid the warning about an empty
7645                          * after a label.  label:; is commonly used to have a label before
7646                          * a }. */
7647                         statement->label.statement = create_empty_statement();
7648                         next_token();
7649                 } else {
7650                         statement->label.statement = parse_statement();
7651                 }
7652         }
7653
7654         /* remember the labels in a list for later checking */
7655         if (label_last == NULL) {
7656                 label_first = &statement->label;
7657         } else {
7658                 label_last->next = &statement->label;
7659         }
7660         label_last = &statement->label;
7661
7662         return statement;
7663 }
7664
7665 /**
7666  * Parse an if statement.
7667  */
7668 static statement_t *parse_if(void)
7669 {
7670         eat(T_if);
7671
7672         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
7673         statement->base.source_position = token.source_position;
7674
7675         expect('(');
7676         add_anchor_token(')');
7677         statement->ifs.condition = parse_expression();
7678         rem_anchor_token(')');
7679         expect(')');
7680
7681         add_anchor_token(T_else);
7682         statement->ifs.true_statement = parse_statement();
7683         rem_anchor_token(T_else);
7684
7685         if (token.type == T_else) {
7686                 next_token();
7687                 statement->ifs.false_statement = parse_statement();
7688         }
7689
7690         return statement;
7691 end_error:
7692         return create_invalid_statement();
7693 }
7694
7695 /**
7696  * Parse a switch statement.
7697  */
7698 static statement_t *parse_switch(void)
7699 {
7700         eat(T_switch);
7701
7702         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
7703         statement->base.source_position = token.source_position;
7704
7705         expect('(');
7706         expression_t *const expr = parse_expression();
7707         type_t       *      type = skip_typeref(expr->base.type);
7708         if (is_type_integer(type)) {
7709                 type = promote_integer(type);
7710         } else if (is_type_valid(type)) {
7711                 errorf(&expr->base.source_position,
7712                        "switch quantity is not an integer, but '%T'", type);
7713                 type = type_error_type;
7714         }
7715         statement->switchs.expression = create_implicit_cast(expr, type);
7716         expect(')');
7717
7718         switch_statement_t *rem = current_switch;
7719         current_switch          = &statement->switchs;
7720         statement->switchs.body = parse_statement();
7721         current_switch          = rem;
7722
7723         if (warning.switch_default &&
7724            find_default_label(&statement->switchs) == NULL) {
7725                 warningf(&statement->base.source_position, "switch has no default case");
7726         }
7727
7728         return statement;
7729 end_error:
7730         return create_invalid_statement();
7731 }
7732
7733 static statement_t *parse_loop_body(statement_t *const loop)
7734 {
7735         statement_t *const rem = current_loop;
7736         current_loop = loop;
7737
7738         statement_t *const body = parse_statement();
7739
7740         current_loop = rem;
7741         return body;
7742 }
7743
7744 /**
7745  * Parse a while statement.
7746  */
7747 static statement_t *parse_while(void)
7748 {
7749         eat(T_while);
7750
7751         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
7752         statement->base.source_position = token.source_position;
7753
7754         expect('(');
7755         add_anchor_token(')');
7756         statement->whiles.condition = parse_expression();
7757         rem_anchor_token(')');
7758         expect(')');
7759
7760         statement->whiles.body = parse_loop_body(statement);
7761
7762         return statement;
7763 end_error:
7764         return create_invalid_statement();
7765 }
7766
7767 /**
7768  * Parse a do statement.
7769  */
7770 static statement_t *parse_do(void)
7771 {
7772         eat(T_do);
7773
7774         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7775
7776         statement->base.source_position = token.source_position;
7777
7778         add_anchor_token(T_while);
7779         statement->do_while.body = parse_loop_body(statement);
7780         rem_anchor_token(T_while);
7781
7782         expect(T_while);
7783         expect('(');
7784         add_anchor_token(')');
7785         statement->do_while.condition = parse_expression();
7786         rem_anchor_token(')');
7787         expect(')');
7788         expect(';');
7789
7790         return statement;
7791 end_error:
7792         return create_invalid_statement();
7793 }
7794
7795 /**
7796  * Parse a for statement.
7797  */
7798 static statement_t *parse_for(void)
7799 {
7800         eat(T_for);
7801
7802         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
7803         statement->base.source_position = token.source_position;
7804
7805         int      top        = environment_top();
7806         scope_t *last_scope = scope;
7807         set_scope(&statement->fors.scope);
7808
7809         expect('(');
7810         add_anchor_token(')');
7811
7812         if (token.type != ';') {
7813                 if (is_declaration_specifier(&token, false)) {
7814                         parse_declaration(record_declaration);
7815                 } else {
7816                         add_anchor_token(';');
7817                         expression_t *const init = parse_expression();
7818                         statement->fors.initialisation = init;
7819                         if (warning.unused_value && !expression_has_effect(init)) {
7820                                 warningf(&init->base.source_position,
7821                                          "initialisation of 'for'-statement has no effect");
7822                         }
7823                         rem_anchor_token(';');
7824                         expect(';');
7825                 }
7826         } else {
7827                 expect(';');
7828         }
7829
7830         if (token.type != ';') {
7831                 add_anchor_token(';');
7832                 statement->fors.condition = parse_expression();
7833                 rem_anchor_token(';');
7834         }
7835         expect(';');
7836         if (token.type != ')') {
7837                 expression_t *const step = parse_expression();
7838                 statement->fors.step = step;
7839                 if (warning.unused_value && !expression_has_effect(step)) {
7840                         warningf(&step->base.source_position,
7841                                  "step of 'for'-statement has no effect");
7842                 }
7843         }
7844         rem_anchor_token(')');
7845         expect(')');
7846         statement->fors.body = parse_loop_body(statement);
7847
7848         assert(scope == &statement->fors.scope);
7849         set_scope(last_scope);
7850         environment_pop_to(top);
7851
7852         return statement;
7853
7854 end_error:
7855         rem_anchor_token(')');
7856         assert(scope == &statement->fors.scope);
7857         set_scope(last_scope);
7858         environment_pop_to(top);
7859
7860         return create_invalid_statement();
7861 }
7862
7863 /**
7864  * Parse a goto statement.
7865  */
7866 static statement_t *parse_goto(void)
7867 {
7868         eat(T_goto);
7869
7870         if (token.type != T_IDENTIFIER) {
7871                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7872                 eat_statement();
7873                 goto end_error;
7874         }
7875         symbol_t *symbol = token.v.symbol;
7876         next_token();
7877
7878         declaration_t *label = get_label(symbol);
7879
7880         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
7881         statement->base.source_position = token.source_position;
7882
7883         statement->gotos.label = label;
7884
7885         /* remember the goto's in a list for later checking */
7886         if (goto_last == NULL) {
7887                 goto_first = &statement->gotos;
7888         } else {
7889                 goto_last->next = &statement->gotos;
7890         }
7891         goto_last = &statement->gotos;
7892
7893         expect(';');
7894
7895         return statement;
7896 end_error:
7897         return create_invalid_statement();
7898 }
7899
7900 /**
7901  * Parse a continue statement.
7902  */
7903 static statement_t *parse_continue(void)
7904 {
7905         statement_t *statement;
7906         if (current_loop == NULL) {
7907                 errorf(HERE, "continue statement not within loop");
7908                 statement = create_invalid_statement();
7909         } else {
7910                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7911
7912                 statement->base.source_position = token.source_position;
7913         }
7914
7915         eat(T_continue);
7916         expect(';');
7917
7918         return statement;
7919 end_error:
7920         return create_invalid_statement();
7921 }
7922
7923 /**
7924  * Parse a break statement.
7925  */
7926 static statement_t *parse_break(void)
7927 {
7928         statement_t *statement;
7929         if (current_switch == NULL && current_loop == NULL) {
7930                 errorf(HERE, "break statement not within loop or switch");
7931                 statement = create_invalid_statement();
7932         } else {
7933                 statement = allocate_statement_zero(STATEMENT_BREAK);
7934
7935                 statement->base.source_position = token.source_position;
7936         }
7937
7938         eat(T_break);
7939         expect(';');
7940
7941         return statement;
7942 end_error:
7943         return create_invalid_statement();
7944 }
7945
7946 /**
7947  * Parse a __leave statement.
7948  */
7949 static statement_t *parse_leave(void)
7950 {
7951         statement_t *statement;
7952         if (current_try == NULL) {
7953                 errorf(HERE, "__leave statement not within __try");
7954                 statement = create_invalid_statement();
7955         } else {
7956                 statement = allocate_statement_zero(STATEMENT_LEAVE);
7957
7958                 statement->base.source_position = token.source_position;
7959         }
7960
7961         eat(T___leave);
7962         expect(';');
7963
7964         return statement;
7965 end_error:
7966         return create_invalid_statement();
7967 }
7968
7969 /**
7970  * Check if a given declaration represents a local variable.
7971  */
7972 static bool is_local_var_declaration(const declaration_t *declaration) {
7973         switch ((storage_class_tag_t) declaration->storage_class) {
7974         case STORAGE_CLASS_AUTO:
7975         case STORAGE_CLASS_REGISTER: {
7976                 const type_t *type = skip_typeref(declaration->type);
7977                 if (is_type_function(type)) {
7978                         return false;
7979                 } else {
7980                         return true;
7981                 }
7982         }
7983         default:
7984                 return false;
7985         }
7986 }
7987
7988 /**
7989  * Check if a given declaration represents a variable.
7990  */
7991 static bool is_var_declaration(const declaration_t *declaration) {
7992         if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7993                 return false;
7994
7995         const type_t *type = skip_typeref(declaration->type);
7996         return !is_type_function(type);
7997 }
7998
7999 /**
8000  * Check if a given expression represents a local variable.
8001  */
8002 static bool is_local_variable(const expression_t *expression)
8003 {
8004         if (expression->base.kind != EXPR_REFERENCE) {
8005                 return false;
8006         }
8007         const declaration_t *declaration = expression->reference.declaration;
8008         return is_local_var_declaration(declaration);
8009 }
8010
8011 /**
8012  * Check if a given expression represents a local variable and
8013  * return its declaration then, else return NULL.
8014  */
8015 declaration_t *expr_is_variable(const expression_t *expression)
8016 {
8017         if (expression->base.kind != EXPR_REFERENCE) {
8018                 return NULL;
8019         }
8020         declaration_t *declaration = expression->reference.declaration;
8021         if (is_var_declaration(declaration))
8022                 return declaration;
8023         return NULL;
8024 }
8025
8026 /**
8027  * Parse a return statement.
8028  */
8029 static statement_t *parse_return(void)
8030 {
8031         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
8032         statement->base.source_position = token.source_position;
8033
8034         eat(T_return);
8035
8036         expression_t *return_value = NULL;
8037         if (token.type != ';') {
8038                 return_value = parse_expression();
8039         }
8040         expect(';');
8041
8042         const type_t *const func_type = current_function->type;
8043         assert(is_type_function(func_type));
8044         type_t *const return_type = skip_typeref(func_type->function.return_type);
8045
8046         if (return_value != NULL) {
8047                 type_t *return_value_type = skip_typeref(return_value->base.type);
8048
8049                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8050                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8051                         warningf(&statement->base.source_position,
8052                                  "'return' with a value, in function returning void");
8053                         return_value = NULL;
8054                 } else {
8055                         assign_error_t error = semantic_assign(return_type, return_value);
8056                         report_assign_error(error, return_type, return_value, "'return'",
8057                                             &statement->base.source_position);
8058                         return_value = create_implicit_cast(return_value, return_type);
8059                 }
8060                 /* check for returning address of a local var */
8061                 if (return_value != NULL &&
8062                                 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8063                         const expression_t *expression = return_value->unary.value;
8064                         if (is_local_variable(expression)) {
8065                                 warningf(&statement->base.source_position,
8066                                          "function returns address of local variable");
8067                         }
8068                 }
8069         } else {
8070                 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8071                         warningf(&statement->base.source_position,
8072                                  "'return' without value, in function returning non-void");
8073                 }
8074         }
8075         statement->returns.value = return_value;
8076
8077         return statement;
8078 end_error:
8079         return create_invalid_statement();
8080 }
8081
8082 /**
8083  * Parse a declaration statement.
8084  */
8085 static statement_t *parse_declaration_statement(void)
8086 {
8087         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8088
8089         statement->base.source_position = token.source_position;
8090
8091         declaration_t *before = last_declaration;
8092         parse_declaration(record_declaration);
8093
8094         if (before == NULL) {
8095                 statement->declaration.declarations_begin = scope->declarations;
8096         } else {
8097                 statement->declaration.declarations_begin = before->next;
8098         }
8099         statement->declaration.declarations_end = last_declaration;
8100
8101         return statement;
8102 }
8103
8104 /**
8105  * Parse an expression statement, ie. expr ';'.
8106  */
8107 static statement_t *parse_expression_statement(void)
8108 {
8109         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8110
8111         statement->base.source_position  = token.source_position;
8112         expression_t *const expr         = parse_expression();
8113         statement->expression.expression = expr;
8114
8115         expect(';');
8116
8117         return statement;
8118 end_error:
8119         return create_invalid_statement();
8120 }
8121
8122 /**
8123  * Parse a microsoft __try { } __finally { } or
8124  * __try{ } __except() { }
8125  */
8126 static statement_t *parse_ms_try_statment(void) {
8127         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8128
8129         statement->base.source_position  = token.source_position;
8130         eat(T___try);
8131
8132         ms_try_statement_t *rem = current_try;
8133         current_try = &statement->ms_try;
8134         statement->ms_try.try_statement = parse_compound_statement(false);
8135         current_try = rem;
8136
8137         if (token.type == T___except) {
8138                 eat(T___except);
8139                 expect('(');
8140                 add_anchor_token(')');
8141                 expression_t *const expr = parse_expression();
8142                 type_t       *      type = skip_typeref(expr->base.type);
8143                 if (is_type_integer(type)) {
8144                         type = promote_integer(type);
8145                 } else if (is_type_valid(type)) {
8146                         errorf(&expr->base.source_position,
8147                                "__expect expression is not an integer, but '%T'", type);
8148                         type = type_error_type;
8149                 }
8150                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8151                 rem_anchor_token(')');
8152                 expect(')');
8153                 statement->ms_try.final_statement = parse_compound_statement(false);
8154         } else if (token.type == T__finally) {
8155                 eat(T___finally);
8156                 statement->ms_try.final_statement = parse_compound_statement(false);
8157         } else {
8158                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8159                 return create_invalid_statement();
8160         }
8161         return statement;
8162 end_error:
8163         return create_invalid_statement();
8164 }
8165
8166 /**
8167  * Parse a statement.
8168  * There's also parse_statement() which additionally checks for
8169  * "statement has no effect" warnings
8170  */
8171 static statement_t *intern_parse_statement(void)
8172 {
8173         statement_t *statement = NULL;
8174
8175         /* declaration or statement */
8176         add_anchor_token(';');
8177         switch(token.type) {
8178         case T_asm:
8179                 statement = parse_asm_statement();
8180                 break;
8181
8182         case T_case:
8183                 statement = parse_case_statement();
8184                 break;
8185
8186         case T_default:
8187                 statement = parse_default_statement();
8188                 break;
8189
8190         case '{':
8191                 statement = parse_compound_statement(false);
8192                 break;
8193
8194         case T_if:
8195                 statement = parse_if ();
8196                 break;
8197
8198         case T_switch:
8199                 statement = parse_switch();
8200                 break;
8201
8202         case T_while:
8203                 statement = parse_while();
8204                 break;
8205
8206         case T_do:
8207                 statement = parse_do();
8208                 break;
8209
8210         case T_for:
8211                 statement = parse_for();
8212                 break;
8213
8214         case T_goto:
8215                 statement = parse_goto();
8216                 break;
8217
8218         case T_continue:
8219                 statement = parse_continue();
8220                 break;
8221
8222         case T_break:
8223                 statement = parse_break();
8224                 break;
8225
8226         case T___leave:
8227                 statement = parse_leave();
8228                 break;
8229
8230         case T_return:
8231                 statement = parse_return();
8232                 break;
8233
8234         case ';':
8235                 if (warning.empty_statement) {
8236                         warningf(HERE, "statement is empty");
8237                 }
8238                 statement = create_empty_statement();
8239                 next_token();
8240                 break;
8241
8242         case T_IDENTIFIER:
8243                 if (look_ahead(1)->type == ':') {
8244                         statement = parse_label_statement();
8245                         break;
8246                 }
8247
8248                 if (is_typedef_symbol(token.v.symbol)) {
8249                         statement = parse_declaration_statement();
8250                         break;
8251                 }
8252
8253                 statement = parse_expression_statement();
8254                 break;
8255
8256         case T___extension__:
8257                 /* this can be a prefix to a declaration or an expression statement */
8258                 /* we simply eat it now and parse the rest with tail recursion */
8259                 do {
8260                         next_token();
8261                 } while(token.type == T___extension__);
8262                 statement = parse_statement();
8263                 break;
8264
8265         DECLARATION_START
8266                 statement = parse_declaration_statement();
8267                 break;
8268
8269         case T___try:
8270                 statement = parse_ms_try_statment();
8271                 break;
8272
8273         default:
8274                 statement = parse_expression_statement();
8275                 break;
8276         }
8277         rem_anchor_token(';');
8278
8279         assert(statement != NULL
8280                         && statement->base.source_position.input_name != NULL);
8281
8282         return statement;
8283 }
8284
8285 /**
8286  * parse a statement and emits "statement has no effect" warning if needed
8287  * (This is really a wrapper around intern_parse_statement with check for 1
8288  *  single warning. It is needed, because for statement expressions we have
8289  *  to avoid the warning on the last statement)
8290  */
8291 static statement_t *parse_statement(void)
8292 {
8293         statement_t *statement = intern_parse_statement();
8294
8295         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8296                 expression_t *expression = statement->expression.expression;
8297                 if (!expression_has_effect(expression)) {
8298                         warningf(&expression->base.source_position,
8299                                         "statement has no effect");
8300                 }
8301         }
8302
8303         return statement;
8304 }
8305
8306 /**
8307  * Parse a compound statement.
8308  */
8309 static statement_t *parse_compound_statement(bool inside_expression_statement)
8310 {
8311         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8312
8313         statement->base.source_position = token.source_position;
8314
8315         eat('{');
8316         add_anchor_token('}');
8317
8318         int      top        = environment_top();
8319         scope_t *last_scope = scope;
8320         set_scope(&statement->compound.scope);
8321
8322         statement_t *last_statement = NULL;
8323
8324         while(token.type != '}' && token.type != T_EOF) {
8325                 statement_t *sub_statement = intern_parse_statement();
8326                 if (is_invalid_statement(sub_statement)) {
8327                         /* an error occurred. if we are at an anchor, return */
8328                         if (at_anchor())
8329                                 goto end_error;
8330                         continue;
8331                 }
8332
8333                 if (last_statement != NULL) {
8334                         last_statement->base.next = sub_statement;
8335                 } else {
8336                         statement->compound.statements = sub_statement;
8337                 }
8338
8339                 while(sub_statement->base.next != NULL)
8340                         sub_statement = sub_statement->base.next;
8341
8342                 last_statement = sub_statement;
8343         }
8344
8345         if (token.type == '}') {
8346                 next_token();
8347         } else {
8348                 errorf(&statement->base.source_position,
8349                        "end of file while looking for closing '}'");
8350         }
8351
8352         /* look over all statements again to produce no effect warnings */
8353         if (warning.unused_value) {
8354                 statement_t *sub_statement = statement->compound.statements;
8355                 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8356                         if (sub_statement->kind != STATEMENT_EXPRESSION)
8357                                 continue;
8358                         /* don't emit a warning for the last expression in an expression
8359                          * statement as it has always an effect */
8360                         if (inside_expression_statement && sub_statement->base.next == NULL)
8361                                 continue;
8362
8363                         expression_t *expression = sub_statement->expression.expression;
8364                         if (!expression_has_effect(expression)) {
8365                                 warningf(&expression->base.source_position,
8366                                          "statement has no effect");
8367                         }
8368                 }
8369         }
8370
8371 end_error:
8372         rem_anchor_token('}');
8373         assert(scope == &statement->compound.scope);
8374         set_scope(last_scope);
8375         environment_pop_to(top);
8376
8377         return statement;
8378 }
8379
8380 /**
8381  * Initialize builtin types.
8382  */
8383 static void initialize_builtin_types(void)
8384 {
8385         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
8386         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
8387         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
8388         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
8389         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
8390         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8391         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
8392         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
8393
8394         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
8395         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8396         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
8397         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
8398 }
8399
8400 /**
8401  * Check for unused global static functions and variables
8402  */
8403 static void check_unused_globals(void)
8404 {
8405         if (!warning.unused_function && !warning.unused_variable)
8406                 return;
8407
8408         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8409                 if (decl->used                ||
8410                     decl->modifiers & DM_USED ||
8411                     decl->storage_class != STORAGE_CLASS_STATIC)
8412                         continue;
8413
8414                 type_t *const type = decl->type;
8415                 const char *s;
8416                 if (is_type_function(skip_typeref(type))) {
8417                         if (!warning.unused_function || decl->is_inline)
8418                                 continue;
8419
8420                         s = (decl->init.statement != NULL ? "defined" : "declared");
8421                 } else {
8422                         if (!warning.unused_variable)
8423                                 continue;
8424
8425                         s = "defined";
8426                 }
8427
8428                 warningf(&decl->source_position, "'%#T' %s but not used",
8429                         type, decl->symbol, s);
8430         }
8431 }
8432
8433 static void parse_global_asm(void)
8434 {
8435         eat(T_asm);
8436         expect('(');
8437
8438         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
8439         statement->base.source_position = token.source_position;
8440         statement->asms.asm_text        = parse_string_literals();
8441         statement->base.next            = unit->global_asm;
8442         unit->global_asm                = statement;
8443
8444         expect(')');
8445         expect(';');
8446
8447 end_error:;
8448 }
8449
8450 /**
8451  * Parse a translation unit.
8452  */
8453 static void parse_translation_unit(void)
8454 {
8455         while(token.type != T_EOF) {
8456                 switch (token.type) {
8457                         case ';':
8458                                 /* TODO error in strict mode */
8459                                 warningf(HERE, "stray ';' outside of function");
8460                                 next_token();
8461                                 break;
8462
8463                         case T_asm:
8464                                 parse_global_asm();
8465                                 break;
8466
8467                         default:
8468                                 parse_external_declaration();
8469                                 break;
8470                 }
8471         }
8472 }
8473
8474 /**
8475  * Parse the input.
8476  *
8477  * @return  the translation unit or NULL if errors occurred.
8478  */
8479 void start_parsing(void)
8480 {
8481         environment_stack = NEW_ARR_F(stack_entry_t, 0);
8482         label_stack       = NEW_ARR_F(stack_entry_t, 0);
8483         diagnostic_count  = 0;
8484         error_count       = 0;
8485         warning_count     = 0;
8486
8487         type_set_output(stderr);
8488         ast_set_output(stderr);
8489
8490         assert(unit == NULL);
8491         unit = allocate_ast_zero(sizeof(unit[0]));
8492
8493         assert(global_scope == NULL);
8494         global_scope = &unit->scope;
8495
8496         assert(scope == NULL);
8497         set_scope(&unit->scope);
8498
8499         initialize_builtin_types();
8500 }
8501
8502 translation_unit_t *finish_parsing(void)
8503 {
8504         assert(scope == &unit->scope);
8505         scope          = NULL;
8506         last_declaration = NULL;
8507
8508         assert(global_scope == &unit->scope);
8509         check_unused_globals();
8510         global_scope = NULL;
8511
8512         DEL_ARR_F(environment_stack);
8513         DEL_ARR_F(label_stack);
8514
8515         translation_unit_t *result = unit;
8516         unit = NULL;
8517         return result;
8518 }
8519
8520 void parse(void)
8521 {
8522         lookahead_bufpos = 0;
8523         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8524                 next_token();
8525         }
8526         parse_translation_unit();
8527 }
8528
8529 /**
8530  * Initialize the parser.
8531  */
8532 void init_parser(void)
8533 {
8534         if (c_mode & _MS) {
8535                 /* add predefined symbols for extended-decl-modifier */
8536                 sym_align      = symbol_table_insert("align");
8537                 sym_allocate   = symbol_table_insert("allocate");
8538                 sym_dllimport  = symbol_table_insert("dllimport");
8539                 sym_dllexport  = symbol_table_insert("dllexport");
8540                 sym_naked      = symbol_table_insert("naked");
8541                 sym_noinline   = symbol_table_insert("noinline");
8542                 sym_noreturn   = symbol_table_insert("noreturn");
8543                 sym_nothrow    = symbol_table_insert("nothrow");
8544                 sym_novtable   = symbol_table_insert("novtable");
8545                 sym_property   = symbol_table_insert("property");
8546                 sym_get        = symbol_table_insert("get");
8547                 sym_put        = symbol_table_insert("put");
8548                 sym_selectany  = symbol_table_insert("selectany");
8549                 sym_thread     = symbol_table_insert("thread");
8550                 sym_uuid       = symbol_table_insert("uuid");
8551                 sym_deprecated = symbol_table_insert("deprecated");
8552                 sym_restrict   = symbol_table_insert("restrict");
8553                 sym_noalias    = symbol_table_insert("noalias");
8554         }
8555         memset(token_anchor_set, 0, sizeof(token_anchor_set));
8556
8557         init_expression_parsers();
8558         obstack_init(&temp_obst);
8559
8560         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8561         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8562 }
8563
8564 /**
8565  * Terminate the parser.
8566  */
8567 void exit_parser(void)
8568 {
8569         obstack_free(&temp_obst, NULL);
8570 }