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