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