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