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