Behave more sane (i.e. do not spew implicit int warnings), when encountering garbage...
[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
2343                         /* reset path to toplevel, evaluate designator from there */
2344                         ascend_to(path, top_path_level);
2345                         if (!walk_designator(path, designator, false)) {
2346                                 /* can't continue after designation error */
2347                                 goto end_error;
2348                         }
2349
2350                         initializer_t *designator_initializer
2351                                 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2352                         designator_initializer->designator.designator = designator;
2353                         ARR_APP1(initializer_t*, initializers, designator_initializer);
2354
2355                         orig_type = path->top_type;
2356                         type      = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2357                 }
2358
2359                 initializer_t *sub;
2360
2361                 if (token.type == '{') {
2362                         if (type != NULL && is_type_scalar(type)) {
2363                                 sub = parse_scalar_initializer(type, env->must_be_constant);
2364                         } else {
2365                                 eat('{');
2366                                 if (type == NULL) {
2367                                         if (env->declaration != NULL) {
2368                                                 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2369                                                        env->declaration->symbol);
2370                                         } else {
2371                                                 errorf(HERE, "extra brace group at end of initializer");
2372                                         }
2373                                 } else
2374                                         descend_into_subtype(path);
2375
2376                                 add_anchor_token('}');
2377                                 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2378                                                             env);
2379                                 rem_anchor_token('}');
2380
2381                                 if (type != NULL) {
2382                                         ascend_from_subtype(path);
2383                                         expect('}');
2384                                 } else {
2385                                         expect('}');
2386                                         goto error_parse_next;
2387                                 }
2388                         }
2389                 } else {
2390                         /* must be an expression */
2391                         expression_t *expression = parse_assignment_expression();
2392
2393                         if (env->must_be_constant && !is_initializer_constant(expression)) {
2394                                 errorf(&expression->base.source_position,
2395                                        "Initialisation expression '%E' is not constant\n",
2396                                        expression);
2397                         }
2398
2399                         if (type == NULL) {
2400                                 /* we are already outside, ... */
2401                                 goto error_excess;
2402                         }
2403
2404                         /* handle { "string" } special case */
2405                         if ((expression->kind == EXPR_STRING_LITERAL
2406                                         || expression->kind == EXPR_WIDE_STRING_LITERAL)
2407                                         && outer_type != NULL) {
2408                                 sub = initializer_from_expression(outer_type, expression);
2409                                 if (sub != NULL) {
2410                                         if (token.type == ',') {
2411                                                 next_token();
2412                                         }
2413                                         if (token.type != '}') {
2414                                                 warningf(HERE, "excessive elements in initializer for type '%T'",
2415                                                                  orig_type);
2416                                         }
2417                                         /* TODO: eat , ... */
2418                                         return sub;
2419                                 }
2420                         }
2421
2422                         /* descend into subtypes until expression matches type */
2423                         while (true) {
2424                                 orig_type = path->top_type;
2425                                 type      = skip_typeref(orig_type);
2426
2427                                 sub = initializer_from_expression(orig_type, expression);
2428                                 if (sub != NULL) {
2429                                         break;
2430                                 }
2431                                 if (!is_type_valid(type)) {
2432                                         goto end_error;
2433                                 }
2434                                 if (is_type_scalar(type)) {
2435                                         errorf(&expression->base.source_position,
2436                                                         "expression '%E' doesn't match expected type '%T'",
2437                                                         expression, orig_type);
2438                                         goto end_error;
2439                                 }
2440
2441                                 descend_into_subtype(path);
2442                         }
2443                 }
2444
2445                 /* update largest index of top array */
2446                 const type_path_entry_t *first      = &path->path[0];
2447                 type_t                  *first_type = first->type;
2448                 first_type                          = skip_typeref(first_type);
2449                 if (is_type_array(first_type)) {
2450                         size_t index = first->v.index;
2451                         if (index > path->max_index)
2452                                 path->max_index = index;
2453                 }
2454
2455                 if (type != NULL) {
2456                         /* append to initializers list */
2457                         ARR_APP1(initializer_t*, initializers, sub);
2458                 } else {
2459 error_excess:
2460                         if (env->declaration != NULL)
2461                                 warningf(HERE, "excess elements in struct initializer for '%Y'",
2462                                  env->declaration->symbol);
2463                         else
2464                                 warningf(HERE, "excess elements in struct initializer");
2465                 }
2466
2467 error_parse_next:
2468                 if (token.type == '}') {
2469                         break;
2470                 }
2471                 expect(',');
2472                 if (token.type == '}') {
2473                         break;
2474                 }
2475
2476                 if (type != NULL) {
2477                         /* advance to the next declaration if we are not at the end */
2478                         advance_current_object(path, top_path_level);
2479                         orig_type = path->top_type;
2480                         if (orig_type != NULL)
2481                                 type = skip_typeref(orig_type);
2482                         else
2483                                 type = NULL;
2484                 }
2485         }
2486
2487         size_t len  = ARR_LEN(initializers);
2488         size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2489         initializer_t *result = allocate_ast_zero(size);
2490         result->kind          = INITIALIZER_LIST;
2491         result->list.len      = len;
2492         memcpy(&result->list.initializers, initializers,
2493                len * sizeof(initializers[0]));
2494
2495         DEL_ARR_F(initializers);
2496         ascend_to(path, top_path_level+1);
2497
2498         return result;
2499
2500 end_error:
2501         skip_initializers();
2502         DEL_ARR_F(initializers);
2503         ascend_to(path, top_path_level+1);
2504         return NULL;
2505 }
2506
2507 /**
2508  * Parses an initializer. Parsers either a compound literal
2509  * (env->declaration == NULL) or an initializer of a declaration.
2510  */
2511 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2512 {
2513         type_t        *type   = skip_typeref(env->type);
2514         initializer_t *result = NULL;
2515         size_t         max_index;
2516
2517         if (is_type_scalar(type)) {
2518                 result = parse_scalar_initializer(type, env->must_be_constant);
2519         } else if (token.type == '{') {
2520                 eat('{');
2521
2522                 type_path_t path;
2523                 memset(&path, 0, sizeof(path));
2524                 path.top_type = env->type;
2525                 path.path     = NEW_ARR_F(type_path_entry_t, 0);
2526
2527                 descend_into_subtype(&path);
2528
2529                 add_anchor_token('}');
2530                 result = parse_sub_initializer(&path, env->type, 1, env);
2531                 rem_anchor_token('}');
2532
2533                 max_index = path.max_index;
2534                 DEL_ARR_F(path.path);
2535
2536                 expect('}');
2537         } else {
2538                 /* parse_scalar_initializer() also works in this case: we simply
2539                  * have an expression without {} around it */
2540                 result = parse_scalar_initializer(type, env->must_be_constant);
2541         }
2542
2543         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
2544          * the array type size */
2545         if (is_type_array(type) && type->array.size_expression == NULL
2546                         && result != NULL) {
2547                 size_t size;
2548                 switch (result->kind) {
2549                 case INITIALIZER_LIST:
2550                         size = max_index + 1;
2551                         break;
2552
2553                 case INITIALIZER_STRING:
2554                         size = result->string.string.size;
2555                         break;
2556
2557                 case INITIALIZER_WIDE_STRING:
2558                         size = result->wide_string.string.size;
2559                         break;
2560
2561                 case INITIALIZER_DESIGNATOR:
2562                 case INITIALIZER_VALUE:
2563                         /* can happen for parse errors */
2564                         size = 0;
2565                         break;
2566
2567                 default:
2568                         internal_errorf(HERE, "invalid initializer type");
2569                 }
2570
2571                 expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2572                 cnst->base.type          = type_size_t;
2573                 cnst->conste.v.int_value = size;
2574
2575                 type_t *new_type = duplicate_type(type);
2576
2577                 new_type->array.size_expression = cnst;
2578                 new_type->array.size_constant   = true;
2579                 new_type->array.size            = size;
2580                 env->type = new_type;
2581         }
2582
2583         return result;
2584 end_error:
2585         return NULL;
2586 }
2587
2588 static declaration_t *append_declaration(declaration_t *declaration);
2589
2590 static declaration_t *parse_compound_type_specifier(bool is_struct)
2591 {
2592         gnu_attribute_t  *attributes = NULL;
2593         decl_modifiers_t  modifiers  = 0;
2594         if (is_struct) {
2595                 eat(T_struct);
2596         } else {
2597                 eat(T_union);
2598         }
2599
2600         symbol_t      *symbol      = NULL;
2601         declaration_t *declaration = NULL;
2602
2603         if (token.type == T___attribute__) {
2604                 modifiers |= parse_attributes(&attributes);
2605         }
2606
2607         if (token.type == T_IDENTIFIER) {
2608                 symbol = token.v.symbol;
2609                 next_token();
2610
2611                 namespace_t const namespc =
2612                         is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2613                 declaration = get_declaration(symbol, namespc);
2614                 if (declaration != NULL) {
2615                         if (declaration->parent_scope != scope &&
2616                             (token.type == '{' || token.type == ';')) {
2617                                 declaration = NULL;
2618                         } else if (declaration->init.complete &&
2619                                    token.type == '{') {
2620                                 assert(symbol != NULL);
2621                                 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2622                                        is_struct ? "struct" : "union", symbol,
2623                                        &declaration->source_position);
2624                                 declaration->scope.declarations = NULL;
2625                         }
2626                 }
2627         } else if (token.type != '{') {
2628                 if (is_struct) {
2629                         parse_error_expected("while parsing struct type specifier",
2630                                              T_IDENTIFIER, '{', NULL);
2631                 } else {
2632                         parse_error_expected("while parsing union type specifier",
2633                                              T_IDENTIFIER, '{', NULL);
2634                 }
2635
2636                 return NULL;
2637         }
2638
2639         if (declaration == NULL) {
2640                 declaration = allocate_declaration_zero();
2641                 declaration->namespc         =
2642                         (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2643                 declaration->source_position = token.source_position;
2644                 declaration->symbol          = symbol;
2645                 declaration->parent_scope    = scope;
2646                 if (symbol != NULL) {
2647                         environment_push(declaration);
2648                 }
2649                 append_declaration(declaration);
2650         }
2651
2652         if (token.type == '{') {
2653                 declaration->init.complete = true;
2654
2655                 parse_compound_type_entries(declaration);
2656                 modifiers |= parse_attributes(&attributes);
2657         }
2658
2659         declaration->modifiers |= modifiers;
2660         return declaration;
2661 }
2662
2663 static void parse_enum_entries(type_t *const enum_type)
2664 {
2665         eat('{');
2666
2667         if (token.type == '}') {
2668                 next_token();
2669                 errorf(HERE, "empty enum not allowed");
2670                 return;
2671         }
2672
2673         add_anchor_token('}');
2674         do {
2675                 if (token.type != T_IDENTIFIER) {
2676                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2677                         eat_block();
2678                         rem_anchor_token('}');
2679                         return;
2680                 }
2681
2682                 declaration_t *const entry = allocate_declaration_zero();
2683                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
2684                 entry->type            = enum_type;
2685                 entry->symbol          = token.v.symbol;
2686                 entry->source_position = token.source_position;
2687                 next_token();
2688
2689                 if (token.type == '=') {
2690                         next_token();
2691                         expression_t *value = parse_constant_expression();
2692
2693                         value = create_implicit_cast(value, enum_type);
2694                         entry->init.enum_value = value;
2695
2696                         /* TODO semantic */
2697                 }
2698
2699                 record_declaration(entry);
2700
2701                 if (token.type != ',')
2702                         break;
2703                 next_token();
2704         } while (token.type != '}');
2705         rem_anchor_token('}');
2706
2707         expect('}');
2708
2709 end_error:
2710         ;
2711 }
2712
2713 static type_t *parse_enum_specifier(void)
2714 {
2715         gnu_attribute_t *attributes = NULL;
2716         declaration_t   *declaration;
2717         symbol_t        *symbol;
2718
2719         eat(T_enum);
2720         if (token.type == T_IDENTIFIER) {
2721                 symbol = token.v.symbol;
2722                 next_token();
2723
2724                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2725         } else if (token.type != '{') {
2726                 parse_error_expected("while parsing enum type specifier",
2727                                      T_IDENTIFIER, '{', NULL);
2728                 return NULL;
2729         } else {
2730                 declaration = NULL;
2731                 symbol      = NULL;
2732         }
2733
2734         if (declaration == NULL) {
2735                 declaration = allocate_declaration_zero();
2736                 declaration->namespc         = NAMESPACE_ENUM;
2737                 declaration->source_position = token.source_position;
2738                 declaration->symbol          = symbol;
2739                 declaration->parent_scope  = scope;
2740         }
2741
2742         type_t *const type      = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2743         type->enumt.declaration = declaration;
2744
2745         if (token.type == '{') {
2746                 if (declaration->init.complete) {
2747                         errorf(HERE, "multiple definitions of enum %Y", symbol);
2748                 }
2749                 if (symbol != NULL) {
2750                         environment_push(declaration);
2751                 }
2752                 append_declaration(declaration);
2753                 declaration->init.complete = true;
2754
2755                 parse_enum_entries(type);
2756                 parse_attributes(&attributes);
2757         }
2758
2759         return type;
2760 }
2761
2762 /**
2763  * if a symbol is a typedef to another type, return true
2764  */
2765 static bool is_typedef_symbol(symbol_t *symbol)
2766 {
2767         const declaration_t *const declaration =
2768                 get_declaration(symbol, NAMESPACE_NORMAL);
2769         return
2770                 declaration != NULL &&
2771                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2772 }
2773
2774 static type_t *parse_typeof(void)
2775 {
2776         eat(T___typeof__);
2777
2778         type_t *type;
2779
2780         expect('(');
2781         add_anchor_token(')');
2782
2783         expression_t *expression  = NULL;
2784
2785 restart:
2786         switch(token.type) {
2787         case T___extension__:
2788                 /* This can be a prefix to a typename or an expression.  We simply eat
2789                  * it now. */
2790                 do {
2791                         next_token();
2792                 } while (token.type == T___extension__);
2793                 goto restart;
2794
2795         case T_IDENTIFIER:
2796                 if (is_typedef_symbol(token.v.symbol)) {
2797                         type = parse_typename();
2798                 } else {
2799                         expression = parse_expression();
2800                         type       = expression->base.type;
2801                 }
2802                 break;
2803
2804         TYPENAME_START
2805                 type = parse_typename();
2806                 break;
2807
2808         default:
2809                 expression = parse_expression();
2810                 type       = expression->base.type;
2811                 break;
2812         }
2813
2814         rem_anchor_token(')');
2815         expect(')');
2816
2817         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2818         typeof_type->typeoft.expression  = expression;
2819         typeof_type->typeoft.typeof_type = type;
2820
2821         return typeof_type;
2822 end_error:
2823         return NULL;
2824 }
2825
2826 typedef enum specifiers_t {
2827         SPECIFIER_SIGNED    = 1 << 0,
2828         SPECIFIER_UNSIGNED  = 1 << 1,
2829         SPECIFIER_LONG      = 1 << 2,
2830         SPECIFIER_INT       = 1 << 3,
2831         SPECIFIER_DOUBLE    = 1 << 4,
2832         SPECIFIER_CHAR      = 1 << 5,
2833         SPECIFIER_SHORT     = 1 << 6,
2834         SPECIFIER_LONG_LONG = 1 << 7,
2835         SPECIFIER_FLOAT     = 1 << 8,
2836         SPECIFIER_BOOL      = 1 << 9,
2837         SPECIFIER_VOID      = 1 << 10,
2838         SPECIFIER_INT8      = 1 << 11,
2839         SPECIFIER_INT16     = 1 << 12,
2840         SPECIFIER_INT32     = 1 << 13,
2841         SPECIFIER_INT64     = 1 << 14,
2842         SPECIFIER_INT128    = 1 << 15,
2843         SPECIFIER_COMPLEX   = 1 << 16,
2844         SPECIFIER_IMAGINARY = 1 << 17,
2845 } specifiers_t;
2846
2847 static type_t *create_builtin_type(symbol_t *const symbol,
2848                                    type_t *const real_type)
2849 {
2850         type_t *type            = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2851         type->builtin.symbol    = symbol;
2852         type->builtin.real_type = real_type;
2853
2854         type_t *result = typehash_insert(type);
2855         if (type != result) {
2856                 free_type(type);
2857         }
2858
2859         return result;
2860 }
2861
2862 static type_t *get_typedef_type(symbol_t *symbol)
2863 {
2864         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2865         if (declaration == NULL ||
2866            declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2867                 return NULL;
2868
2869         type_t *type               = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2870         type->typedeft.declaration = declaration;
2871
2872         return type;
2873 }
2874
2875 /**
2876  * check for the allowed MS alignment values.
2877  */
2878 static bool check_alignment_value(long long intvalue)
2879 {
2880         if (intvalue < 1 || intvalue > 8192) {
2881                 errorf(HERE, "illegal alignment value");
2882                 return false;
2883         }
2884         unsigned v = (unsigned)intvalue;
2885         for(unsigned i = 1; i <= 8192; i += i) {
2886                 if (i == v)
2887                         return true;
2888         }
2889         errorf(HERE, "alignment must be power of two");
2890         return false;
2891 }
2892
2893 #define DET_MOD(name, tag) do { \
2894         if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2895         *modifiers |= tag; \
2896 } while (0)
2897
2898 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2899 {
2900         decl_modifiers_t *modifiers = &specifiers->modifiers;
2901
2902         while (true) {
2903                 if (token.type == T_restrict) {
2904                         next_token();
2905                         DET_MOD(restrict, DM_RESTRICT);
2906                         goto end_loop;
2907                 } else if (token.type != T_IDENTIFIER)
2908                         break;
2909                 symbol_t *symbol = token.v.symbol;
2910                 if (symbol == sym_align) {
2911                         next_token();
2912                         expect('(');
2913                         if (token.type != T_INTEGER)
2914                                 goto end_error;
2915                         if (check_alignment_value(token.v.intvalue)) {
2916                                 if (specifiers->alignment != 0)
2917                                         warningf(HERE, "align used more than once");
2918                                 specifiers->alignment = (unsigned char)token.v.intvalue;
2919                         }
2920                         next_token();
2921                         expect(')');
2922                 } else if (symbol == sym_allocate) {
2923                         next_token();
2924                         expect('(');
2925                         if (token.type != T_IDENTIFIER)
2926                                 goto end_error;
2927                         (void)token.v.symbol;
2928                         expect(')');
2929                 } else if (symbol == sym_dllimport) {
2930                         next_token();
2931                         DET_MOD(dllimport, DM_DLLIMPORT);
2932                 } else if (symbol == sym_dllexport) {
2933                         next_token();
2934                         DET_MOD(dllexport, DM_DLLEXPORT);
2935                 } else if (symbol == sym_thread) {
2936                         next_token();
2937                         DET_MOD(thread, DM_THREAD);
2938                 } else if (symbol == sym_naked) {
2939                         next_token();
2940                         DET_MOD(naked, DM_NAKED);
2941                 } else if (symbol == sym_noinline) {
2942                         next_token();
2943                         DET_MOD(noinline, DM_NOINLINE);
2944                 } else if (symbol == sym_noreturn) {
2945                         next_token();
2946                         DET_MOD(noreturn, DM_NORETURN);
2947                 } else if (symbol == sym_nothrow) {
2948                         next_token();
2949                         DET_MOD(nothrow, DM_NOTHROW);
2950                 } else if (symbol == sym_novtable) {
2951                         next_token();
2952                         DET_MOD(novtable, DM_NOVTABLE);
2953                 } else if (symbol == sym_property) {
2954                         next_token();
2955                         expect('(');
2956                         for(;;) {
2957                                 bool is_get = false;
2958                                 if (token.type != T_IDENTIFIER)
2959                                         goto end_error;
2960                                 if (token.v.symbol == sym_get) {
2961                                         is_get = true;
2962                                 } else if (token.v.symbol == sym_put) {
2963                                 } else {
2964                                         errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2965                                         goto end_error;
2966                                 }
2967                                 next_token();
2968                                 expect('=');
2969                                 if (token.type != T_IDENTIFIER)
2970                                         goto end_error;
2971                                 if (is_get) {
2972                                         if (specifiers->get_property_sym != NULL) {
2973                                                 errorf(HERE, "get property name already specified");
2974                                         } else {
2975                                                 specifiers->get_property_sym = token.v.symbol;
2976                                         }
2977                                 } else {
2978                                         if (specifiers->put_property_sym != NULL) {
2979                                                 errorf(HERE, "put property name already specified");
2980                                         } else {
2981                                                 specifiers->put_property_sym = token.v.symbol;
2982                                         }
2983                                 }
2984                                 next_token();
2985                                 if (token.type == ',') {
2986                                         next_token();
2987                                         continue;
2988                                 }
2989                                 break;
2990                         }
2991                         expect(')');
2992                 } else if (symbol == sym_selectany) {
2993                         next_token();
2994                         DET_MOD(selectany, DM_SELECTANY);
2995                 } else if (symbol == sym_uuid) {
2996                         next_token();
2997                         expect('(');
2998                         if (token.type != T_STRING_LITERAL)
2999                                 goto end_error;
3000                         next_token();
3001                         expect(')');
3002                 } else if (symbol == sym_deprecated) {
3003                         next_token();
3004                         if (specifiers->deprecated != 0)
3005                                 warningf(HERE, "deprecated used more than once");
3006                         specifiers->deprecated = 1;
3007                         if (token.type == '(') {
3008                                 next_token();
3009                                 if (token.type == T_STRING_LITERAL) {
3010                                         specifiers->deprecated_string = token.v.string.begin;
3011                                         next_token();
3012                                 } else {
3013                                         errorf(HERE, "string literal expected");
3014                                 }
3015                                 expect(')');
3016                         }
3017                 } else if (symbol == sym_noalias) {
3018                         next_token();
3019                         DET_MOD(noalias, DM_NOALIAS);
3020                 } else {
3021                         warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3022                         next_token();
3023                         if (token.type == '(')
3024                                 skip_until(')');
3025                 }
3026 end_loop:
3027                 if (token.type == ',')
3028                         next_token();
3029         }
3030 end_error:
3031         return;
3032 }
3033
3034 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3035 {
3036         type_t            *type            = NULL;
3037         type_qualifiers_t  qualifiers      = TYPE_QUALIFIER_NONE;
3038         type_modifiers_t   modifiers       = TYPE_MODIFIER_NONE;
3039         unsigned           type_specifiers = 0;
3040         int                newtype         = 0;
3041
3042         specifiers->source_position = token.source_position;
3043
3044         while (true) {
3045                 specifiers->modifiers
3046                         |= parse_attributes(&specifiers->gnu_attributes);
3047                 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3048                         modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3049
3050                 switch(token.type) {
3051
3052                 /* storage class */
3053 #define MATCH_STORAGE_CLASS(token, class)                                  \
3054                 case token:                                                        \
3055                         if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3056                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3057                         }                                                              \
3058                         specifiers->declared_storage_class = class;                    \
3059                         next_token();                                                  \
3060                         break;
3061
3062                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
3063                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
3064                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
3065                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
3066                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3067
3068                 case T__declspec:
3069                         next_token();
3070                         expect('(');
3071                         add_anchor_token(')');
3072                         parse_microsoft_extended_decl_modifier(specifiers);
3073                         rem_anchor_token(')');
3074                         expect(')');
3075                         break;
3076
3077                 case T___thread:
3078                         switch (specifiers->declared_storage_class) {
3079                         case STORAGE_CLASS_NONE:
3080                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3081                                 break;
3082
3083                         case STORAGE_CLASS_EXTERN:
3084                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3085                                 break;
3086
3087                         case STORAGE_CLASS_STATIC:
3088                                 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3089                                 break;
3090
3091                         default:
3092                                 errorf(HERE, "multiple storage classes in declaration specifiers");
3093                                 break;
3094                         }
3095                         next_token();
3096                         break;
3097
3098                 /* type qualifiers */
3099 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
3100                 case token:                                                     \
3101                         qualifiers |= qualifier;                                    \
3102                         next_token();                                               \
3103                         break
3104
3105                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3106                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3107                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3108                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3109                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3110                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3111                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3112                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3113
3114                 case T___extension__:
3115                         /* TODO */
3116                         next_token();
3117                         break;
3118
3119                 /* type specifiers */
3120 #define MATCH_SPECIFIER(token, specifier, name)                         \
3121                 case token:                                                     \
3122                         next_token();                                               \
3123                         if (type_specifiers & specifier) {                           \
3124                                 errorf(HERE, "multiple " name " type specifiers given"); \
3125                         } else {                                                    \
3126                                 type_specifiers |= specifier;                           \
3127                         }                                                           \
3128                         break
3129
3130                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void");
3131                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char");
3132                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short");
3133                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int");
3134                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float");
3135                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double");
3136                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed");
3137                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned");
3138                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool");
3139                 MATCH_SPECIFIER(T__int8,      SPECIFIER_INT8,      "_int8");
3140                 MATCH_SPECIFIER(T__int16,     SPECIFIER_INT16,     "_int16");
3141                 MATCH_SPECIFIER(T__int32,     SPECIFIER_INT32,     "_int32");
3142                 MATCH_SPECIFIER(T__int64,     SPECIFIER_INT64,     "_int64");
3143                 MATCH_SPECIFIER(T__int128,    SPECIFIER_INT128,    "_int128");
3144                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex");
3145                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3146
3147                 case T__forceinline:
3148                         /* only in microsoft mode */
3149                         specifiers->modifiers |= DM_FORCEINLINE;
3150                         /* FALLTHROUGH */
3151
3152                 case T_inline:
3153                         next_token();
3154                         specifiers->is_inline = true;
3155                         break;
3156
3157                 case T_long:
3158                         next_token();
3159                         if (type_specifiers & SPECIFIER_LONG_LONG) {
3160                                 errorf(HERE, "multiple type specifiers given");
3161                         } else if (type_specifiers & SPECIFIER_LONG) {
3162                                 type_specifiers |= SPECIFIER_LONG_LONG;
3163                         } else {
3164                                 type_specifiers |= SPECIFIER_LONG;
3165                         }
3166                         break;
3167
3168                 case T_struct: {
3169                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3170
3171                         type->compound.declaration = parse_compound_type_specifier(true);
3172                         break;
3173                 }
3174                 case T_union: {
3175                         type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3176                         type->compound.declaration = parse_compound_type_specifier(false);
3177                         if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3178                                 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3179                         break;
3180                 }
3181                 case T_enum:
3182                         type = parse_enum_specifier();
3183                         break;
3184                 case T___typeof__:
3185                         type = parse_typeof();
3186                         break;
3187                 case T___builtin_va_list:
3188                         type = duplicate_type(type_valist);
3189                         next_token();
3190                         break;
3191
3192                 case T_IDENTIFIER: {
3193                         /* only parse identifier if we haven't found a type yet */
3194                         if (type != NULL || type_specifiers != 0)
3195                                 goto finish_specifiers;
3196
3197                         type_t *typedef_type = get_typedef_type(token.v.symbol);
3198
3199                         if (typedef_type == NULL)
3200                                 goto finish_specifiers;
3201
3202                         next_token();
3203                         type = typedef_type;
3204                         break;
3205                 }
3206
3207                 /* function specifier */
3208                 default:
3209                         goto finish_specifiers;
3210                 }
3211         }
3212
3213 finish_specifiers:
3214
3215         if (type == NULL) {
3216                 atomic_type_kind_t atomic_type;
3217
3218                 /* match valid basic types */
3219                 switch(type_specifiers) {
3220                 case SPECIFIER_VOID:
3221                         atomic_type = ATOMIC_TYPE_VOID;
3222                         break;
3223                 case SPECIFIER_CHAR:
3224                         atomic_type = ATOMIC_TYPE_CHAR;
3225                         break;
3226                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3227                         atomic_type = ATOMIC_TYPE_SCHAR;
3228                         break;
3229                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3230                         atomic_type = ATOMIC_TYPE_UCHAR;
3231                         break;
3232                 case SPECIFIER_SHORT:
3233                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3234                 case SPECIFIER_SHORT | SPECIFIER_INT:
3235                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3236                         atomic_type = ATOMIC_TYPE_SHORT;
3237                         break;
3238                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3239                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3240                         atomic_type = ATOMIC_TYPE_USHORT;
3241                         break;
3242                 case SPECIFIER_INT:
3243                 case SPECIFIER_SIGNED:
3244                 case SPECIFIER_SIGNED | SPECIFIER_INT:
3245                         atomic_type = ATOMIC_TYPE_INT;
3246                         break;
3247                 case SPECIFIER_UNSIGNED:
3248                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3249                         atomic_type = ATOMIC_TYPE_UINT;
3250                         break;
3251                 case SPECIFIER_LONG:
3252                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3253                 case SPECIFIER_LONG | SPECIFIER_INT:
3254                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3255                         atomic_type = ATOMIC_TYPE_LONG;
3256                         break;
3257                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3258                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3259                         atomic_type = ATOMIC_TYPE_ULONG;
3260                         break;
3261                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3262                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3263                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3264                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3265                         | SPECIFIER_INT:
3266                         atomic_type = ATOMIC_TYPE_LONGLONG;
3267                         break;
3268                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3269                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3270                         | SPECIFIER_INT:
3271                         atomic_type = ATOMIC_TYPE_ULONGLONG;
3272                         break;
3273
3274                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3275                         atomic_type = unsigned_int8_type_kind;
3276                         break;
3277
3278                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3279                         atomic_type = unsigned_int16_type_kind;
3280                         break;
3281
3282                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3283                         atomic_type = unsigned_int32_type_kind;
3284                         break;
3285
3286                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3287                         atomic_type = unsigned_int64_type_kind;
3288                         break;
3289
3290                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3291                         atomic_type = unsigned_int128_type_kind;
3292                         break;
3293
3294                 case SPECIFIER_INT8:
3295                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3296                         atomic_type = int8_type_kind;
3297                         break;
3298
3299                 case SPECIFIER_INT16:
3300                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3301                         atomic_type = int16_type_kind;
3302                         break;
3303
3304                 case SPECIFIER_INT32:
3305                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3306                         atomic_type = int32_type_kind;
3307                         break;
3308
3309                 case SPECIFIER_INT64:
3310                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3311                         atomic_type = int64_type_kind;
3312                         break;
3313
3314                 case SPECIFIER_INT128:
3315                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3316                         atomic_type = int128_type_kind;
3317                         break;
3318
3319                 case SPECIFIER_FLOAT:
3320                         atomic_type = ATOMIC_TYPE_FLOAT;
3321                         break;
3322                 case SPECIFIER_DOUBLE:
3323                         atomic_type = ATOMIC_TYPE_DOUBLE;
3324                         break;
3325                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3326                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3327                         break;
3328                 case SPECIFIER_BOOL:
3329                         atomic_type = ATOMIC_TYPE_BOOL;
3330                         break;
3331                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3332                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3333                         atomic_type = ATOMIC_TYPE_FLOAT;
3334                         break;
3335                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3336                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3337                         atomic_type = ATOMIC_TYPE_DOUBLE;
3338                         break;
3339                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3340                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3341                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3342                         break;
3343                 default:
3344                         /* invalid specifier combination, give an error message */
3345                         if (type_specifiers == 0) {
3346                                 if (! strict_mode) {
3347                                         if (warning.implicit_int) {
3348                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
3349                                         }
3350                                         atomic_type = ATOMIC_TYPE_INT;
3351                                         break;
3352                                 } else {
3353                                         errorf(HERE, "no type specifiers given in declaration");
3354                                 }
3355                         } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3356                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
3357                                 errorf(HERE, "signed and unsigned specifiers gives");
3358                         } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3359                                 errorf(HERE, "only integer types can be signed or unsigned");
3360                         } else {
3361                                 errorf(HERE, "multiple datatypes in declaration");
3362                         }
3363                         atomic_type = ATOMIC_TYPE_INVALID;
3364                 }
3365
3366                 if (type_specifiers & SPECIFIER_COMPLEX &&
3367                    atomic_type != ATOMIC_TYPE_INVALID) {
3368                         type                = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3369                         type->complex.akind = atomic_type;
3370                 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3371                           atomic_type != ATOMIC_TYPE_INVALID) {
3372                         type                  = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3373                         type->imaginary.akind = atomic_type;
3374                 } else {
3375                         type               = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3376                         type->atomic.akind = atomic_type;
3377                 }
3378                 newtype = 1;
3379         } else {
3380                 if (type_specifiers != 0) {
3381                         errorf(HERE, "multiple datatypes in declaration");
3382                 }
3383         }
3384
3385         /* FIXME: check type qualifiers here */
3386
3387         type->base.qualifiers = qualifiers;
3388         type->base.modifiers  = modifiers;
3389
3390         type_t *result = typehash_insert(type);
3391         if (newtype && result != type) {
3392                 free_type(type);
3393         }
3394
3395         specifiers->type = result;
3396 end_error:
3397         return;
3398 }
3399
3400 static type_qualifiers_t parse_type_qualifiers(void)
3401 {
3402         type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3403
3404         while (true) {
3405                 switch(token.type) {
3406                 /* type qualifiers */
3407                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3408                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3409                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3410                 /* microsoft extended type modifiers */
3411                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3412                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3413                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3414                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3415                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3416
3417                 default:
3418                         return qualifiers;
3419                 }
3420         }
3421 }
3422
3423 static declaration_t *parse_identifier_list(void)
3424 {
3425         declaration_t *declarations     = NULL;
3426         declaration_t *last_declaration = NULL;
3427         do {
3428                 declaration_t *const declaration = allocate_declaration_zero();
3429                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
3430                 declaration->source_position = token.source_position;
3431                 declaration->symbol          = token.v.symbol;
3432                 next_token();
3433
3434                 if (last_declaration != NULL) {
3435                         last_declaration->next = declaration;
3436                 } else {
3437                         declarations = declaration;
3438                 }
3439                 last_declaration = declaration;
3440
3441                 if (token.type != ',') {
3442                         break;
3443                 }
3444                 next_token();
3445         } while (token.type == T_IDENTIFIER);
3446
3447         return declarations;
3448 }
3449
3450 static type_t *automatic_type_conversion(type_t *orig_type);
3451
3452 static void semantic_parameter(declaration_t *declaration)
3453 {
3454         /* TODO: improve error messages */
3455
3456         if (declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3457                 errorf(HERE, "typedef not allowed in parameter list");
3458         } else if (declaration->declared_storage_class != STORAGE_CLASS_NONE
3459                         && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3460                 errorf(HERE, "parameter may only have none or register storage class");
3461         }
3462
3463         type_t *const orig_type = declaration->type;
3464         /* Â§6.7.5.3(7): Array as last part of a parameter type is just syntactic
3465          * sugar.  Turn it into a pointer.
3466          * Â§6.7.5.3(8): A declaration of a parameter as ``function returning type''
3467          * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3468          */
3469         type_t *const type = automatic_type_conversion(orig_type);
3470         declaration->type = type;
3471
3472         if (is_type_incomplete(skip_typeref(type))) {
3473                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3474                        orig_type, declaration->symbol);
3475         }
3476 }
3477
3478 static declaration_t *parse_parameter(void)
3479 {
3480         declaration_specifiers_t specifiers;
3481         memset(&specifiers, 0, sizeof(specifiers));
3482
3483         parse_declaration_specifiers(&specifiers);
3484
3485         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3486
3487         return declaration;
3488 }
3489
3490 static declaration_t *parse_parameters(function_type_t *type)
3491 {
3492         declaration_t *declarations = NULL;
3493
3494         eat('(');
3495         add_anchor_token(')');
3496         int saved_comma_state = save_and_reset_anchor_state(',');
3497
3498         if (token.type == T_IDENTIFIER) {
3499                 symbol_t *symbol = token.v.symbol;
3500                 if (!is_typedef_symbol(symbol)) {
3501                         type->kr_style_parameters = true;
3502                         declarations = parse_identifier_list();
3503                         goto parameters_finished;
3504                 }
3505         }
3506
3507         if (token.type == ')') {
3508                 type->unspecified_parameters = 1;
3509                 goto parameters_finished;
3510         }
3511
3512         declaration_t        *declaration;
3513         declaration_t        *last_declaration = NULL;
3514         function_parameter_t *parameter;
3515         function_parameter_t *last_parameter = NULL;
3516
3517         while (true) {
3518                 switch(token.type) {
3519                 case T_DOTDOTDOT:
3520                         next_token();
3521                         type->variadic = 1;
3522                         goto parameters_finished;
3523
3524                 case T_IDENTIFIER:
3525                 case T___extension__:
3526                 DECLARATION_START
3527                         declaration = parse_parameter();
3528
3529                         /* func(void) is not a parameter */
3530                         if (last_parameter == NULL
3531                                         && token.type == ')'
3532                                         && declaration->symbol == NULL
3533                                         && skip_typeref(declaration->type) == type_void) {
3534                                 goto parameters_finished;
3535                         }
3536                         semantic_parameter(declaration);
3537
3538                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
3539                         memset(parameter, 0, sizeof(parameter[0]));
3540                         parameter->type = declaration->type;
3541
3542                         if (last_parameter != NULL) {
3543                                 last_declaration->next = declaration;
3544                                 last_parameter->next   = parameter;
3545                         } else {
3546                                 type->parameters = parameter;
3547                                 declarations     = declaration;
3548                         }
3549                         last_parameter   = parameter;
3550                         last_declaration = declaration;
3551                         break;
3552
3553                 default:
3554                         goto parameters_finished;
3555                 }
3556                 if (token.type != ',') {
3557                         goto parameters_finished;
3558                 }
3559                 next_token();
3560         }
3561
3562
3563 parameters_finished:
3564         rem_anchor_token(')');
3565         expect(')');
3566
3567         restore_anchor_state(',', saved_comma_state);
3568         return declarations;
3569
3570 end_error:
3571         restore_anchor_state(',', saved_comma_state);
3572         return NULL;
3573 }
3574
3575 typedef enum construct_type_kind_t {
3576         CONSTRUCT_INVALID,
3577         CONSTRUCT_POINTER,
3578         CONSTRUCT_FUNCTION,
3579         CONSTRUCT_ARRAY
3580 } construct_type_kind_t;
3581
3582 typedef struct construct_type_t construct_type_t;
3583 struct construct_type_t {
3584         construct_type_kind_t  kind;
3585         construct_type_t      *next;
3586 };
3587
3588 typedef struct parsed_pointer_t parsed_pointer_t;
3589 struct parsed_pointer_t {
3590         construct_type_t  construct_type;
3591         type_qualifiers_t type_qualifiers;
3592 };
3593
3594 typedef struct construct_function_type_t construct_function_type_t;
3595 struct construct_function_type_t {
3596         construct_type_t  construct_type;
3597         type_t           *function_type;
3598 };
3599
3600 typedef struct parsed_array_t parsed_array_t;
3601 struct parsed_array_t {
3602         construct_type_t  construct_type;
3603         type_qualifiers_t type_qualifiers;
3604         bool              is_static;
3605         bool              is_variable;
3606         expression_t     *size;
3607 };
3608
3609 typedef struct construct_base_type_t construct_base_type_t;
3610 struct construct_base_type_t {
3611         construct_type_t  construct_type;
3612         type_t           *type;
3613 };
3614
3615 static construct_type_t *parse_pointer_declarator(void)
3616 {
3617         eat('*');
3618
3619         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3620         memset(pointer, 0, sizeof(pointer[0]));
3621         pointer->construct_type.kind = CONSTRUCT_POINTER;
3622         pointer->type_qualifiers     = parse_type_qualifiers();
3623
3624         return (construct_type_t*) pointer;
3625 }
3626
3627 static construct_type_t *parse_array_declarator(void)
3628 {
3629         eat('[');
3630         add_anchor_token(']');
3631
3632         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3633         memset(array, 0, sizeof(array[0]));
3634         array->construct_type.kind = CONSTRUCT_ARRAY;
3635
3636         if (token.type == T_static) {
3637                 array->is_static = true;
3638                 next_token();
3639         }
3640
3641         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3642         if (type_qualifiers != 0) {
3643                 if (token.type == T_static) {
3644                         array->is_static = true;
3645                         next_token();
3646                 }
3647         }
3648         array->type_qualifiers = type_qualifiers;
3649
3650         if (token.type == '*' && look_ahead(1)->type == ']') {
3651                 array->is_variable = true;
3652                 next_token();
3653         } else if (token.type != ']') {
3654                 array->size = parse_assignment_expression();
3655         }
3656
3657         rem_anchor_token(']');
3658         expect(']');
3659
3660         return (construct_type_t*) array;
3661 end_error:
3662         return NULL;
3663 }
3664
3665 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3666 {
3667         type_t *type;
3668         if (declaration != NULL) {
3669                 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3670
3671                 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3672
3673                 if (mask & (mask-1)) {
3674                         const char *first = NULL, *second = NULL;
3675
3676                         /* more than one calling convention set */
3677                         if (declaration->modifiers & DM_CDECL) {
3678                                 if (first == NULL)       first = "cdecl";
3679                                 else if (second == NULL) second = "cdecl";
3680                         }
3681                         if (declaration->modifiers & DM_STDCALL) {
3682                                 if (first == NULL)       first = "stdcall";
3683                                 else if (second == NULL) second = "stdcall";
3684                         }
3685                         if (declaration->modifiers & DM_FASTCALL) {
3686                                 if (first == NULL)       first = "faslcall";
3687                                 else if (second == NULL) second = "fastcall";
3688                         }
3689                         if (declaration->modifiers & DM_THISCALL) {
3690                                 if (first == NULL)       first = "thiscall";
3691                                 else if (second == NULL) second = "thiscall";
3692                         }
3693                         errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3694                 }
3695
3696                 if (declaration->modifiers & DM_CDECL)
3697                         type->function.calling_convention = CC_CDECL;
3698                 else if (declaration->modifiers & DM_STDCALL)
3699                         type->function.calling_convention = CC_STDCALL;
3700                 else if (declaration->modifiers & DM_FASTCALL)
3701                         type->function.calling_convention = CC_FASTCALL;
3702                 else if (declaration->modifiers & DM_THISCALL)
3703                         type->function.calling_convention = CC_THISCALL;
3704         } else {
3705                 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3706         }
3707
3708         declaration_t *parameters = parse_parameters(&type->function);
3709         if (declaration != NULL) {
3710                 declaration->scope.declarations = parameters;
3711         }
3712
3713         construct_function_type_t *construct_function_type =
3714                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3715         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3716         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3717         construct_function_type->function_type       = type;
3718
3719         return &construct_function_type->construct_type;
3720 }
3721
3722 static void fix_declaration_type(declaration_t *declaration)
3723 {
3724         decl_modifiers_t declaration_modifiers = declaration->modifiers;
3725         type_modifiers_t type_modifiers        = declaration->type->base.modifiers;
3726
3727         if (declaration_modifiers & DM_TRANSPARENT_UNION)
3728                 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3729
3730         if (declaration->type->base.modifiers == type_modifiers)
3731                 return;
3732
3733         type_t *copy = duplicate_type(declaration->type);
3734         copy->base.modifiers = type_modifiers;
3735
3736         type_t *result = typehash_insert(copy);
3737         if (result != copy) {
3738                 obstack_free(type_obst, copy);
3739         }
3740
3741         declaration->type = result;
3742 }
3743
3744 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3745                 bool may_be_abstract)
3746 {
3747         /* construct a single linked list of construct_type_t's which describe
3748          * how to construct the final declarator type */
3749         construct_type_t *first = NULL;
3750         construct_type_t *last  = NULL;
3751         gnu_attribute_t  *attributes = NULL;
3752
3753         decl_modifiers_t modifiers = parse_attributes(&attributes);
3754
3755         /* pointers */
3756         while (token.type == '*') {
3757                 construct_type_t *type = parse_pointer_declarator();
3758
3759                 if (last == NULL) {
3760                         first = type;
3761                         last  = type;
3762                 } else {
3763                         last->next = type;
3764                         last       = type;
3765                 }
3766
3767                 /* TODO: find out if this is correct */
3768                 modifiers |= parse_attributes(&attributes);
3769         }
3770
3771         construct_type_t *inner_types = NULL;
3772
3773         switch(token.type) {
3774         case T_IDENTIFIER:
3775                 if (declaration == NULL) {
3776                         errorf(HERE, "no identifier expected in typename");
3777                 } else {
3778                         declaration->symbol          = token.v.symbol;
3779                         declaration->source_position = token.source_position;
3780                 }
3781                 next_token();
3782                 break;
3783         case '(':
3784                 next_token();
3785                 add_anchor_token(')');
3786                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3787                 rem_anchor_token(')');
3788                 expect(')');
3789                 break;
3790         default:
3791                 if (may_be_abstract)
3792                         break;
3793                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3794                 /* avoid a loop in the outermost scope, because eat_statement doesn't
3795                  * eat '}' */
3796                 if (token.type == '}' && current_function == NULL) {
3797                         next_token();
3798                 } else {
3799                         eat_statement();
3800                 }
3801                 return NULL;
3802         }
3803
3804         construct_type_t *p = last;
3805
3806         while(true) {
3807                 construct_type_t *type;
3808                 switch(token.type) {
3809                 case '(':
3810                         type = parse_function_declarator(declaration);
3811                         break;
3812                 case '[':
3813                         type = parse_array_declarator();
3814                         break;
3815                 default:
3816                         goto declarator_finished;
3817                 }
3818
3819                 /* insert in the middle of the list (behind p) */
3820                 if (p != NULL) {
3821                         type->next = p->next;
3822                         p->next    = type;
3823                 } else {
3824                         type->next = first;
3825                         first      = type;
3826                 }
3827                 if (last == p) {
3828                         last = type;
3829                 }
3830         }
3831
3832 declarator_finished:
3833         /* append inner_types at the end of the list, we don't to set last anymore
3834          * as it's not needed anymore */
3835         if (last == NULL) {
3836                 assert(first == NULL);
3837                 first = inner_types;
3838         } else {
3839                 last->next = inner_types;
3840         }
3841
3842         return first;
3843 end_error:
3844         return NULL;
3845 }
3846
3847 static void parse_declaration_attributes(declaration_t *declaration)
3848 {
3849         gnu_attribute_t  *attributes = NULL;
3850         decl_modifiers_t  modifiers  = parse_attributes(&attributes);
3851
3852         if (declaration == NULL)
3853                 return;
3854
3855         declaration->modifiers |= modifiers;
3856         /* check if we have these stupid mode attributes... */
3857         type_t *old_type = declaration->type;
3858         if (old_type == NULL)
3859                 return;
3860
3861         gnu_attribute_t *attribute = attributes;
3862         for ( ; attribute != NULL; attribute = attribute->next) {
3863                 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3864                         continue;
3865
3866                 atomic_type_kind_t  akind = attribute->u.akind;
3867                 if (!is_type_signed(old_type)) {
3868                         switch(akind) {
3869                         case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3870                         case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3871                         case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3872                         case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3873                         default:
3874                                 panic("invalid akind in mode attribute");
3875                         }
3876                 }
3877                 declaration->type
3878                         = make_atomic_type(akind, old_type->base.qualifiers);
3879         }
3880 }
3881
3882 static type_t *construct_declarator_type(construct_type_t *construct_list,
3883                                          type_t *type)
3884 {
3885         construct_type_t *iter = construct_list;
3886         for( ; iter != NULL; iter = iter->next) {
3887                 switch(iter->kind) {
3888                 case CONSTRUCT_INVALID:
3889                         internal_errorf(HERE, "invalid type construction found");
3890                 case CONSTRUCT_FUNCTION: {
3891                         construct_function_type_t *construct_function_type
3892                                 = (construct_function_type_t*) iter;
3893
3894                         type_t *function_type = construct_function_type->function_type;
3895
3896                         function_type->function.return_type = type;
3897
3898                         type_t *skipped_return_type = skip_typeref(type);
3899                         if (is_type_function(skipped_return_type)) {
3900                                 errorf(HERE, "function returning function is not allowed");
3901                                 type = type_error_type;
3902                         } else if (is_type_array(skipped_return_type)) {
3903                                 errorf(HERE, "function returning array is not allowed");
3904                                 type = type_error_type;
3905                         } else {
3906                                 type = function_type;
3907                         }
3908                         break;
3909                 }
3910
3911                 case CONSTRUCT_POINTER: {
3912                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3913                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, &null_position);
3914                         pointer_type->pointer.points_to  = type;
3915                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
3916
3917                         type = pointer_type;
3918                         break;
3919                 }
3920
3921                 case CONSTRUCT_ARRAY: {
3922                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
3923                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, &null_position);
3924
3925                         expression_t *size_expression = parsed_array->size;
3926                         if (size_expression != NULL) {
3927                                 size_expression
3928                                         = create_implicit_cast(size_expression, type_size_t);
3929                         }
3930
3931                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
3932                         array_type->array.element_type    = type;
3933                         array_type->array.is_static       = parsed_array->is_static;
3934                         array_type->array.is_variable     = parsed_array->is_variable;
3935                         array_type->array.size_expression = size_expression;
3936
3937                         if (size_expression != NULL) {
3938                                 if (is_constant_expression(size_expression)) {
3939                                         array_type->array.size_constant = true;
3940                                         array_type->array.size
3941                                                 = fold_constant(size_expression);
3942                                 } else {
3943                                         array_type->array.is_vla = true;
3944                                 }
3945                         }
3946
3947                         type_t *skipped_type = skip_typeref(type);
3948                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3949                                 errorf(HERE, "array of void is not allowed");
3950                                 type = type_error_type;
3951                         } else {
3952                                 type = array_type;
3953                         }
3954                         break;
3955                 }
3956                 }
3957
3958                 type_t *hashed_type = typehash_insert(type);
3959                 if (hashed_type != type) {
3960                         /* the function type was constructed earlier freeing it here will
3961                          * destroy other types... */
3962                         if (iter->kind != CONSTRUCT_FUNCTION) {
3963                                 free_type(type);
3964                         }
3965                         type = hashed_type;
3966                 }
3967         }
3968
3969         return type;
3970 }
3971
3972 static declaration_t *parse_declarator(
3973                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3974 {
3975         declaration_t *const declaration    = allocate_declaration_zero();
3976         declaration->declared_storage_class = specifiers->declared_storage_class;
3977         declaration->modifiers              = specifiers->modifiers;
3978         declaration->deprecated             = specifiers->deprecated;
3979         declaration->deprecated_string      = specifiers->deprecated_string;
3980         declaration->get_property_sym       = specifiers->get_property_sym;
3981         declaration->put_property_sym       = specifiers->put_property_sym;
3982         declaration->is_inline              = specifiers->is_inline;
3983
3984         declaration->storage_class          = specifiers->declared_storage_class;
3985         if (declaration->storage_class == STORAGE_CLASS_NONE
3986                         && scope != global_scope) {
3987                 declaration->storage_class = STORAGE_CLASS_AUTO;
3988         }
3989
3990         if (specifiers->alignment != 0) {
3991                 /* TODO: add checks here */
3992                 declaration->alignment = specifiers->alignment;
3993         }
3994
3995         construct_type_t *construct_type
3996                 = parse_inner_declarator(declaration, may_be_abstract);
3997         type_t *const type = specifiers->type;
3998         declaration->type = construct_declarator_type(construct_type, type);
3999
4000         parse_declaration_attributes(declaration);
4001
4002         fix_declaration_type(declaration);
4003
4004         if (construct_type != NULL) {
4005                 obstack_free(&temp_obst, construct_type);
4006         }
4007
4008         return declaration;
4009 }
4010
4011 static type_t *parse_abstract_declarator(type_t *base_type)
4012 {
4013         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4014
4015         type_t *result = construct_declarator_type(construct_type, base_type);
4016         if (construct_type != NULL) {
4017                 obstack_free(&temp_obst, construct_type);
4018         }
4019
4020         return result;
4021 }
4022
4023 static declaration_t *append_declaration(declaration_t* const declaration)
4024 {
4025         if (last_declaration != NULL) {
4026                 last_declaration->next = declaration;
4027         } else {
4028                 scope->declarations = declaration;
4029         }
4030         last_declaration = declaration;
4031         return declaration;
4032 }
4033
4034 /**
4035  * Check if the declaration of main is suspicious.  main should be a
4036  * function with external linkage, returning int, taking either zero
4037  * arguments, two, or three arguments of appropriate types, ie.
4038  *
4039  * int main([ int argc, char **argv [, char **env ] ]).
4040  *
4041  * @param decl    the declaration to check
4042  * @param type    the function type of the declaration
4043  */
4044 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4045 {
4046         if (decl->storage_class == STORAGE_CLASS_STATIC) {
4047                 warningf(&decl->source_position,
4048                          "'main' is normally a non-static function");
4049         }
4050         if (skip_typeref(func_type->return_type) != type_int) {
4051                 warningf(&decl->source_position,
4052                          "return type of 'main' should be 'int', but is '%T'",
4053                          func_type->return_type);
4054         }
4055         const function_parameter_t *parm = func_type->parameters;
4056         if (parm != NULL) {
4057                 type_t *const first_type = parm->type;
4058                 if (!types_compatible(skip_typeref(first_type), type_int)) {
4059                         warningf(&decl->source_position,
4060                                  "first argument of 'main' should be 'int', but is '%T'", first_type);
4061                 }
4062                 parm = parm->next;
4063                 if (parm != NULL) {
4064                         type_t *const second_type = parm->type;
4065                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4066                                 warningf(&decl->source_position,
4067                                          "second argument of 'main' should be 'char**', but is '%T'", second_type);
4068                         }
4069                         parm = parm->next;
4070                         if (parm != NULL) {
4071                                 type_t *const third_type = parm->type;
4072                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4073                                         warningf(&decl->source_position,
4074                                                  "third argument of 'main' should be 'char**', but is '%T'", third_type);
4075                                 }
4076                                 parm = parm->next;
4077                                 if (parm != NULL)
4078                                         goto warn_arg_count;
4079                         }
4080                 } else {
4081 warn_arg_count:
4082                         warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4083                 }
4084         }
4085 }
4086
4087 /**
4088  * Check if a symbol is the equal to "main".
4089  */
4090 static bool is_sym_main(const symbol_t *const sym)
4091 {
4092         return strcmp(sym->string, "main") == 0;
4093 }
4094
4095 static declaration_t *internal_record_declaration(
4096         declaration_t *const declaration,
4097         const bool is_definition)
4098 {
4099         const symbol_t *const symbol  = declaration->symbol;
4100         const namespace_t     namespc = (namespace_t)declaration->namespc;
4101
4102         assert(declaration->symbol != NULL);
4103         declaration_t *previous_declaration = get_declaration(symbol, namespc);
4104
4105         type_t *const orig_type = declaration->type;
4106         type_t *const type      = skip_typeref(orig_type);
4107         if (is_type_function(type) &&
4108                         type->function.unspecified_parameters &&
4109                         warning.strict_prototypes &&
4110                         previous_declaration == NULL) {
4111                 warningf(&declaration->source_position,
4112                          "function declaration '%#T' is not a prototype",
4113                          orig_type, declaration->symbol);
4114         }
4115
4116         if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4117                 check_type_of_main(declaration, &type->function);
4118         }
4119
4120         assert(declaration != previous_declaration);
4121         if (previous_declaration != NULL
4122                         && previous_declaration->parent_scope == scope) {
4123                 /* can happen for K&R style declarations */
4124                 if (previous_declaration->type == NULL) {
4125                         previous_declaration->type = declaration->type;
4126                 }
4127
4128                 const type_t *prev_type = skip_typeref(previous_declaration->type);
4129                 if (!types_compatible(type, prev_type)) {
4130                         errorf(&declaration->source_position,
4131                                    "declaration '%#T' is incompatible with '%#T' (declared %P)",
4132                                    orig_type, symbol, previous_declaration->type, symbol,
4133                                    &previous_declaration->source_position);
4134                 } else {
4135                         unsigned old_storage_class = previous_declaration->storage_class;
4136                         if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4137                                 errorf(&declaration->source_position,
4138                                            "redeclaration of enum entry '%Y' (declared %P)",
4139                                            symbol, &previous_declaration->source_position);
4140                                 return previous_declaration;
4141                         }
4142
4143                         if (warning.redundant_decls                                     &&
4144                             is_definition                                               &&
4145                             previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4146                             !(previous_declaration->modifiers & DM_USED)                &&
4147                             !previous_declaration->used) {
4148                                 warningf(&previous_declaration->source_position,
4149                                          "unnecessary static forward declaration for '%#T'",
4150                                          previous_declaration->type, symbol);
4151                         }
4152
4153                         unsigned new_storage_class = declaration->storage_class;
4154
4155                         if (is_type_incomplete(prev_type)) {
4156                                 previous_declaration->type = type;
4157                                 prev_type                  = type;
4158                         }
4159
4160                         /* pretend no storage class means extern for function
4161                          * declarations (except if the previous declaration is neither
4162                          * none nor extern) */
4163                         if (is_type_function(type)) {
4164                                 if (prev_type->function.unspecified_parameters) {
4165                                         previous_declaration->type = type;
4166                                         prev_type                  = type;
4167                                 }
4168
4169                                 switch (old_storage_class) {
4170                                 case STORAGE_CLASS_NONE:
4171                                         old_storage_class = STORAGE_CLASS_EXTERN;
4172                                         /* FALLTHROUGH */
4173
4174                                 case STORAGE_CLASS_EXTERN:
4175                                         if (is_definition) {
4176                                                 if (warning.missing_prototypes &&
4177                                                     prev_type->function.unspecified_parameters &&
4178                                                     !is_sym_main(symbol)) {
4179                                                         warningf(&declaration->source_position,
4180                                                                          "no previous prototype for '%#T'",
4181                                                                          orig_type, symbol);
4182                                                 }
4183                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
4184                                                 new_storage_class = STORAGE_CLASS_EXTERN;
4185                                         }
4186                                         break;
4187
4188                                 default:
4189                                         break;
4190                                 }
4191                         }
4192
4193                         if (old_storage_class == STORAGE_CLASS_EXTERN &&
4194                                         new_storage_class == STORAGE_CLASS_EXTERN) {
4195 warn_redundant_declaration:
4196                                 if (!is_definition          &&
4197                                     warning.redundant_decls &&
4198                                     strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4199                                         warningf(&declaration->source_position,
4200                                                  "redundant declaration for '%Y' (declared %P)",
4201                                                  symbol, &previous_declaration->source_position);
4202                                 }
4203                         } else if (current_function == NULL) {
4204                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
4205                                     new_storage_class == STORAGE_CLASS_STATIC) {
4206                                         errorf(&declaration->source_position,
4207                                                "static declaration of '%Y' follows non-static declaration (declared %P)",
4208                                                symbol, &previous_declaration->source_position);
4209                                 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4210                                         previous_declaration->storage_class          = STORAGE_CLASS_NONE;
4211                                         previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4212                                 } else {
4213                                         goto warn_redundant_declaration;
4214                                 }
4215                         } else if (old_storage_class == new_storage_class) {
4216                                 errorf(&declaration->source_position,
4217                                        "redeclaration of '%Y' (declared %P)",
4218                                        symbol, &previous_declaration->source_position);
4219                         } else {
4220                                 errorf(&declaration->source_position,
4221                                        "redeclaration of '%Y' with different linkage (declared %P)",
4222                                        symbol, &previous_declaration->source_position);
4223                         }
4224                 }
4225
4226                 if (declaration->is_inline)
4227                         previous_declaration->is_inline = true;
4228                 return previous_declaration;
4229         } else if (is_type_function(type)) {
4230                 if (is_definition &&
4231                     declaration->storage_class != STORAGE_CLASS_STATIC) {
4232                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
4233                                 warningf(&declaration->source_position,
4234                                          "no previous prototype for '%#T'", orig_type, symbol);
4235                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4236                                 warningf(&declaration->source_position,
4237                                          "no previous declaration for '%#T'", orig_type,
4238                                          symbol);
4239                         }
4240                 }
4241         } else {
4242                 if (warning.missing_declarations &&
4243                     scope == global_scope && (
4244                       declaration->storage_class == STORAGE_CLASS_NONE ||
4245                       declaration->storage_class == STORAGE_CLASS_THREAD
4246                     )) {
4247                         warningf(&declaration->source_position,
4248                                  "no previous declaration for '%#T'", orig_type, symbol);
4249                 }
4250         }
4251
4252         assert(declaration->parent_scope == NULL);
4253         assert(scope != NULL);
4254
4255         declaration->parent_scope = scope;
4256
4257         environment_push(declaration);
4258         return append_declaration(declaration);
4259 }
4260
4261 static declaration_t *record_declaration(declaration_t *declaration)
4262 {
4263         return internal_record_declaration(declaration, false);
4264 }
4265
4266 static declaration_t *record_definition(declaration_t *declaration)
4267 {
4268         return internal_record_declaration(declaration, true);
4269 }
4270
4271 static void parser_error_multiple_definition(declaration_t *declaration,
4272                 const source_position_t *source_position)
4273 {
4274         errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4275                declaration->symbol, &declaration->source_position);
4276 }
4277
4278 static bool is_declaration_specifier(const token_t *token,
4279                                      bool only_specifiers_qualifiers)
4280 {
4281         switch(token->type) {
4282                 TYPE_SPECIFIERS
4283                 TYPE_QUALIFIERS
4284                         return true;
4285                 case T_IDENTIFIER:
4286                         return is_typedef_symbol(token->v.symbol);
4287
4288                 case T___extension__:
4289                 STORAGE_CLASSES
4290                         return !only_specifiers_qualifiers;
4291
4292                 default:
4293                         return false;
4294         }
4295 }
4296
4297 static void parse_init_declarator_rest(declaration_t *declaration)
4298 {
4299         eat('=');
4300
4301         type_t *orig_type = declaration->type;
4302         type_t *type      = skip_typeref(orig_type);
4303
4304         if (declaration->init.initializer != NULL) {
4305                 parser_error_multiple_definition(declaration, HERE);
4306         }
4307
4308         bool must_be_constant = false;
4309         if (declaration->storage_class == STORAGE_CLASS_STATIC
4310                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4311                         || declaration->parent_scope == global_scope) {
4312                 must_be_constant = true;
4313         }
4314
4315         parse_initializer_env_t env;
4316         env.type             = orig_type;
4317         env.must_be_constant = must_be_constant;
4318         env.declaration      = declaration;
4319
4320         initializer_t *initializer = parse_initializer(&env);
4321
4322         if (env.type != orig_type) {
4323                 orig_type         = env.type;
4324                 type              = skip_typeref(orig_type);
4325                 declaration->type = env.type;
4326         }
4327
4328         if (is_type_function(type)) {
4329                 errorf(&declaration->source_position,
4330                        "initializers not allowed for function types at declator '%Y' (type '%T')",
4331                        declaration->symbol, orig_type);
4332         } else {
4333                 declaration->init.initializer = initializer;
4334         }
4335 }
4336
4337 /* parse rest of a declaration without any declarator */
4338 static void parse_anonymous_declaration_rest(
4339                 const declaration_specifiers_t *specifiers,
4340                 parsed_declaration_func finished_declaration)
4341 {
4342         eat(';');
4343
4344         declaration_t *const declaration    = allocate_declaration_zero();
4345         declaration->type                   = specifiers->type;
4346         declaration->declared_storage_class = specifiers->declared_storage_class;
4347         declaration->source_position        = specifiers->source_position;
4348         declaration->modifiers              = specifiers->modifiers;
4349
4350         if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4351                 warningf(&declaration->source_position,
4352                          "useless storage class in empty declaration");
4353         }
4354         declaration->storage_class = STORAGE_CLASS_NONE;
4355
4356         type_t *type = declaration->type;
4357         switch (type->kind) {
4358                 case TYPE_COMPOUND_STRUCT:
4359                 case TYPE_COMPOUND_UNION: {
4360                         if (type->compound.declaration->symbol == NULL) {
4361                                 warningf(&declaration->source_position,
4362                                          "unnamed struct/union that defines no instances");
4363                         }
4364                         break;
4365                 }
4366
4367                 case TYPE_ENUM:
4368                         break;
4369
4370                 default:
4371                         warningf(&declaration->source_position, "empty declaration");
4372                         break;
4373         }
4374
4375         finished_declaration(declaration);
4376 }
4377
4378 static void parse_declaration_rest(declaration_t *ndeclaration,
4379                 const declaration_specifiers_t *specifiers,
4380                 parsed_declaration_func finished_declaration)
4381 {
4382         add_anchor_token(';');
4383         add_anchor_token('=');
4384         add_anchor_token(',');
4385         while(true) {
4386                 declaration_t *declaration = finished_declaration(ndeclaration);
4387
4388                 type_t *orig_type = declaration->type;
4389                 type_t *type      = skip_typeref(orig_type);
4390
4391                 if (type->kind != TYPE_FUNCTION &&
4392                     declaration->is_inline &&
4393                     is_type_valid(type)) {
4394                         warningf(&declaration->source_position,
4395                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
4396                 }
4397
4398                 if (token.type == '=') {
4399                         parse_init_declarator_rest(declaration);
4400                 }
4401
4402                 if (token.type != ',')
4403                         break;
4404                 eat(',');
4405
4406                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4407         }
4408         expect(';');
4409
4410 end_error:
4411         rem_anchor_token(';');
4412         rem_anchor_token('=');
4413         rem_anchor_token(',');
4414 }
4415
4416 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4417 {
4418         symbol_t *symbol  = declaration->symbol;
4419         if (symbol == NULL) {
4420                 errorf(HERE, "anonymous declaration not valid as function parameter");
4421                 return declaration;
4422         }
4423         namespace_t namespc = (namespace_t) declaration->namespc;
4424         if (namespc != NAMESPACE_NORMAL) {
4425                 return record_declaration(declaration);
4426         }
4427
4428         declaration_t *previous_declaration = get_declaration(symbol, namespc);
4429         if (previous_declaration == NULL ||
4430                         previous_declaration->parent_scope != scope) {
4431                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4432                        symbol);
4433                 return declaration;
4434         }
4435
4436         if (previous_declaration->type == NULL) {
4437                 previous_declaration->type          = declaration->type;
4438                 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4439                 previous_declaration->storage_class = declaration->storage_class;
4440                 previous_declaration->parent_scope  = scope;
4441                 return previous_declaration;
4442         } else {
4443                 return record_declaration(declaration);
4444         }
4445 }
4446
4447 static void parse_declaration(parsed_declaration_func finished_declaration)
4448 {
4449         declaration_specifiers_t specifiers;
4450         memset(&specifiers, 0, sizeof(specifiers));
4451         parse_declaration_specifiers(&specifiers);
4452
4453         if (token.type == ';') {
4454                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4455         } else {
4456                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4457                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4458         }
4459 }
4460
4461 static type_t *get_default_promoted_type(type_t *orig_type)
4462 {
4463         type_t *result = orig_type;
4464
4465         type_t *type = skip_typeref(orig_type);
4466         if (is_type_integer(type)) {
4467                 result = promote_integer(type);
4468         } else if (type == type_float) {
4469                 result = type_double;
4470         }
4471
4472         return result;
4473 }
4474
4475 static void parse_kr_declaration_list(declaration_t *declaration)
4476 {
4477         type_t *type = skip_typeref(declaration->type);
4478         if (!is_type_function(type))
4479                 return;
4480
4481         if (!type->function.kr_style_parameters)
4482                 return;
4483
4484         /* push function parameters */
4485         int       top        = environment_top();
4486         scope_t  *last_scope = scope;
4487         set_scope(&declaration->scope);
4488
4489         declaration_t *parameter = declaration->scope.declarations;
4490         for ( ; parameter != NULL; parameter = parameter->next) {
4491                 assert(parameter->parent_scope == NULL);
4492                 parameter->parent_scope = scope;
4493                 environment_push(parameter);
4494         }
4495
4496         /* parse declaration list */
4497         while (is_declaration_specifier(&token, false)) {
4498                 parse_declaration(finished_kr_declaration);
4499         }
4500
4501         /* pop function parameters */
4502         assert(scope == &declaration->scope);
4503         set_scope(last_scope);
4504         environment_pop_to(top);
4505
4506         /* update function type */
4507         type_t *new_type = duplicate_type(type);
4508
4509         function_parameter_t *parameters     = NULL;
4510         function_parameter_t *last_parameter = NULL;
4511
4512         declaration_t *parameter_declaration = declaration->scope.declarations;
4513         for( ; parameter_declaration != NULL;
4514                         parameter_declaration = parameter_declaration->next) {
4515                 type_t *parameter_type = parameter_declaration->type;
4516                 if (parameter_type == NULL) {
4517                         if (strict_mode) {
4518                                 errorf(HERE, "no type specified for function parameter '%Y'",
4519                                        parameter_declaration->symbol);
4520                         } else {
4521                                 if (warning.implicit_int) {
4522                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4523                                                 parameter_declaration->symbol);
4524                                 }
4525                                 parameter_type              = type_int;
4526                                 parameter_declaration->type = parameter_type;
4527                         }
4528                 }
4529
4530                 semantic_parameter(parameter_declaration);
4531                 parameter_type = parameter_declaration->type;
4532
4533                 /*
4534                  * we need the default promoted types for the function type
4535                  */
4536                 parameter_type = get_default_promoted_type(parameter_type);
4537
4538                 function_parameter_t *function_parameter
4539                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4540                 memset(function_parameter, 0, sizeof(function_parameter[0]));
4541
4542                 function_parameter->type = parameter_type;
4543                 if (last_parameter != NULL) {
4544                         last_parameter->next = function_parameter;
4545                 } else {
4546                         parameters = function_parameter;
4547                 }
4548                 last_parameter = function_parameter;
4549         }
4550
4551         /* Â§ 6.9.1.7: A K&R style parameter list does NOT act as a function
4552          * prototype */
4553         new_type->function.parameters             = parameters;
4554         new_type->function.unspecified_parameters = true;
4555
4556         type = typehash_insert(new_type);
4557         if (type != new_type) {
4558                 obstack_free(type_obst, new_type);
4559         }
4560
4561         declaration->type = type;
4562 }
4563
4564 static bool first_err = true;
4565
4566 /**
4567  * When called with first_err set, prints the name of the current function,
4568  * else does noting.
4569  */
4570 static void print_in_function(void)
4571 {
4572         if (first_err) {
4573                 first_err = false;
4574                 diagnosticf("%s: In function '%Y':\n",
4575                         current_function->source_position.input_name,
4576                         current_function->symbol);
4577         }
4578 }
4579
4580 /**
4581  * Check if all labels are defined in the current function.
4582  * Check if all labels are used in the current function.
4583  */
4584 static void check_labels(void)
4585 {
4586         for (const goto_statement_t *goto_statement = goto_first;
4587             goto_statement != NULL;
4588             goto_statement = goto_statement->next) {
4589                 declaration_t *label = goto_statement->label;
4590
4591                 label->used = true;
4592                 if (label->source_position.input_name == NULL) {
4593                         print_in_function();
4594                         errorf(&goto_statement->base.source_position,
4595                                "label '%Y' used but not defined", label->symbol);
4596                  }
4597         }
4598         goto_first = goto_last = NULL;
4599
4600         if (warning.unused_label) {
4601                 for (const label_statement_t *label_statement = label_first;
4602                          label_statement != NULL;
4603                          label_statement = label_statement->next) {
4604                         const declaration_t *label = label_statement->label;
4605
4606                         if (! label->used) {
4607                                 print_in_function();
4608                                 warningf(&label_statement->base.source_position,
4609                                         "label '%Y' defined but not used", label->symbol);
4610                         }
4611                 }
4612         }
4613         label_first = label_last = NULL;
4614 }
4615
4616 /**
4617  * Check declarations of current_function for unused entities.
4618  */
4619 static void check_declarations(void)
4620 {
4621         if (warning.unused_parameter) {
4622                 const scope_t *scope = &current_function->scope;
4623
4624                 const declaration_t *parameter = scope->declarations;
4625                 for (; parameter != NULL; parameter = parameter->next) {
4626                         if (! parameter->used) {
4627                                 print_in_function();
4628                                 warningf(&parameter->source_position,
4629                                          "unused parameter '%Y'", parameter->symbol);
4630                         }
4631                 }
4632         }
4633         if (warning.unused_variable) {
4634         }
4635 }
4636
4637 static void parse_external_declaration(void)
4638 {
4639         /* function-definitions and declarations both start with declaration
4640          * specifiers */
4641         declaration_specifiers_t specifiers;
4642         memset(&specifiers, 0, sizeof(specifiers));
4643
4644         add_anchor_token(';');
4645         parse_declaration_specifiers(&specifiers);
4646         rem_anchor_token(';');
4647
4648         /* must be a declaration */
4649         if (token.type == ';') {
4650                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4651                 return;
4652         }
4653
4654         add_anchor_token(',');
4655         add_anchor_token('=');
4656         rem_anchor_token(';');
4657
4658         /* declarator is common to both function-definitions and declarations */
4659         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4660
4661         rem_anchor_token(',');
4662         rem_anchor_token('=');
4663         rem_anchor_token(';');
4664
4665         /* must be a declaration */
4666         switch (token.type) {
4667                 case ',':
4668                 case ';':
4669                         parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4670                         return;
4671
4672                 case '=':
4673                         parse_declaration_rest(ndeclaration, &specifiers, record_definition);
4674                         return;
4675         }
4676
4677         /* must be a function definition */
4678         parse_kr_declaration_list(ndeclaration);
4679
4680         if (token.type != '{') {
4681                 parse_error_expected("while parsing function definition", '{', NULL);
4682                 eat_until_matching_token(';');
4683                 return;
4684         }
4685
4686         type_t *type = ndeclaration->type;
4687
4688         /* note that we don't skip typerefs: the standard doesn't allow them here
4689          * (so we can't use is_type_function here) */
4690         if (type->kind != TYPE_FUNCTION) {
4691                 if (is_type_valid(type)) {
4692                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
4693                                type, ndeclaration->symbol);
4694                 }
4695                 eat_block();
4696                 return;
4697         }
4698
4699         /* Â§ 6.7.5.3 (14) a function definition with () means no
4700          * parameters (and not unspecified parameters) */
4701         if (type->function.unspecified_parameters
4702                         && type->function.parameters == NULL
4703                         && !type->function.kr_style_parameters) {
4704                 type_t *duplicate = duplicate_type(type);
4705                 duplicate->function.unspecified_parameters = false;
4706
4707                 type = typehash_insert(duplicate);
4708                 if (type != duplicate) {
4709                         obstack_free(type_obst, duplicate);
4710                 }
4711                 ndeclaration->type = type;
4712         }
4713
4714         declaration_t *const declaration = record_definition(ndeclaration);
4715         if (ndeclaration != declaration) {
4716                 declaration->scope = ndeclaration->scope;
4717         }
4718         type = skip_typeref(declaration->type);
4719
4720         /* push function parameters and switch scope */
4721         int       top        = environment_top();
4722         scope_t  *last_scope = scope;
4723         set_scope(&declaration->scope);
4724
4725         declaration_t *parameter = declaration->scope.declarations;
4726         for( ; parameter != NULL; parameter = parameter->next) {
4727                 if (parameter->parent_scope == &ndeclaration->scope) {
4728                         parameter->parent_scope = scope;
4729                 }
4730                 assert(parameter->parent_scope == NULL
4731                                 || parameter->parent_scope == scope);
4732                 parameter->parent_scope = scope;
4733                 if (parameter->symbol == NULL) {
4734                         errorf(&ndeclaration->source_position, "parameter name omitted");
4735                         continue;
4736                 }
4737                 environment_push(parameter);
4738         }
4739
4740         if (declaration->init.statement != NULL) {
4741                 parser_error_multiple_definition(declaration, HERE);
4742                 eat_block();
4743         } else {
4744                 /* parse function body */
4745                 int            label_stack_top      = label_top();
4746                 declaration_t *old_current_function = current_function;
4747                 current_function                    = declaration;
4748
4749                 declaration->init.statement = parse_compound_statement(false);
4750                 first_err = true;
4751                 check_labels();
4752                 check_declarations();
4753
4754                 assert(current_function == declaration);
4755                 current_function = old_current_function;
4756                 label_pop_to(label_stack_top);
4757         }
4758
4759         assert(scope == &declaration->scope);
4760         set_scope(last_scope);
4761         environment_pop_to(top);
4762 }
4763
4764 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4765                                   source_position_t *source_position)
4766 {
4767         type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4768
4769         type->bitfield.base_type = base_type;
4770         type->bitfield.size      = size;
4771
4772         return type;
4773 }
4774
4775 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4776                                           symbol_t *symbol)
4777 {
4778         declaration_t *iter = compound_declaration->scope.declarations;
4779         for( ; iter != NULL; iter = iter->next) {
4780                 if (iter->namespc != NAMESPACE_NORMAL)
4781                         continue;
4782
4783                 if (iter->symbol == NULL) {
4784                         type_t *type = skip_typeref(iter->type);
4785                         if (is_type_compound(type)) {
4786                                 declaration_t *result
4787                                         = find_compound_entry(type->compound.declaration, symbol);
4788                                 if (result != NULL)
4789                                         return result;
4790                         }
4791                         continue;
4792                 }
4793
4794                 if (iter->symbol == symbol) {
4795                         return iter;
4796                 }
4797         }
4798
4799         return NULL;
4800 }
4801
4802 static void parse_compound_declarators(declaration_t *struct_declaration,
4803                 const declaration_specifiers_t *specifiers)
4804 {
4805         declaration_t *last_declaration = struct_declaration->scope.declarations;
4806         if (last_declaration != NULL) {
4807                 while(last_declaration->next != NULL) {
4808                         last_declaration = last_declaration->next;
4809                 }
4810         }
4811
4812         while(1) {
4813                 declaration_t *declaration;
4814
4815                 if (token.type == ':') {
4816                         source_position_t source_position = *HERE;
4817                         next_token();
4818
4819                         type_t *base_type = specifiers->type;
4820                         expression_t *size = parse_constant_expression();
4821
4822                         if (!is_type_integer(skip_typeref(base_type))) {
4823                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
4824                                        base_type);
4825                         }
4826
4827                         type_t *type = make_bitfield_type(base_type, size, &source_position);
4828
4829                         declaration                         = allocate_declaration_zero();
4830                         declaration->namespc                = NAMESPACE_NORMAL;
4831                         declaration->declared_storage_class = STORAGE_CLASS_NONE;
4832                         declaration->storage_class          = STORAGE_CLASS_NONE;
4833                         declaration->source_position        = source_position;
4834                         declaration->modifiers              = specifiers->modifiers;
4835                         declaration->type                   = type;
4836                 } else {
4837                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4838
4839                         type_t *orig_type = declaration->type;
4840                         type_t *type      = skip_typeref(orig_type);
4841
4842                         if (token.type == ':') {
4843                                 source_position_t source_position = *HERE;
4844                                 next_token();
4845                                 expression_t *size = parse_constant_expression();
4846
4847                                 if (!is_type_integer(type)) {
4848                                         errorf(HERE, "bitfield base type '%T' is not an "
4849                                                "integer type", orig_type);
4850                                 }
4851
4852                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4853                                 declaration->type = bitfield_type;
4854                         } else {
4855                                 /* TODO we ignore arrays for now... what is missing is a check
4856                                  * that they're at the end of the struct */
4857                                 if (is_type_incomplete(type) && !is_type_array(type)) {
4858                                         errorf(HERE,
4859                                                "compound member '%Y' has incomplete type '%T'",
4860                                                declaration->symbol, orig_type);
4861                                 } else if (is_type_function(type)) {
4862                                         errorf(HERE, "compound member '%Y' must not have function "
4863                                                "type '%T'", declaration->symbol, orig_type);
4864                                 }
4865                         }
4866                 }
4867
4868                 /* make sure we don't define a symbol multiple times */
4869                 symbol_t *symbol = declaration->symbol;
4870                 if (symbol != NULL) {
4871                         declaration_t *prev_decl
4872                                 = find_compound_entry(struct_declaration, symbol);
4873
4874                         if (prev_decl != NULL) {
4875                                 assert(prev_decl->symbol == symbol);
4876                                 errorf(&declaration->source_position,
4877                                        "multiple declarations of symbol '%Y' (declared %P)",
4878                                        symbol, &prev_decl->source_position);
4879                         }
4880                 }
4881
4882                 /* append declaration */
4883                 if (last_declaration != NULL) {
4884                         last_declaration->next = declaration;
4885                 } else {
4886                         struct_declaration->scope.declarations = declaration;
4887                 }
4888                 last_declaration = declaration;
4889
4890                 if (token.type != ',')
4891                         break;
4892                 next_token();
4893         }
4894         expect(';');
4895
4896 end_error:
4897         ;
4898 }
4899
4900 static void parse_compound_type_entries(declaration_t *compound_declaration)
4901 {
4902         eat('{');
4903         add_anchor_token('}');
4904
4905         while(token.type != '}' && token.type != T_EOF) {
4906                 declaration_specifiers_t specifiers;
4907                 memset(&specifiers, 0, sizeof(specifiers));
4908                 parse_declaration_specifiers(&specifiers);
4909
4910                 parse_compound_declarators(compound_declaration, &specifiers);
4911         }
4912         rem_anchor_token('}');
4913
4914         if (token.type == T_EOF) {
4915                 errorf(HERE, "EOF while parsing struct");
4916         }
4917         next_token();
4918 }
4919
4920 static type_t *parse_typename(void)
4921 {
4922         declaration_specifiers_t specifiers;
4923         memset(&specifiers, 0, sizeof(specifiers));
4924         parse_declaration_specifiers(&specifiers);
4925         if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4926                 /* TODO: improve error message, user does probably not know what a
4927                  * storage class is...
4928                  */
4929                 errorf(HERE, "typename may not have a storage class");
4930         }
4931
4932         type_t *result = parse_abstract_declarator(specifiers.type);
4933
4934         return result;
4935 }
4936
4937
4938
4939
4940 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4941 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4942                                                           expression_t *left);
4943
4944 typedef struct expression_parser_function_t expression_parser_function_t;
4945 struct expression_parser_function_t {
4946         unsigned                         precedence;
4947         parse_expression_function        parser;
4948         unsigned                         infix_precedence;
4949         parse_expression_infix_function  infix_parser;
4950 };
4951
4952 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4953
4954 /**
4955  * Prints an error message if an expression was expected but not read
4956  */
4957 static expression_t *expected_expression_error(void)
4958 {
4959         /* skip the error message if the error token was read */
4960         if (token.type != T_ERROR) {
4961                 errorf(HERE, "expected expression, got token '%K'", &token);
4962         }
4963         next_token();
4964
4965         return create_invalid_expression();
4966 }
4967
4968 /**
4969  * Parse a string constant.
4970  */
4971 static expression_t *parse_string_const(void)
4972 {
4973         wide_string_t wres;
4974         if (token.type == T_STRING_LITERAL) {
4975                 string_t res = token.v.string;
4976                 next_token();
4977                 while (token.type == T_STRING_LITERAL) {
4978                         res = concat_strings(&res, &token.v.string);
4979                         next_token();
4980                 }
4981                 if (token.type != T_WIDE_STRING_LITERAL) {
4982                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4983                         /* note: that we use type_char_ptr here, which is already the
4984                          * automatic converted type. revert_automatic_type_conversion
4985                          * will construct the array type */
4986                         cnst->base.type    = type_char_ptr;
4987                         cnst->string.value = res;
4988                         return cnst;
4989                 }
4990
4991                 wres = concat_string_wide_string(&res, &token.v.wide_string);
4992         } else {
4993                 wres = token.v.wide_string;
4994         }
4995         next_token();
4996
4997         for (;;) {
4998                 switch (token.type) {
4999                         case T_WIDE_STRING_LITERAL:
5000                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
5001                                 break;
5002
5003                         case T_STRING_LITERAL:
5004                                 wres = concat_wide_string_string(&wres, &token.v.string);
5005                                 break;
5006
5007                         default: {
5008                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5009                                 cnst->base.type         = type_wchar_t_ptr;
5010                                 cnst->wide_string.value = wres;
5011                                 return cnst;
5012                         }
5013                 }
5014                 next_token();
5015         }
5016 }
5017
5018 /**
5019  * Parse an integer constant.
5020  */
5021 static expression_t *parse_int_const(void)
5022 {
5023         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5024         cnst->base.source_position = *HERE;
5025         cnst->base.type            = token.datatype;
5026         cnst->conste.v.int_value   = token.v.intvalue;
5027
5028         next_token();
5029
5030         return cnst;
5031 }
5032
5033 /**
5034  * Parse a character constant.
5035  */
5036 static expression_t *parse_character_constant(void)
5037 {
5038         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5039
5040         cnst->base.source_position = *HERE;
5041         cnst->base.type            = token.datatype;
5042         cnst->conste.v.character   = token.v.string;
5043
5044         if (cnst->conste.v.character.size != 1) {
5045                 if (warning.multichar && (c_mode & _GNUC)) {
5046                         /* TODO */
5047                         warningf(HERE, "multi-character character constant");
5048                 } else {
5049                         errorf(HERE, "more than 1 characters in character constant");
5050                 }
5051         }
5052         next_token();
5053
5054         return cnst;
5055 }
5056
5057 /**
5058  * Parse a wide character constant.
5059  */
5060 static expression_t *parse_wide_character_constant(void)
5061 {
5062         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5063
5064         cnst->base.source_position    = *HERE;
5065         cnst->base.type               = token.datatype;
5066         cnst->conste.v.wide_character = token.v.wide_string;
5067
5068         if (cnst->conste.v.wide_character.size != 1) {
5069                 if (warning.multichar && (c_mode & _GNUC)) {
5070                         /* TODO */
5071                         warningf(HERE, "multi-character character constant");
5072                 } else {
5073                         errorf(HERE, "more than 1 characters in character constant");
5074                 }
5075         }
5076         next_token();
5077
5078         return cnst;
5079 }
5080
5081 /**
5082  * Parse a float constant.
5083  */
5084 static expression_t *parse_float_const(void)
5085 {
5086         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5087         cnst->base.type            = token.datatype;
5088         cnst->conste.v.float_value = token.v.floatvalue;
5089
5090         next_token();
5091
5092         return cnst;
5093 }
5094
5095 static declaration_t *create_implicit_function(symbol_t *symbol,
5096                 const source_position_t *source_position)
5097 {
5098         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
5099         ntype->function.return_type            = type_int;
5100         ntype->function.unspecified_parameters = true;
5101
5102         type_t *type = typehash_insert(ntype);
5103         if (type != ntype) {
5104                 free_type(ntype);
5105         }
5106
5107         declaration_t *const declaration    = allocate_declaration_zero();
5108         declaration->storage_class          = STORAGE_CLASS_EXTERN;
5109         declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5110         declaration->type                   = type;
5111         declaration->symbol                 = symbol;
5112         declaration->source_position        = *source_position;
5113
5114         bool strict_prototypes_old = warning.strict_prototypes;
5115         warning.strict_prototypes  = false;
5116         record_declaration(declaration);
5117         warning.strict_prototypes = strict_prototypes_old;
5118
5119         return declaration;
5120 }
5121
5122 /**
5123  * Creates a return_type (func)(argument_type) function type if not
5124  * already exists.
5125  */
5126 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5127                                     type_t *argument_type2)
5128 {
5129         function_parameter_t *parameter2
5130                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5131         memset(parameter2, 0, sizeof(parameter2[0]));
5132         parameter2->type = argument_type2;
5133
5134         function_parameter_t *parameter1
5135                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5136         memset(parameter1, 0, sizeof(parameter1[0]));
5137         parameter1->type = argument_type1;
5138         parameter1->next = parameter2;
5139
5140         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5141         type->function.return_type = return_type;
5142         type->function.parameters  = parameter1;
5143
5144         type_t *result = typehash_insert(type);
5145         if (result != type) {
5146                 free_type(type);
5147         }
5148
5149         return result;
5150 }
5151
5152 /**
5153  * Creates a return_type (func)(argument_type) function type if not
5154  * already exists.
5155  *
5156  * @param return_type    the return type
5157  * @param argument_type  the argument type
5158  */
5159 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5160 {
5161         function_parameter_t *parameter
5162                 = obstack_alloc(type_obst, sizeof(parameter[0]));
5163         memset(parameter, 0, sizeof(parameter[0]));
5164         parameter->type = argument_type;
5165
5166         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5167         type->function.return_type = return_type;
5168         type->function.parameters  = parameter;
5169
5170         type_t *result = typehash_insert(type);
5171         if (result != type) {
5172                 free_type(type);
5173         }
5174
5175         return result;
5176 }
5177
5178 static type_t *make_function_0_type(type_t *return_type)
5179 {
5180         type_t *type               = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5181         type->function.return_type = return_type;
5182         type->function.parameters  = NULL;
5183
5184         type_t *result = typehash_insert(type);
5185         if (result != type) {
5186                 free_type(type);
5187         }
5188
5189         return result;
5190 }
5191
5192 /**
5193  * Creates a function type for some function like builtins.
5194  *
5195  * @param symbol   the symbol describing the builtin
5196  */
5197 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5198 {
5199         switch(symbol->ID) {
5200         case T___builtin_alloca:
5201                 return make_function_1_type(type_void_ptr, type_size_t);
5202         case T___builtin_huge_val:
5203                 return make_function_0_type(type_double);
5204         case T___builtin_nan:
5205                 return make_function_1_type(type_double, type_char_ptr);
5206         case T___builtin_nanf:
5207                 return make_function_1_type(type_float, type_char_ptr);
5208         case T___builtin_nand:
5209                 return make_function_1_type(type_long_double, type_char_ptr);
5210         case T___builtin_va_end:
5211                 return make_function_1_type(type_void, type_valist);
5212         case T___builtin_expect:
5213                 return make_function_2_type(type_long, type_long, type_long);
5214         default:
5215                 internal_errorf(HERE, "not implemented builtin symbol found");
5216         }
5217 }
5218
5219 /**
5220  * Performs automatic type cast as described in Â§ 6.3.2.1.
5221  *
5222  * @param orig_type  the original type
5223  */
5224 static type_t *automatic_type_conversion(type_t *orig_type)
5225 {
5226         type_t *type = skip_typeref(orig_type);
5227         if (is_type_array(type)) {
5228                 array_type_t *array_type   = &type->array;
5229                 type_t       *element_type = array_type->element_type;
5230                 unsigned      qualifiers   = array_type->base.qualifiers;
5231
5232                 return make_pointer_type(element_type, qualifiers);
5233         }
5234
5235         if (is_type_function(type)) {
5236                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5237         }
5238
5239         return orig_type;
5240 }
5241
5242 /**
5243  * reverts the automatic casts of array to pointer types and function
5244  * to function-pointer types as defined Â§ 6.3.2.1
5245  */
5246 type_t *revert_automatic_type_conversion(const expression_t *expression)
5247 {
5248         switch (expression->kind) {
5249                 case EXPR_REFERENCE: return expression->reference.declaration->type;
5250                 case EXPR_SELECT:    return expression->select.compound_entry->type;
5251
5252                 case EXPR_UNARY_DEREFERENCE: {
5253                         const expression_t *const value = expression->unary.value;
5254                         type_t             *const type  = skip_typeref(value->base.type);
5255                         assert(is_type_pointer(type));
5256                         return type->pointer.points_to;
5257                 }
5258
5259                 case EXPR_BUILTIN_SYMBOL:
5260                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5261
5262                 case EXPR_ARRAY_ACCESS: {
5263                         const expression_t *array_ref = expression->array_access.array_ref;
5264                         type_t             *type_left = skip_typeref(array_ref->base.type);
5265                         if (!is_type_valid(type_left))
5266                                 return type_left;
5267                         assert(is_type_pointer(type_left));
5268                         return type_left->pointer.points_to;
5269                 }
5270
5271                 case EXPR_STRING_LITERAL: {
5272                         size_t size = expression->string.value.size;
5273                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5274                 }
5275
5276                 case EXPR_WIDE_STRING_LITERAL: {
5277                         size_t size = expression->wide_string.value.size;
5278                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5279                 }
5280
5281                 case EXPR_COMPOUND_LITERAL:
5282                         return expression->compound_literal.type;
5283
5284                 default: break;
5285         }
5286
5287         return expression->base.type;
5288 }
5289
5290 static expression_t *parse_reference(void)
5291 {
5292         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5293
5294         reference_expression_t *ref = &expression->reference;
5295         symbol_t *const symbol = token.v.symbol;
5296
5297         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5298
5299         source_position_t source_position = token.source_position;
5300         next_token();
5301
5302         if (declaration == NULL) {
5303                 if (! strict_mode && token.type == '(') {
5304                         /* an implicitly defined function */
5305                         if (warning.implicit_function_declaration) {
5306                                 warningf(HERE, "implicit declaration of function '%Y'",
5307                                         symbol);
5308                         }
5309
5310                         declaration = create_implicit_function(symbol,
5311                                                                &source_position);
5312                 } else {
5313                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
5314                         return create_invalid_expression();
5315                 }
5316         }
5317
5318         type_t *type         = declaration->type;
5319
5320         /* we always do the auto-type conversions; the & and sizeof parser contains
5321          * code to revert this! */
5322         type = automatic_type_conversion(type);
5323
5324         ref->declaration = declaration;
5325         ref->base.type   = type;
5326
5327         /* this declaration is used */
5328         declaration->used = true;
5329
5330         /* check for deprecated functions */
5331         if (declaration->deprecated != 0) {
5332                 const char *prefix = "";
5333                 if (is_type_function(declaration->type))
5334                         prefix = "function ";
5335
5336                 if (declaration->deprecated_string != NULL) {
5337                         warningf(&source_position,
5338                                 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5339                                 declaration->deprecated_string);
5340                 } else {
5341                         warningf(&source_position,
5342                                 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5343                 }
5344         }
5345
5346         return expression;
5347 }
5348
5349 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5350 {
5351         (void) expression;
5352         (void) dest_type;
5353         /* TODO check if explicit cast is allowed and issue warnings/errors */
5354 }
5355
5356 static expression_t *parse_compound_literal(type_t *type)
5357 {
5358         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5359
5360         parse_initializer_env_t env;
5361         env.type             = type;
5362         env.declaration      = NULL;
5363         env.must_be_constant = false;
5364         initializer_t *initializer = parse_initializer(&env);
5365         type = env.type;
5366
5367         expression->compound_literal.initializer = initializer;
5368         expression->compound_literal.type        = type;
5369         expression->base.type                    = automatic_type_conversion(type);
5370
5371         return expression;
5372 }
5373
5374 /**
5375  * Parse a cast expression.
5376  */
5377 static expression_t *parse_cast(void)
5378 {
5379         source_position_t source_position = token.source_position;
5380
5381         type_t *type  = parse_typename();
5382
5383         /* matching add_anchor_token() is at call site */
5384         rem_anchor_token(')');
5385         expect(')');
5386
5387         if (token.type == '{') {
5388                 return parse_compound_literal(type);
5389         }
5390
5391         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5392         cast->base.source_position = source_position;
5393
5394         expression_t *value = parse_sub_expression(20);
5395
5396         check_cast_allowed(value, type);
5397
5398         cast->base.type   = type;
5399         cast->unary.value = value;
5400
5401         return cast;
5402 end_error:
5403         return create_invalid_expression();
5404 }
5405
5406 /**
5407  * Parse a statement expression.
5408  */
5409 static expression_t *parse_statement_expression(void)
5410 {
5411         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5412
5413         statement_t *statement           = parse_compound_statement(true);
5414         expression->statement.statement  = statement;
5415         expression->base.source_position = statement->base.source_position;
5416
5417         /* find last statement and use its type */
5418         type_t *type = type_void;
5419         const statement_t *stmt = statement->compound.statements;
5420         if (stmt != NULL) {
5421                 while (stmt->base.next != NULL)
5422                         stmt = stmt->base.next;
5423
5424                 if (stmt->kind == STATEMENT_EXPRESSION) {
5425                         type = stmt->expression.expression->base.type;
5426                 }
5427         } else {
5428                 warningf(&expression->base.source_position, "empty statement expression ({})");
5429         }
5430         expression->base.type = type;
5431
5432         expect(')');
5433
5434         return expression;
5435 end_error:
5436         return create_invalid_expression();
5437 }
5438
5439 /**
5440  * Parse a braced expression.
5441  */
5442 static expression_t *parse_brace_expression(void)
5443 {
5444         eat('(');
5445         add_anchor_token(')');
5446
5447         switch(token.type) {
5448         case '{':
5449                 /* gcc extension: a statement expression */
5450                 return parse_statement_expression();
5451
5452         TYPE_QUALIFIERS
5453         TYPE_SPECIFIERS
5454                 return parse_cast();
5455         case T_IDENTIFIER:
5456                 if (is_typedef_symbol(token.v.symbol)) {
5457                         return parse_cast();
5458                 }
5459         }
5460
5461         expression_t *result = parse_expression();
5462         rem_anchor_token(')');
5463         expect(')');
5464
5465         return result;
5466 end_error:
5467         return create_invalid_expression();
5468 }
5469
5470 static expression_t *parse_function_keyword(void)
5471 {
5472         next_token();
5473         /* TODO */
5474
5475         if (current_function == NULL) {
5476                 errorf(HERE, "'__func__' used outside of a function");
5477         }
5478
5479         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5480         expression->base.type     = type_char_ptr;
5481         expression->funcname.kind = FUNCNAME_FUNCTION;
5482
5483         return expression;
5484 }
5485
5486 static expression_t *parse_pretty_function_keyword(void)
5487 {
5488         eat(T___PRETTY_FUNCTION__);
5489
5490         if (current_function == NULL) {
5491                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5492         }
5493
5494         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5495         expression->base.type     = type_char_ptr;
5496         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5497
5498         return expression;
5499 }
5500
5501 static expression_t *parse_funcsig_keyword(void)
5502 {
5503         eat(T___FUNCSIG__);
5504
5505         if (current_function == NULL) {
5506                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5507         }
5508
5509         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5510         expression->base.type     = type_char_ptr;
5511         expression->funcname.kind = FUNCNAME_FUNCSIG;
5512
5513         return expression;
5514 }
5515
5516 static expression_t *parse_funcdname_keyword(void)
5517 {
5518         eat(T___FUNCDNAME__);
5519
5520         if (current_function == NULL) {
5521                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5522         }
5523
5524         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
5525         expression->base.type     = type_char_ptr;
5526         expression->funcname.kind = FUNCNAME_FUNCDNAME;
5527
5528         return expression;
5529 }
5530
5531 static designator_t *parse_designator(void)
5532 {
5533         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
5534         result->source_position = *HERE;
5535
5536         if (token.type != T_IDENTIFIER) {
5537                 parse_error_expected("while parsing member designator",
5538                                      T_IDENTIFIER, NULL);
5539                 return NULL;
5540         }
5541         result->symbol = token.v.symbol;
5542         next_token();
5543
5544         designator_t *last_designator = result;
5545         while(true) {
5546                 if (token.type == '.') {
5547                         next_token();
5548                         if (token.type != T_IDENTIFIER) {
5549                                 parse_error_expected("while parsing member designator",
5550                                                      T_IDENTIFIER, NULL);
5551                                 return NULL;
5552                         }
5553                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5554                         designator->source_position = *HERE;
5555                         designator->symbol          = token.v.symbol;
5556                         next_token();
5557
5558                         last_designator->next = designator;
5559                         last_designator       = designator;
5560                         continue;
5561                 }
5562                 if (token.type == '[') {
5563                         next_token();
5564                         add_anchor_token(']');
5565                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
5566                         designator->source_position = *HERE;
5567                         designator->array_index     = parse_expression();
5568                         rem_anchor_token(']');
5569                         expect(']');
5570                         if (designator->array_index == NULL) {
5571                                 return NULL;
5572                         }
5573
5574                         last_designator->next = designator;
5575                         last_designator       = designator;
5576                         continue;
5577                 }
5578                 break;
5579         }
5580
5581         return result;
5582 end_error:
5583         return NULL;
5584 }
5585
5586 /**
5587  * Parse the __builtin_offsetof() expression.
5588  */
5589 static expression_t *parse_offsetof(void)
5590 {
5591         eat(T___builtin_offsetof);
5592
5593         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5594         expression->base.type    = type_size_t;
5595
5596         expect('(');
5597         add_anchor_token(',');
5598         type_t *type = parse_typename();
5599         rem_anchor_token(',');
5600         expect(',');
5601         add_anchor_token(')');
5602         designator_t *designator = parse_designator();
5603         rem_anchor_token(')');
5604         expect(')');
5605
5606         expression->offsetofe.type       = type;
5607         expression->offsetofe.designator = designator;
5608
5609         type_path_t path;
5610         memset(&path, 0, sizeof(path));
5611         path.top_type = type;
5612         path.path     = NEW_ARR_F(type_path_entry_t, 0);
5613
5614         descend_into_subtype(&path);
5615
5616         if (!walk_designator(&path, designator, true)) {
5617                 return create_invalid_expression();
5618         }
5619
5620         DEL_ARR_F(path.path);
5621
5622         return expression;
5623 end_error:
5624         return create_invalid_expression();
5625 }
5626
5627 /**
5628  * Parses a _builtin_va_start() expression.
5629  */
5630 static expression_t *parse_va_start(void)
5631 {
5632         eat(T___builtin_va_start);
5633
5634         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5635
5636         expect('(');
5637         add_anchor_token(',');
5638         expression->va_starte.ap = parse_assignment_expression();
5639         rem_anchor_token(',');
5640         expect(',');
5641         expression_t *const expr = parse_assignment_expression();
5642         if (expr->kind == EXPR_REFERENCE) {
5643                 declaration_t *const decl = expr->reference.declaration;
5644                 if (decl == NULL)
5645                         return create_invalid_expression();
5646                 if (decl->parent_scope == &current_function->scope &&
5647                     decl->next == NULL) {
5648                         expression->va_starte.parameter = decl;
5649                         expect(')');
5650                         return expression;
5651                 }
5652         }
5653         errorf(&expr->base.source_position,
5654                "second argument of 'va_start' must be last parameter of the current function");
5655 end_error:
5656         return create_invalid_expression();
5657 }
5658
5659 /**
5660  * Parses a _builtin_va_arg() expression.
5661  */
5662 static expression_t *parse_va_arg(void)
5663 {
5664         eat(T___builtin_va_arg);
5665
5666         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5667
5668         expect('(');
5669         expression->va_arge.ap = parse_assignment_expression();
5670         expect(',');
5671         expression->base.type = parse_typename();
5672         expect(')');
5673
5674         return expression;
5675 end_error:
5676         return create_invalid_expression();
5677 }
5678
5679 static expression_t *parse_builtin_symbol(void)
5680 {
5681         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5682
5683         symbol_t *symbol = token.v.symbol;
5684
5685         expression->builtin_symbol.symbol = symbol;
5686         next_token();
5687
5688         type_t *type = get_builtin_symbol_type(symbol);
5689         type = automatic_type_conversion(type);
5690
5691         expression->base.type = type;
5692         return expression;
5693 }
5694
5695 /**
5696  * Parses a __builtin_constant() expression.
5697  */
5698 static expression_t *parse_builtin_constant(void)
5699 {
5700         eat(T___builtin_constant_p);
5701
5702         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5703
5704         expect('(');
5705         add_anchor_token(')');
5706         expression->builtin_constant.value = parse_assignment_expression();
5707         rem_anchor_token(')');
5708         expect(')');
5709         expression->base.type = type_int;
5710
5711         return expression;
5712 end_error:
5713         return create_invalid_expression();
5714 }
5715
5716 /**
5717  * Parses a __builtin_prefetch() expression.
5718  */
5719 static expression_t *parse_builtin_prefetch(void)
5720 {
5721         eat(T___builtin_prefetch);
5722
5723         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5724
5725         expect('(');
5726         add_anchor_token(')');
5727         expression->builtin_prefetch.adr = parse_assignment_expression();
5728         if (token.type == ',') {
5729                 next_token();
5730                 expression->builtin_prefetch.rw = parse_assignment_expression();
5731         }
5732         if (token.type == ',') {
5733                 next_token();
5734                 expression->builtin_prefetch.locality = parse_assignment_expression();
5735         }
5736         rem_anchor_token(')');
5737         expect(')');
5738         expression->base.type = type_void;
5739
5740         return expression;
5741 end_error:
5742         return create_invalid_expression();
5743 }
5744
5745 /**
5746  * Parses a __builtin_is_*() compare expression.
5747  */
5748 static expression_t *parse_compare_builtin(void)
5749 {
5750         expression_t *expression;
5751
5752         switch(token.type) {
5753         case T___builtin_isgreater:
5754                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5755                 break;
5756         case T___builtin_isgreaterequal:
5757                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5758                 break;
5759         case T___builtin_isless:
5760                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5761                 break;
5762         case T___builtin_islessequal:
5763                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5764                 break;
5765         case T___builtin_islessgreater:
5766                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5767                 break;
5768         case T___builtin_isunordered:
5769                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5770                 break;
5771         default:
5772                 internal_errorf(HERE, "invalid compare builtin found");
5773                 break;
5774         }
5775         expression->base.source_position = *HERE;
5776         next_token();
5777
5778         expect('(');
5779         expression->binary.left = parse_assignment_expression();
5780         expect(',');
5781         expression->binary.right = parse_assignment_expression();
5782         expect(')');
5783
5784         type_t *const orig_type_left  = expression->binary.left->base.type;
5785         type_t *const orig_type_right = expression->binary.right->base.type;
5786
5787         type_t *const type_left  = skip_typeref(orig_type_left);
5788         type_t *const type_right = skip_typeref(orig_type_right);
5789         if (!is_type_float(type_left) && !is_type_float(type_right)) {
5790                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5791                         type_error_incompatible("invalid operands in comparison",
5792                                 &expression->base.source_position, orig_type_left, orig_type_right);
5793                 }
5794         } else {
5795                 semantic_comparison(&expression->binary);
5796         }
5797
5798         return expression;
5799 end_error:
5800         return create_invalid_expression();
5801 }
5802
5803 #if 0
5804 /**
5805  * Parses a __builtin_expect() expression.
5806  */
5807 static expression_t *parse_builtin_expect(void)
5808 {
5809         eat(T___builtin_expect);
5810
5811         expression_t *expression
5812                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5813
5814         expect('(');
5815         expression->binary.left = parse_assignment_expression();
5816         expect(',');
5817         expression->binary.right = parse_constant_expression();
5818         expect(')');
5819
5820         expression->base.type = expression->binary.left->base.type;
5821
5822         return expression;
5823 end_error:
5824         return create_invalid_expression();
5825 }
5826 #endif
5827
5828 /**
5829  * Parses a MS assume() expression.
5830  */
5831 static expression_t *parse_assume(void)
5832 {
5833         eat(T__assume);
5834
5835         expression_t *expression
5836                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5837
5838         expect('(');
5839         add_anchor_token(')');
5840         expression->unary.value = parse_assignment_expression();
5841         rem_anchor_token(')');
5842         expect(')');
5843
5844         expression->base.type = type_void;
5845         return expression;
5846 end_error:
5847         return create_invalid_expression();
5848 }
5849
5850 /**
5851  * Parse a microsoft __noop expression.
5852  */
5853 static expression_t *parse_noop_expression(void)
5854 {
5855         source_position_t source_position = *HERE;
5856         eat(T___noop);
5857
5858         if (token.type == '(') {
5859                 /* parse arguments */
5860                 eat('(');
5861                 add_anchor_token(')');
5862                 add_anchor_token(',');
5863
5864                 if (token.type != ')') {
5865                         while(true) {
5866                                 (void)parse_assignment_expression();
5867                                 if (token.type != ',')
5868                                         break;
5869                                 next_token();
5870                         }
5871                 }
5872         }
5873         rem_anchor_token(',');
5874         rem_anchor_token(')');
5875         expect(')');
5876
5877         /* the result is a (int)0 */
5878         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
5879         cnst->base.source_position = source_position;
5880         cnst->base.type            = type_int;
5881         cnst->conste.v.int_value   = 0;
5882         cnst->conste.is_ms_noop    = true;
5883
5884         return cnst;
5885
5886 end_error:
5887         return create_invalid_expression();
5888 }
5889
5890 /**
5891  * Parses a primary expression.
5892  */
5893 static expression_t *parse_primary_expression(void)
5894 {
5895         switch (token.type) {
5896                 case T_INTEGER:                  return parse_int_const();
5897                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
5898                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
5899                 case T_FLOATINGPOINT:            return parse_float_const();
5900                 case T_STRING_LITERAL:
5901                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
5902                 case T_IDENTIFIER:               return parse_reference();
5903                 case T___FUNCTION__:
5904                 case T___func__:                 return parse_function_keyword();
5905                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
5906                 case T___FUNCSIG__:              return parse_funcsig_keyword();
5907                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
5908                 case T___builtin_offsetof:       return parse_offsetof();
5909                 case T___builtin_va_start:       return parse_va_start();
5910                 case T___builtin_va_arg:         return parse_va_arg();
5911                 case T___builtin_expect:
5912                 case T___builtin_alloca:
5913                 case T___builtin_nan:
5914                 case T___builtin_nand:
5915                 case T___builtin_nanf:
5916                 case T___builtin_huge_val:
5917                 case T___builtin_va_end:         return parse_builtin_symbol();
5918                 case T___builtin_isgreater:
5919                 case T___builtin_isgreaterequal:
5920                 case T___builtin_isless:
5921                 case T___builtin_islessequal:
5922                 case T___builtin_islessgreater:
5923                 case T___builtin_isunordered:    return parse_compare_builtin();
5924                 case T___builtin_constant_p:     return parse_builtin_constant();
5925                 case T___builtin_prefetch:       return parse_builtin_prefetch();
5926                 case T__assume:                  return parse_assume();
5927
5928                 case '(':                        return parse_brace_expression();
5929                 case T___noop:                   return parse_noop_expression();
5930         }
5931
5932         errorf(HERE, "unexpected token %K, expected an expression", &token);
5933         return create_invalid_expression();
5934 }
5935
5936 /**
5937  * Check if the expression has the character type and issue a warning then.
5938  */
5939 static void check_for_char_index_type(const expression_t *expression)
5940 {
5941         type_t       *const type      = expression->base.type;
5942         const type_t *const base_type = skip_typeref(type);
5943
5944         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5945                         warning.char_subscripts) {
5946                 warningf(&expression->base.source_position,
5947                          "array subscript has type '%T'", type);
5948         }
5949 }
5950
5951 static expression_t *parse_array_expression(unsigned precedence,
5952                                             expression_t *left)
5953 {
5954         (void) precedence;
5955
5956         eat('[');
5957         add_anchor_token(']');
5958
5959         expression_t *inside = parse_expression();
5960
5961         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5962
5963         array_access_expression_t *array_access = &expression->array_access;
5964
5965         type_t *const orig_type_left   = left->base.type;
5966         type_t *const orig_type_inside = inside->base.type;
5967
5968         type_t *const type_left   = skip_typeref(orig_type_left);
5969         type_t *const type_inside = skip_typeref(orig_type_inside);
5970
5971         type_t *return_type;
5972         if (is_type_pointer(type_left)) {
5973                 return_type             = type_left->pointer.points_to;
5974                 array_access->array_ref = left;
5975                 array_access->index     = inside;
5976                 check_for_char_index_type(inside);
5977         } else if (is_type_pointer(type_inside)) {
5978                 return_type             = type_inside->pointer.points_to;
5979                 array_access->array_ref = inside;
5980                 array_access->index     = left;
5981                 array_access->flipped   = true;
5982                 check_for_char_index_type(left);
5983         } else {
5984                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5985                         errorf(HERE,
5986                                 "array access on object with non-pointer types '%T', '%T'",
5987                                 orig_type_left, orig_type_inside);
5988                 }
5989                 return_type             = type_error_type;
5990                 array_access->array_ref = create_invalid_expression();
5991         }
5992
5993         rem_anchor_token(']');
5994         if (token.type != ']') {
5995                 parse_error_expected("Problem while parsing array access", ']', NULL);
5996                 return expression;
5997         }
5998         next_token();
5999
6000         return_type           = automatic_type_conversion(return_type);
6001         expression->base.type = return_type;
6002
6003         return expression;
6004 }
6005
6006 static expression_t *parse_typeprop(expression_kind_t const kind,
6007                                     source_position_t const pos,
6008                                     unsigned const precedence)
6009 {
6010         expression_t *tp_expression = allocate_expression_zero(kind);
6011         tp_expression->base.type            = type_size_t;
6012         tp_expression->base.source_position = pos;
6013
6014         char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6015
6016         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6017                 next_token();
6018                 add_anchor_token(')');
6019                 type_t* const orig_type = parse_typename();
6020                 tp_expression->typeprop.type = orig_type;
6021
6022                 type_t const* const type = skip_typeref(orig_type);
6023                 char const* const wrong_type =
6024                         is_type_incomplete(type)    ? "incomplete"          :
6025                         type->kind == TYPE_FUNCTION ? "function designator" :
6026                         type->kind == TYPE_BITFIELD ? "bitfield"            :
6027                         NULL;
6028                 if (wrong_type != NULL) {
6029                         errorf(&pos, "operand of %s expression must not be %s type '%T'",
6030                                what, wrong_type, type);
6031                 }
6032
6033                 rem_anchor_token(')');
6034                 expect(')');
6035         } else {
6036                 expression_t *expression = parse_sub_expression(precedence);
6037
6038                 type_t* const orig_type = revert_automatic_type_conversion(expression);
6039                 expression->base.type = orig_type;
6040
6041                 type_t const* const type = skip_typeref(orig_type);
6042                 char const* const wrong_type =
6043                         is_type_incomplete(type)    ? "incomplete"          :
6044                         type->kind == TYPE_FUNCTION ? "function designator" :
6045                         type->kind == TYPE_BITFIELD ? "bitfield"            :
6046                         NULL;
6047                 if (wrong_type != NULL) {
6048                         errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6049                 }
6050
6051                 tp_expression->typeprop.type          = expression->base.type;
6052                 tp_expression->typeprop.tp_expression = expression;
6053         }
6054
6055         return tp_expression;
6056 end_error:
6057         return create_invalid_expression();
6058 }
6059
6060 static expression_t *parse_sizeof(unsigned precedence)
6061 {
6062         source_position_t pos = *HERE;
6063         eat(T_sizeof);
6064         return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6065 }
6066
6067 static expression_t *parse_alignof(unsigned precedence)
6068 {
6069         source_position_t pos = *HERE;
6070         eat(T___alignof__);
6071         return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6072 }
6073
6074 static expression_t *parse_select_expression(unsigned precedence,
6075                                              expression_t *compound)
6076 {
6077         (void) precedence;
6078         assert(token.type == '.' || token.type == T_MINUSGREATER);
6079
6080         bool is_pointer = (token.type == T_MINUSGREATER);
6081         next_token();
6082
6083         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
6084         select->select.compound = compound;
6085
6086         if (token.type != T_IDENTIFIER) {
6087                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6088                 return select;
6089         }
6090         symbol_t *symbol      = token.v.symbol;
6091         select->select.symbol = symbol;
6092         next_token();
6093
6094         type_t *const orig_type = compound->base.type;
6095         type_t *const type      = skip_typeref(orig_type);
6096
6097         type_t *type_left = type;
6098         if (is_pointer) {
6099                 if (!is_type_pointer(type)) {
6100                         if (is_type_valid(type)) {
6101                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6102                         }
6103                         return create_invalid_expression();
6104                 }
6105                 type_left = type->pointer.points_to;
6106         }
6107         type_left = skip_typeref(type_left);
6108
6109         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6110             type_left->kind != TYPE_COMPOUND_UNION) {
6111                 if (is_type_valid(type_left)) {
6112                         errorf(HERE, "request for member '%Y' in something not a struct or "
6113                                "union, but '%T'", symbol, type_left);
6114                 }
6115                 return create_invalid_expression();
6116         }
6117
6118         declaration_t *const declaration = type_left->compound.declaration;
6119
6120         if (!declaration->init.complete) {
6121                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6122                        symbol, type_left);
6123                 return create_invalid_expression();
6124         }
6125
6126         declaration_t *iter = find_compound_entry(declaration, symbol);
6127         if (iter == NULL) {
6128                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6129                 return create_invalid_expression();
6130         }
6131
6132         /* we always do the auto-type conversions; the & and sizeof parser contains
6133          * code to revert this! */
6134         type_t *expression_type = automatic_type_conversion(iter->type);
6135
6136         select->select.compound_entry = iter;
6137         select->base.type             = expression_type;
6138
6139         type_t *skipped = skip_typeref(iter->type);
6140         if (skipped->kind == TYPE_BITFIELD) {
6141                 select->base.type = skipped->bitfield.base_type;
6142         }
6143
6144         return select;
6145 }
6146
6147 static void check_call_argument(const function_parameter_t *parameter,
6148                                 call_argument_t *argument)
6149 {
6150         type_t         *expected_type      = parameter->type;
6151         type_t         *expected_type_skip = skip_typeref(expected_type);
6152         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
6153         expression_t   *arg_expr           = argument->expression;
6154
6155         /* handle transparent union gnu extension */
6156         if (is_type_union(expected_type_skip)
6157                         && (expected_type_skip->base.modifiers
6158                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6159                 declaration_t  *union_decl = expected_type_skip->compound.declaration;
6160
6161                 declaration_t *declaration = union_decl->scope.declarations;
6162                 type_t        *best_type   = NULL;
6163                 for ( ; declaration != NULL; declaration = declaration->next) {
6164                         type_t *decl_type = declaration->type;
6165                         error = semantic_assign(decl_type, arg_expr);
6166                         if (error == ASSIGN_ERROR_INCOMPATIBLE
6167                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6168                                 continue;
6169
6170                         if (error == ASSIGN_SUCCESS) {
6171                                 best_type = decl_type;
6172                         } else if (best_type == NULL) {
6173                                 best_type = decl_type;
6174                         }
6175                 }
6176
6177                 if (best_type != NULL) {
6178                         expected_type = best_type;
6179                 }
6180         }
6181
6182         error                = semantic_assign(expected_type, arg_expr);
6183         argument->expression = create_implicit_cast(argument->expression,
6184                                                     expected_type);
6185
6186         /* TODO report exact scope in error messages (like "in 3rd parameter") */
6187         report_assign_error(error, expected_type, arg_expr,     "function call",
6188                             &arg_expr->base.source_position);
6189 }
6190
6191 /**
6192  * Parse a call expression, ie. expression '( ... )'.
6193  *
6194  * @param expression  the function address
6195  */
6196 static expression_t *parse_call_expression(unsigned precedence,
6197                                            expression_t *expression)
6198 {
6199         (void) precedence;
6200         expression_t *result = allocate_expression_zero(EXPR_CALL);
6201         result->base.source_position = expression->base.source_position;
6202
6203         call_expression_t *call = &result->call;
6204         call->function          = expression;
6205
6206         type_t *const orig_type = expression->base.type;
6207         type_t *const type      = skip_typeref(orig_type);
6208
6209         function_type_t *function_type = NULL;
6210         if (is_type_pointer(type)) {
6211                 type_t *const to_type = skip_typeref(type->pointer.points_to);
6212
6213                 if (is_type_function(to_type)) {
6214                         function_type   = &to_type->function;
6215                         call->base.type = function_type->return_type;
6216                 }
6217         }
6218
6219         if (function_type == NULL && is_type_valid(type)) {
6220                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6221         }
6222
6223         /* parse arguments */
6224         eat('(');
6225         add_anchor_token(')');
6226         add_anchor_token(',');
6227
6228         if (token.type != ')') {
6229                 call_argument_t *last_argument = NULL;
6230
6231                 while(true) {
6232                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6233
6234                         argument->expression = parse_assignment_expression();
6235                         if (last_argument == NULL) {
6236                                 call->arguments = argument;
6237                         } else {
6238                                 last_argument->next = argument;
6239                         }
6240                         last_argument = argument;
6241
6242                         if (token.type != ',')
6243                                 break;
6244                         next_token();
6245                 }
6246         }
6247         rem_anchor_token(',');
6248         rem_anchor_token(')');
6249         expect(')');
6250
6251         if (function_type == NULL)
6252                 return result;
6253
6254         function_parameter_t *parameter = function_type->parameters;
6255         call_argument_t      *argument  = call->arguments;
6256         if (!function_type->unspecified_parameters) {
6257                 for( ; parameter != NULL && argument != NULL;
6258                                 parameter = parameter->next, argument = argument->next) {
6259                         check_call_argument(parameter, argument);
6260                 }
6261
6262                 if (parameter != NULL) {
6263                         errorf(HERE, "too few arguments to function '%E'", expression);
6264                 } else if (argument != NULL && !function_type->variadic) {
6265                         errorf(HERE, "too many arguments to function '%E'", expression);
6266                 }
6267         }
6268
6269         /* do default promotion */
6270         for( ; argument != NULL; argument = argument->next) {
6271                 type_t *type = argument->expression->base.type;
6272
6273                 type = get_default_promoted_type(type);
6274
6275                 argument->expression
6276                         = create_implicit_cast(argument->expression, type);
6277         }
6278
6279         check_format(&result->call);
6280
6281         return result;
6282 end_error:
6283         return create_invalid_expression();
6284 }
6285
6286 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6287
6288 static bool same_compound_type(const type_t *type1, const type_t *type2)
6289 {
6290         return
6291                 is_type_compound(type1) &&
6292                 type1->kind == type2->kind &&
6293                 type1->compound.declaration == type2->compound.declaration;
6294 }
6295
6296 /**
6297  * Parse a conditional expression, ie. 'expression ? ... : ...'.
6298  *
6299  * @param expression  the conditional expression
6300  */
6301 static expression_t *parse_conditional_expression(unsigned precedence,
6302                                                   expression_t *expression)
6303 {
6304         eat('?');
6305         add_anchor_token(':');
6306
6307         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6308
6309         conditional_expression_t *conditional = &result->conditional;
6310         conditional->condition = expression;
6311
6312         /* 6.5.15.2 */
6313         type_t *const condition_type_orig = expression->base.type;
6314         type_t *const condition_type      = skip_typeref(condition_type_orig);
6315         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6316                 type_error("expected a scalar type in conditional condition",
6317                            &expression->base.source_position, condition_type_orig);
6318         }
6319
6320         expression_t *true_expression = parse_expression();
6321         rem_anchor_token(':');
6322         expect(':');
6323         expression_t *false_expression = parse_sub_expression(precedence);
6324
6325         type_t *const orig_true_type  = true_expression->base.type;
6326         type_t *const orig_false_type = false_expression->base.type;
6327         type_t *const true_type       = skip_typeref(orig_true_type);
6328         type_t *const false_type      = skip_typeref(orig_false_type);
6329
6330         /* 6.5.15.3 */
6331         type_t *result_type;
6332         if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6333                 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6334                 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6335                     || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6336                         warningf(&expression->base.source_position,
6337                                         "ISO C forbids conditional expression with only one void side");
6338                 }
6339                 result_type = type_void;
6340         } else if (is_type_arithmetic(true_type)
6341                    && is_type_arithmetic(false_type)) {
6342                 result_type = semantic_arithmetic(true_type, false_type);
6343
6344                 true_expression  = create_implicit_cast(true_expression, result_type);
6345                 false_expression = create_implicit_cast(false_expression, result_type);
6346
6347                 conditional->true_expression  = true_expression;
6348                 conditional->false_expression = false_expression;
6349                 conditional->base.type        = result_type;
6350         } else if (same_compound_type(true_type, false_type)) {
6351                 /* just take 1 of the 2 types */
6352                 result_type = true_type;
6353         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6354                 type_t *pointer_type;
6355                 type_t *other_type;
6356                 expression_t *other_expression;
6357                 if (is_type_pointer(true_type) &&
6358                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6359                         pointer_type     = true_type;
6360                         other_type       = false_type;
6361                         other_expression = false_expression;
6362                 } else {
6363                         pointer_type     = false_type;
6364                         other_type       = true_type;
6365                         other_expression = true_expression;
6366                 }
6367
6368                 if (is_null_pointer_constant(other_expression)) {
6369                         result_type = pointer_type;
6370                 } else if (is_type_pointer(other_type)) {
6371                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6372                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
6373
6374                         type_t *to;
6375                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6376                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6377                                 to = type_void;
6378                         } else if (types_compatible(get_unqualified_type(to1),
6379                                                     get_unqualified_type(to2))) {
6380                                 to = to1;
6381                         } else {
6382                                 warningf(&expression->base.source_position,
6383                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
6384                                         true_type, false_type);
6385                                 to = type_void;
6386                         }
6387
6388                         type_t *const copy = duplicate_type(to);
6389                         copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6390
6391                         type_t *const type = typehash_insert(copy);
6392                         if (type != copy)
6393                                 free_type(copy);
6394
6395                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6396                 } else if (is_type_integer(other_type)) {
6397                         warningf(&expression->base.source_position,
6398                                         "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6399                         result_type = pointer_type;
6400                 } else {
6401                         type_error_incompatible("while parsing conditional",
6402                                         &expression->base.source_position, true_type, false_type);
6403                         result_type = type_error_type;
6404                 }
6405         } else {
6406                 /* TODO: one pointer to void*, other some pointer */
6407
6408                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6409                         type_error_incompatible("while parsing conditional",
6410                                                 &expression->base.source_position, true_type,
6411                                                 false_type);
6412                 }
6413                 result_type = type_error_type;
6414         }
6415
6416         conditional->true_expression
6417                 = create_implicit_cast(true_expression, result_type);
6418         conditional->false_expression
6419                 = create_implicit_cast(false_expression, result_type);
6420         conditional->base.type = result_type;
6421         return result;
6422 end_error:
6423         return create_invalid_expression();
6424 }
6425
6426 /**
6427  * Parse an extension expression.
6428  */
6429 static expression_t *parse_extension(unsigned precedence)
6430 {
6431         eat(T___extension__);
6432
6433         /* TODO enable extensions */
6434         expression_t *expression = parse_sub_expression(precedence);
6435         /* TODO disable extensions */
6436         return expression;
6437 }
6438
6439 /**
6440  * Parse a __builtin_classify_type() expression.
6441  */
6442 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6443 {
6444         eat(T___builtin_classify_type);
6445
6446         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6447         result->base.type    = type_int;
6448
6449         expect('(');
6450         add_anchor_token(')');
6451         expression_t *expression = parse_sub_expression(precedence);
6452         rem_anchor_token(')');
6453         expect(')');
6454         result->classify_type.type_expression = expression;
6455
6456         return result;
6457 end_error:
6458         return create_invalid_expression();
6459 }
6460
6461 static void check_pointer_arithmetic(const source_position_t *source_position,
6462                                      type_t *pointer_type,
6463                                      type_t *orig_pointer_type)
6464 {
6465         type_t *points_to = pointer_type->pointer.points_to;
6466         points_to = skip_typeref(points_to);
6467
6468         if (is_type_incomplete(points_to) &&
6469                         (! (c_mode & _GNUC)
6470                          || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6471                 errorf(source_position,
6472                            "arithmetic with pointer to incomplete type '%T' not allowed",
6473                            orig_pointer_type);
6474         } else if (is_type_function(points_to)) {
6475                 errorf(source_position,
6476                            "arithmetic with pointer to function type '%T' not allowed",
6477                            orig_pointer_type);
6478         }
6479 }
6480
6481 static void semantic_incdec(unary_expression_t *expression)
6482 {
6483         type_t *const orig_type = expression->value->base.type;
6484         type_t *const type      = skip_typeref(orig_type);
6485         if (is_type_pointer(type)) {
6486                 check_pointer_arithmetic(&expression->base.source_position,
6487                                          type, orig_type);
6488         } else if (!is_type_real(type) && is_type_valid(type)) {
6489                 /* TODO: improve error message */
6490                 errorf(HERE, "operation needs an arithmetic or pointer type");
6491         }
6492         expression->base.type = orig_type;
6493 }
6494
6495 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6496 {
6497         type_t *const orig_type = expression->value->base.type;
6498         type_t *const type      = skip_typeref(orig_type);
6499         if (!is_type_arithmetic(type)) {
6500                 if (is_type_valid(type)) {
6501                         /* TODO: improve error message */
6502                         errorf(HERE, "operation needs an arithmetic type");
6503                 }
6504                 return;
6505         }
6506
6507         expression->base.type = orig_type;
6508 }
6509
6510 static void semantic_unexpr_scalar(unary_expression_t *expression)
6511 {
6512         type_t *const orig_type = expression->value->base.type;
6513         type_t *const type      = skip_typeref(orig_type);
6514         if (!is_type_scalar(type)) {
6515                 if (is_type_valid(type)) {
6516                         errorf(HERE, "operand of ! must be of scalar type");
6517                 }
6518                 return;
6519         }
6520
6521         expression->base.type = orig_type;
6522 }
6523
6524 static void semantic_unexpr_integer(unary_expression_t *expression)
6525 {
6526         type_t *const orig_type = expression->value->base.type;
6527         type_t *const type      = skip_typeref(orig_type);
6528         if (!is_type_integer(type)) {
6529                 if (is_type_valid(type)) {
6530                         errorf(HERE, "operand of ~ must be of integer type");
6531                 }
6532                 return;
6533         }
6534
6535         expression->base.type = orig_type;
6536 }
6537
6538 static void semantic_dereference(unary_expression_t *expression)
6539 {
6540         type_t *const orig_type = expression->value->base.type;
6541         type_t *const type      = skip_typeref(orig_type);
6542         if (!is_type_pointer(type)) {
6543                 if (is_type_valid(type)) {
6544                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6545                 }
6546                 return;
6547         }
6548
6549         type_t *result_type   = type->pointer.points_to;
6550         result_type           = automatic_type_conversion(result_type);
6551         expression->base.type = result_type;
6552 }
6553
6554 static void set_address_taken(expression_t *expression, bool may_be_register)
6555 {
6556         if (expression->kind != EXPR_REFERENCE)
6557                 return;
6558
6559         declaration_t *const declaration = expression->reference.declaration;
6560         /* happens for parse errors */
6561         if (declaration == NULL)
6562                 return;
6563
6564         if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6565                 errorf(&expression->base.source_position,
6566                                 "address of register variable '%Y' requested",
6567                                 declaration->symbol);
6568         } else {
6569                 declaration->address_taken = 1;
6570         }
6571 }
6572
6573 /**
6574  * Check the semantic of the address taken expression.
6575  */
6576 static void semantic_take_addr(unary_expression_t *expression)
6577 {
6578         expression_t *value = expression->value;
6579         value->base.type    = revert_automatic_type_conversion(value);
6580
6581         type_t *orig_type = value->base.type;
6582         if (!is_type_valid(orig_type))
6583                 return;
6584
6585         set_address_taken(value, false);
6586
6587         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6588 }
6589
6590 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
6591 static expression_t *parse_##unexpression_type(unsigned precedence)            \
6592 {                                                                              \
6593         eat(token_type);                                                           \
6594                                                                                    \
6595         expression_t *unary_expression                                             \
6596                 = allocate_expression_zero(unexpression_type);                         \
6597         unary_expression->base.source_position = *HERE;                            \
6598         unary_expression->unary.value = parse_sub_expression(precedence);          \
6599                                                                                    \
6600         sfunc(&unary_expression->unary);                                           \
6601                                                                                    \
6602         return unary_expression;                                                   \
6603 }
6604
6605 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6606                                semantic_unexpr_arithmetic)
6607 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6608                                semantic_unexpr_arithmetic)
6609 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6610                                semantic_unexpr_scalar)
6611 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6612                                semantic_dereference)
6613 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6614                                semantic_take_addr)
6615 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6616                                semantic_unexpr_integer)
6617 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
6618                                semantic_incdec)
6619 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6620                                semantic_incdec)
6621
6622 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6623                                                sfunc)                         \
6624 static expression_t *parse_##unexpression_type(unsigned precedence,           \
6625                                                expression_t *left)            \
6626 {                                                                             \
6627         (void) precedence;                                                        \
6628         eat(token_type);                                                          \
6629                                                                               \
6630         expression_t *unary_expression                                            \
6631                 = allocate_expression_zero(unexpression_type);                        \
6632         unary_expression->unary.value = left;                                     \
6633                                                                                   \
6634         sfunc(&unary_expression->unary);                                          \
6635                                                                               \
6636         return unary_expression;                                                  \
6637 }
6638
6639 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6640                                        EXPR_UNARY_POSTFIX_INCREMENT,
6641                                        semantic_incdec)
6642 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6643                                        EXPR_UNARY_POSTFIX_DECREMENT,
6644                                        semantic_incdec)
6645
6646 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6647 {
6648         /* TODO: handle complex + imaginary types */
6649
6650         /* Â§ 6.3.1.8 Usual arithmetic conversions */
6651         if (type_left == type_long_double || type_right == type_long_double) {
6652                 return type_long_double;
6653         } else if (type_left == type_double || type_right == type_double) {
6654                 return type_double;
6655         } else if (type_left == type_float || type_right == type_float) {
6656                 return type_float;
6657         }
6658
6659         type_left  = promote_integer(type_left);
6660         type_right = promote_integer(type_right);
6661
6662         if (type_left == type_right)
6663                 return type_left;
6664
6665         bool const signed_left  = is_type_signed(type_left);
6666         bool const signed_right = is_type_signed(type_right);
6667         int  const rank_left    = get_rank(type_left);
6668         int  const rank_right   = get_rank(type_right);
6669
6670         if (signed_left == signed_right)
6671                 return rank_left >= rank_right ? type_left : type_right;
6672
6673         int     s_rank;
6674         int     u_rank;
6675         type_t *s_type;
6676         type_t *u_type;
6677         if (signed_left) {
6678                 s_rank = rank_left;
6679                 s_type = type_left;
6680                 u_rank = rank_right;
6681                 u_type = type_right;
6682         } else {
6683                 s_rank = rank_right;
6684                 s_type = type_right;
6685                 u_rank = rank_left;
6686                 u_type = type_left;
6687         }
6688
6689         if (u_rank >= s_rank)
6690                 return u_type;
6691
6692         if (get_atomic_type_size(s_rank) > get_atomic_type_size(u_rank))
6693                 return s_type;
6694
6695         /* FIXME ugly */
6696         type_t *const type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
6697         switch (s_rank) {
6698                 case ATOMIC_TYPE_INT:      type->atomic.akind = ATOMIC_TYPE_UINT;      break;
6699                 case ATOMIC_TYPE_LONG:     type->atomic.akind = ATOMIC_TYPE_ULONG;     break;
6700                 case ATOMIC_TYPE_LONGLONG: type->atomic.akind = ATOMIC_TYPE_ULONGLONG; break;
6701
6702                 default: panic("invalid atomic type");
6703         }
6704
6705         type_t* const result = typehash_insert(type);
6706         if (result != type)
6707                 free_type(type);
6708
6709         return result;
6710 }
6711
6712 /**
6713  * Check the semantic restrictions for a binary expression.
6714  */
6715 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6716 {
6717         expression_t *const left            = expression->left;
6718         expression_t *const right           = expression->right;
6719         type_t       *const orig_type_left  = left->base.type;
6720         type_t       *const orig_type_right = right->base.type;
6721         type_t       *const type_left       = skip_typeref(orig_type_left);
6722         type_t       *const type_right      = skip_typeref(orig_type_right);
6723
6724         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6725                 /* TODO: improve error message */
6726                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6727                         errorf(HERE, "operation needs arithmetic types");
6728                 }
6729                 return;
6730         }
6731
6732         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6733         expression->left      = create_implicit_cast(left, arithmetic_type);
6734         expression->right     = create_implicit_cast(right, arithmetic_type);
6735         expression->base.type = arithmetic_type;
6736 }
6737
6738 static void semantic_shift_op(binary_expression_t *expression)
6739 {
6740         expression_t *const left            = expression->left;
6741         expression_t *const right           = expression->right;
6742         type_t       *const orig_type_left  = left->base.type;
6743         type_t       *const orig_type_right = right->base.type;
6744         type_t       *      type_left       = skip_typeref(orig_type_left);
6745         type_t       *      type_right      = skip_typeref(orig_type_right);
6746
6747         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6748                 /* TODO: improve error message */
6749                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6750                         errorf(HERE, "operation needs integer types");
6751                 }
6752                 return;
6753         }
6754
6755         type_left  = promote_integer(type_left);
6756         type_right = promote_integer(type_right);
6757
6758         expression->left      = create_implicit_cast(left, type_left);
6759         expression->right     = create_implicit_cast(right, type_right);
6760         expression->base.type = type_left;
6761 }
6762
6763 static void semantic_add(binary_expression_t *expression)
6764 {
6765         expression_t *const left            = expression->left;
6766         expression_t *const right           = expression->right;
6767         type_t       *const orig_type_left  = left->base.type;
6768         type_t       *const orig_type_right = right->base.type;
6769         type_t       *const type_left       = skip_typeref(orig_type_left);
6770         type_t       *const type_right      = skip_typeref(orig_type_right);
6771
6772         /* Â§ 6.5.6 */
6773         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6774                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6775                 expression->left  = create_implicit_cast(left, arithmetic_type);
6776                 expression->right = create_implicit_cast(right, arithmetic_type);
6777                 expression->base.type = arithmetic_type;
6778                 return;
6779         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6780                 check_pointer_arithmetic(&expression->base.source_position,
6781                                          type_left, orig_type_left);
6782                 expression->base.type = type_left;
6783         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6784                 check_pointer_arithmetic(&expression->base.source_position,
6785                                          type_right, orig_type_right);
6786                 expression->base.type = type_right;
6787         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6788                 errorf(&expression->base.source_position,
6789                        "invalid operands to binary + ('%T', '%T')",
6790                        orig_type_left, orig_type_right);
6791         }
6792 }
6793
6794 static void semantic_sub(binary_expression_t *expression)
6795 {
6796         expression_t *const left            = expression->left;
6797         expression_t *const right           = expression->right;
6798         type_t       *const orig_type_left  = left->base.type;
6799         type_t       *const orig_type_right = right->base.type;
6800         type_t       *const type_left       = skip_typeref(orig_type_left);
6801         type_t       *const type_right      = skip_typeref(orig_type_right);
6802
6803         /* Â§ 5.6.5 */
6804         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6805                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6806                 expression->left        = create_implicit_cast(left, arithmetic_type);
6807                 expression->right       = create_implicit_cast(right, arithmetic_type);
6808                 expression->base.type =  arithmetic_type;
6809                 return;
6810         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6811                 check_pointer_arithmetic(&expression->base.source_position,
6812                                          type_left, orig_type_left);
6813                 expression->base.type = type_left;
6814         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6815                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6816                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6817                 if (!types_compatible(unqual_left, unqual_right)) {
6818                         errorf(&expression->base.source_position,
6819                                "subtracting pointers to incompatible types '%T' and '%T'",
6820                                orig_type_left, orig_type_right);
6821                 } else if (!is_type_object(unqual_left)) {
6822                         if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6823                                 warningf(&expression->base.source_position,
6824                                          "subtracting pointers to void");
6825                         } else {
6826                                 errorf(&expression->base.source_position,
6827                                        "subtracting pointers to non-object types '%T'",
6828                                        orig_type_left);
6829                         }
6830                 }
6831                 expression->base.type = type_ptrdiff_t;
6832         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6833                 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6834                        orig_type_left, orig_type_right);
6835         }
6836 }
6837
6838 /**
6839  * Check the semantics of comparison expressions.
6840  *
6841  * @param expression   The expression to check.
6842  */
6843 static void semantic_comparison(binary_expression_t *expression)
6844 {
6845         expression_t *left            = expression->left;
6846         expression_t *right           = expression->right;
6847         type_t       *orig_type_left  = left->base.type;
6848         type_t       *orig_type_right = right->base.type;
6849
6850         type_t *type_left  = skip_typeref(orig_type_left);
6851         type_t *type_right = skip_typeref(orig_type_right);
6852
6853         /* TODO non-arithmetic types */
6854         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6855                 /* test for signed vs unsigned compares */
6856                 if (warning.sign_compare &&
6857                     (expression->base.kind != EXPR_BINARY_EQUAL &&
6858                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6859                     (is_type_signed(type_left) != is_type_signed(type_right))) {
6860
6861                         /* check if 1 of the operands is a constant, in this case we just
6862                          * check wether we can safely represent the resulting constant in
6863                          * the type of the other operand. */
6864                         expression_t *const_expr = NULL;
6865                         expression_t *other_expr = NULL;
6866
6867                         if (is_constant_expression(left)) {
6868                                 const_expr = left;
6869                                 other_expr = right;
6870                         } else if (is_constant_expression(right)) {
6871                                 const_expr = right;
6872                                 other_expr = left;
6873                         }
6874
6875                         if (const_expr != NULL) {
6876                                 type_t *other_type = skip_typeref(other_expr->base.type);
6877                                 long    val        = fold_constant(const_expr);
6878                                 /* TODO: check if val can be represented by other_type */
6879                                 (void) other_type;
6880                                 (void) val;
6881                         }
6882                         warningf(&expression->base.source_position,
6883                                  "comparison between signed and unsigned");
6884                 }
6885                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6886                 expression->left        = create_implicit_cast(left, arithmetic_type);
6887                 expression->right       = create_implicit_cast(right, arithmetic_type);
6888                 expression->base.type   = arithmetic_type;
6889                 if (warning.float_equal &&
6890                     (expression->base.kind == EXPR_BINARY_EQUAL ||
6891                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6892                     is_type_float(arithmetic_type)) {
6893                         warningf(&expression->base.source_position,
6894                                  "comparing floating point with == or != is unsafe");
6895                 }
6896         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6897                 /* TODO check compatibility */
6898         } else if (is_type_pointer(type_left)) {
6899                 expression->right = create_implicit_cast(right, type_left);
6900         } else if (is_type_pointer(type_right)) {
6901                 expression->left = create_implicit_cast(left, type_right);
6902         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6903                 type_error_incompatible("invalid operands in comparison",
6904                                         &expression->base.source_position,
6905                                         type_left, type_right);
6906         }
6907         expression->base.type = type_int;
6908 }
6909
6910 /**
6911  * Checks if a compound type has constant fields.
6912  */
6913 static bool has_const_fields(const compound_type_t *type)
6914 {
6915         const scope_t       *scope       = &type->declaration->scope;
6916         const declaration_t *declaration = scope->declarations;
6917
6918         for (; declaration != NULL; declaration = declaration->next) {
6919                 if (declaration->namespc != NAMESPACE_NORMAL)
6920                         continue;
6921
6922                 const type_t *decl_type = skip_typeref(declaration->type);
6923                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6924                         return true;
6925         }
6926         /* TODO */
6927         return false;
6928 }
6929
6930 static bool is_lvalue(const expression_t *expression)
6931 {
6932         switch (expression->kind) {
6933         case EXPR_REFERENCE:
6934         case EXPR_ARRAY_ACCESS:
6935         case EXPR_SELECT:
6936         case EXPR_UNARY_DEREFERENCE:
6937                 return true;
6938
6939         default:
6940                 return false;
6941         }
6942 }
6943
6944 static bool is_valid_assignment_lhs(expression_t const* const left)
6945 {
6946         type_t *const orig_type_left = revert_automatic_type_conversion(left);
6947         type_t *const type_left      = skip_typeref(orig_type_left);
6948
6949         if (!is_lvalue(left)) {
6950                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6951                        left);
6952                 return false;
6953         }
6954
6955         if (is_type_array(type_left)) {
6956                 errorf(HERE, "cannot assign to arrays ('%E')", left);
6957                 return false;
6958         }
6959         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6960                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6961                        orig_type_left);
6962                 return false;
6963         }
6964         if (is_type_incomplete(type_left)) {
6965                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6966                        left, orig_type_left);
6967                 return false;
6968         }
6969         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6970                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6971                        left, orig_type_left);
6972                 return false;
6973         }
6974
6975         return true;
6976 }
6977
6978 static void semantic_arithmetic_assign(binary_expression_t *expression)
6979 {
6980         expression_t *left            = expression->left;
6981         expression_t *right           = expression->right;
6982         type_t       *orig_type_left  = left->base.type;
6983         type_t       *orig_type_right = right->base.type;
6984
6985         if (!is_valid_assignment_lhs(left))
6986                 return;
6987
6988         type_t *type_left  = skip_typeref(orig_type_left);
6989         type_t *type_right = skip_typeref(orig_type_right);
6990
6991         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6992                 /* TODO: improve error message */
6993                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6994                         errorf(HERE, "operation needs arithmetic types");
6995                 }
6996                 return;
6997         }
6998
6999         /* combined instructions are tricky. We can't create an implicit cast on
7000          * the left side, because we need the uncasted form for the store.
7001          * The ast2firm pass has to know that left_type must be right_type
7002          * for the arithmetic operation and create a cast by itself */
7003         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7004         expression->right       = create_implicit_cast(right, arithmetic_type);
7005         expression->base.type   = type_left;
7006 }
7007
7008 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7009 {
7010         expression_t *const left            = expression->left;
7011         expression_t *const right           = expression->right;
7012         type_t       *const orig_type_left  = left->base.type;
7013         type_t       *const orig_type_right = right->base.type;
7014         type_t       *const type_left       = skip_typeref(orig_type_left);
7015         type_t       *const type_right      = skip_typeref(orig_type_right);
7016
7017         if (!is_valid_assignment_lhs(left))
7018                 return;
7019
7020         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7021                 /* combined instructions are tricky. We can't create an implicit cast on
7022                  * the left side, because we need the uncasted form for the store.
7023                  * The ast2firm pass has to know that left_type must be right_type
7024                  * for the arithmetic operation and create a cast by itself */
7025                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7026                 expression->right     = create_implicit_cast(right, arithmetic_type);
7027                 expression->base.type = type_left;
7028         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7029                 check_pointer_arithmetic(&expression->base.source_position,
7030                                          type_left, orig_type_left);
7031                 expression->base.type = type_left;
7032         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7033                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
7034         }
7035 }
7036
7037 /**
7038  * Check the semantic restrictions of a logical expression.
7039  */
7040 static void semantic_logical_op(binary_expression_t *expression)
7041 {
7042         expression_t *const left            = expression->left;
7043         expression_t *const right           = expression->right;
7044         type_t       *const orig_type_left  = left->base.type;
7045         type_t       *const orig_type_right = right->base.type;
7046         type_t       *const type_left       = skip_typeref(orig_type_left);
7047         type_t       *const type_right      = skip_typeref(orig_type_right);
7048
7049         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7050                 /* TODO: improve error message */
7051                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7052                         errorf(HERE, "operation needs scalar types");
7053                 }
7054                 return;
7055         }
7056
7057         expression->base.type = type_int;
7058 }
7059
7060 /**
7061  * Check the semantic restrictions of a binary assign expression.
7062  */
7063 static void semantic_binexpr_assign(binary_expression_t *expression)
7064 {
7065         expression_t *left           = expression->left;
7066         type_t       *orig_type_left = left->base.type;
7067
7068         type_t *type_left = revert_automatic_type_conversion(left);
7069         type_left         = skip_typeref(orig_type_left);
7070
7071         if (!is_valid_assignment_lhs(left))
7072                 return;
7073
7074         assign_error_t error = semantic_assign(orig_type_left, expression->right);
7075         report_assign_error(error, orig_type_left, expression->right,
7076                         "assignment", &left->base.source_position);
7077         expression->right = create_implicit_cast(expression->right, orig_type_left);
7078         expression->base.type = orig_type_left;
7079 }
7080
7081 /**
7082  * Determine if the outermost operation (or parts thereof) of the given
7083  * expression has no effect in order to generate a warning about this fact.
7084  * Therefore in some cases this only examines some of the operands of the
7085  * expression (see comments in the function and examples below).
7086  * Examples:
7087  *   f() + 23;    // warning, because + has no effect
7088  *   x || f();    // no warning, because x controls execution of f()
7089  *   x ? y : f(); // warning, because y has no effect
7090  *   (void)x;     // no warning to be able to suppress the warning
7091  * This function can NOT be used for an "expression has definitely no effect"-
7092  * analysis. */
7093 static bool expression_has_effect(const expression_t *const expr)
7094 {
7095         switch (expr->kind) {
7096                 case EXPR_UNKNOWN:                   break;
7097                 case EXPR_INVALID:                   return true; /* do NOT warn */
7098                 case EXPR_REFERENCE:                 return false;
7099                 /* suppress the warning for microsoft __noop operations */
7100                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
7101                 case EXPR_CHARACTER_CONSTANT:        return false;
7102                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
7103                 case EXPR_STRING_LITERAL:            return false;
7104                 case EXPR_WIDE_STRING_LITERAL:       return false;
7105
7106                 case EXPR_CALL: {
7107                         const call_expression_t *const call = &expr->call;
7108                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7109                                 return true;
7110
7111                         switch (call->function->builtin_symbol.symbol->ID) {
7112                                 case T___builtin_va_end: return true;
7113                                 default:                 return false;
7114                         }
7115                 }
7116
7117                 /* Generate the warning if either the left or right hand side of a
7118                  * conditional expression has no effect */
7119                 case EXPR_CONDITIONAL: {
7120                         const conditional_expression_t *const cond = &expr->conditional;
7121                         return
7122                                 expression_has_effect(cond->true_expression) &&
7123                                 expression_has_effect(cond->false_expression);
7124                 }
7125
7126                 case EXPR_SELECT:                    return false;
7127                 case EXPR_ARRAY_ACCESS:              return false;
7128                 case EXPR_SIZEOF:                    return false;
7129                 case EXPR_CLASSIFY_TYPE:             return false;
7130                 case EXPR_ALIGNOF:                   return false;
7131
7132                 case EXPR_FUNCNAME:                  return false;
7133                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
7134                 case EXPR_BUILTIN_CONSTANT_P:        return false;
7135                 case EXPR_BUILTIN_PREFETCH:          return true;
7136                 case EXPR_OFFSETOF:                  return false;
7137                 case EXPR_VA_START:                  return true;
7138                 case EXPR_VA_ARG:                    return true;
7139                 case EXPR_STATEMENT:                 return true; // TODO
7140                 case EXPR_COMPOUND_LITERAL:          return false;
7141
7142                 case EXPR_UNARY_NEGATE:              return false;
7143                 case EXPR_UNARY_PLUS:                return false;
7144                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
7145                 case EXPR_UNARY_NOT:                 return false;
7146                 case EXPR_UNARY_DEREFERENCE:         return false;
7147                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
7148                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
7149                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
7150                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
7151                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
7152
7153                 /* Treat void casts as if they have an effect in order to being able to
7154                  * suppress the warning */
7155                 case EXPR_UNARY_CAST: {
7156                         type_t *const type = skip_typeref(expr->base.type);
7157                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
7158                 }
7159
7160                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
7161                 case EXPR_UNARY_ASSUME:              return true;
7162
7163                 case EXPR_BINARY_ADD:                return false;
7164                 case EXPR_BINARY_SUB:                return false;
7165                 case EXPR_BINARY_MUL:                return false;
7166                 case EXPR_BINARY_DIV:                return false;
7167                 case EXPR_BINARY_MOD:                return false;
7168                 case EXPR_BINARY_EQUAL:              return false;
7169                 case EXPR_BINARY_NOTEQUAL:           return false;
7170                 case EXPR_BINARY_LESS:               return false;
7171                 case EXPR_BINARY_LESSEQUAL:          return false;
7172                 case EXPR_BINARY_GREATER:            return false;
7173                 case EXPR_BINARY_GREATEREQUAL:       return false;
7174                 case EXPR_BINARY_BITWISE_AND:        return false;
7175                 case EXPR_BINARY_BITWISE_OR:         return false;
7176                 case EXPR_BINARY_BITWISE_XOR:        return false;
7177                 case EXPR_BINARY_SHIFTLEFT:          return false;
7178                 case EXPR_BINARY_SHIFTRIGHT:         return false;
7179                 case EXPR_BINARY_ASSIGN:             return true;
7180                 case EXPR_BINARY_MUL_ASSIGN:         return true;
7181                 case EXPR_BINARY_DIV_ASSIGN:         return true;
7182                 case EXPR_BINARY_MOD_ASSIGN:         return true;
7183                 case EXPR_BINARY_ADD_ASSIGN:         return true;
7184                 case EXPR_BINARY_SUB_ASSIGN:         return true;
7185                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
7186                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
7187                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7188                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7189                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
7190
7191                 /* Only examine the right hand side of && and ||, because the left hand
7192                  * side already has the effect of controlling the execution of the right
7193                  * hand side */
7194                 case EXPR_BINARY_LOGICAL_AND:
7195                 case EXPR_BINARY_LOGICAL_OR:
7196                 /* Only examine the right hand side of a comma expression, because the left
7197                  * hand side has a separate warning */
7198                 case EXPR_BINARY_COMMA:
7199                         return expression_has_effect(expr->binary.right);
7200
7201                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
7202                 case EXPR_BINARY_ISGREATER:          return false;
7203                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
7204                 case EXPR_BINARY_ISLESS:             return false;
7205                 case EXPR_BINARY_ISLESSEQUAL:        return false;
7206                 case EXPR_BINARY_ISLESSGREATER:      return false;
7207                 case EXPR_BINARY_ISUNORDERED:        return false;
7208         }
7209
7210         internal_errorf(HERE, "unexpected expression");
7211 }
7212
7213 static void semantic_comma(binary_expression_t *expression)
7214 {
7215         if (warning.unused_value) {
7216                 const expression_t *const left = expression->left;
7217                 if (!expression_has_effect(left)) {
7218                         warningf(&left->base.source_position,
7219                                  "left-hand operand of comma expression has no effect");
7220                 }
7221         }
7222         expression->base.type = expression->right->base.type;
7223 }
7224
7225 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
7226 static expression_t *parse_##binexpression_type(unsigned precedence,      \
7227                                                 expression_t *left)       \
7228 {                                                                         \
7229         eat(token_type);                                                      \
7230         source_position_t pos = *HERE;                                        \
7231                                                                           \
7232         expression_t *right = parse_sub_expression(precedence + lr);          \
7233                                                                           \
7234         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7235         binexpr->base.source_position = pos;                                  \
7236         binexpr->binary.left  = left;                                         \
7237         binexpr->binary.right = right;                                        \
7238         sfunc(&binexpr->binary);                                              \
7239                                                                           \
7240         return binexpr;                                                       \
7241 }
7242
7243 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
7244 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
7245 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
7246 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
7247 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
7248 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
7249 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
7250 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
7251 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
7252
7253 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
7254                       semantic_comparison, 1)
7255 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7256                       semantic_comparison, 1)
7257 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
7258                       semantic_comparison, 1)
7259 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
7260                       semantic_comparison, 1)
7261
7262 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7263                       semantic_binexpr_arithmetic, 1)
7264 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7265                       semantic_binexpr_arithmetic, 1)
7266 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7267                       semantic_binexpr_arithmetic, 1)
7268 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7269                       semantic_logical_op, 1)
7270 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7271                       semantic_logical_op, 1)
7272 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7273                       semantic_shift_op, 1)
7274 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7275                       semantic_shift_op, 1)
7276 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7277                       semantic_arithmetic_addsubb_assign, 0)
7278 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7279                       semantic_arithmetic_addsubb_assign, 0)
7280 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7281                       semantic_arithmetic_assign, 0)
7282 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7283                       semantic_arithmetic_assign, 0)
7284 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7285                       semantic_arithmetic_assign, 0)
7286 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7287                       semantic_arithmetic_assign, 0)
7288 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7289                       semantic_arithmetic_assign, 0)
7290 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7291                       semantic_arithmetic_assign, 0)
7292 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7293                       semantic_arithmetic_assign, 0)
7294 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7295                       semantic_arithmetic_assign, 0)
7296
7297 static expression_t *parse_sub_expression(unsigned precedence)
7298 {
7299         if (token.type < 0) {
7300                 return expected_expression_error();
7301         }
7302
7303         expression_parser_function_t *parser
7304                 = &expression_parsers[token.type];
7305         source_position_t             source_position = token.source_position;
7306         expression_t                 *left;
7307
7308         if (parser->parser != NULL) {
7309                 left = parser->parser(parser->precedence);
7310         } else {
7311                 left = parse_primary_expression();
7312         }
7313         assert(left != NULL);
7314         left->base.source_position = source_position;
7315
7316         while(true) {
7317                 if (token.type < 0) {
7318                         return expected_expression_error();
7319                 }
7320
7321                 parser = &expression_parsers[token.type];
7322                 if (parser->infix_parser == NULL)
7323                         break;
7324                 if (parser->infix_precedence < precedence)
7325                         break;
7326
7327                 left = parser->infix_parser(parser->infix_precedence, left);
7328
7329                 assert(left != NULL);
7330                 assert(left->kind != EXPR_UNKNOWN);
7331                 left->base.source_position = source_position;
7332         }
7333
7334         return left;
7335 }
7336
7337 /**
7338  * Parse an expression.
7339  */
7340 static expression_t *parse_expression(void)
7341 {
7342         return parse_sub_expression(1);
7343 }
7344
7345 /**
7346  * Register a parser for a prefix-like operator with given precedence.
7347  *
7348  * @param parser      the parser function
7349  * @param token_type  the token type of the prefix token
7350  * @param precedence  the precedence of the operator
7351  */
7352 static void register_expression_parser(parse_expression_function parser,
7353                                        int token_type, unsigned precedence)
7354 {
7355         expression_parser_function_t *entry = &expression_parsers[token_type];
7356
7357         if (entry->parser != NULL) {
7358                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7359                 panic("trying to register multiple expression parsers for a token");
7360         }
7361         entry->parser     = parser;
7362         entry->precedence = precedence;
7363 }
7364
7365 /**
7366  * Register a parser for an infix operator with given precedence.
7367  *
7368  * @param parser      the parser function
7369  * @param token_type  the token type of the infix operator
7370  * @param precedence  the precedence of the operator
7371  */
7372 static void register_infix_parser(parse_expression_infix_function parser,
7373                 int token_type, unsigned precedence)
7374 {
7375         expression_parser_function_t *entry = &expression_parsers[token_type];
7376
7377         if (entry->infix_parser != NULL) {
7378                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7379                 panic("trying to register multiple infix expression parsers for a "
7380                       "token");
7381         }
7382         entry->infix_parser     = parser;
7383         entry->infix_precedence = precedence;
7384 }
7385
7386 /**
7387  * Initialize the expression parsers.
7388  */
7389 static void init_expression_parsers(void)
7390 {
7391         memset(&expression_parsers, 0, sizeof(expression_parsers));
7392
7393         register_infix_parser(parse_array_expression,         '[',              30);
7394         register_infix_parser(parse_call_expression,          '(',              30);
7395         register_infix_parser(parse_select_expression,        '.',              30);
7396         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
7397         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7398                                                               T_PLUSPLUS,       30);
7399         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7400                                                               T_MINUSMINUS,     30);
7401
7402         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              17);
7403         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              17);
7404         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              17);
7405         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              16);
7406         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              16);
7407         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       15);
7408         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 15);
7409         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
7410         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
7411         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
7412         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
7413         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
7414         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7415                                                     T_EXCLAMATIONMARKEQUAL, 13);
7416         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
7417         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
7418         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
7419         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
7420         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
7421         register_infix_parser(parse_conditional_expression,   '?',               7);
7422         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
7423         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
7424         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
7425         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
7426         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
7427         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
7428         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7429                                                                 T_LESSLESSEQUAL, 2);
7430         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7431                                                           T_GREATERGREATEREQUAL, 2);
7432         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7433                                                                      T_ANDEQUAL, 2);
7434         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7435                                                                     T_PIPEEQUAL, 2);
7436         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7437                                                                    T_CARETEQUAL, 2);
7438
7439         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
7440
7441         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
7442         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
7443         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
7444         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
7445         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
7446         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
7447         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7448                                                                   T_PLUSPLUS,   25);
7449         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7450                                                                   T_MINUSMINUS, 25);
7451         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
7452         register_expression_parser(parse_alignof,                T___alignof__, 25);
7453         register_expression_parser(parse_extension,            T___extension__, 25);
7454         register_expression_parser(parse_builtin_classify_type,
7455                                                      T___builtin_classify_type, 25);
7456 }
7457
7458 /**
7459  * Parse a asm statement arguments specification.
7460  */
7461 static asm_argument_t *parse_asm_arguments(bool is_out)
7462 {
7463         asm_argument_t *result = NULL;
7464         asm_argument_t *last   = NULL;
7465
7466         while (token.type == T_STRING_LITERAL || token.type == '[') {
7467                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7468                 memset(argument, 0, sizeof(argument[0]));
7469
7470                 if (token.type == '[') {
7471                         eat('[');
7472                         if (token.type != T_IDENTIFIER) {
7473                                 parse_error_expected("while parsing asm argument",
7474                                                      T_IDENTIFIER, NULL);
7475                                 return NULL;
7476                         }
7477                         argument->symbol = token.v.symbol;
7478
7479                         expect(']');
7480                 }
7481
7482                 argument->constraints = parse_string_literals();
7483                 expect('(');
7484                 add_anchor_token(')');
7485                 expression_t *expression = parse_expression();
7486                 rem_anchor_token(')');
7487                 if (is_out) {
7488                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
7489                          * change size or type representation (e.g. int -> long is ok, but
7490                          * int -> float is not) */
7491                         if (expression->kind == EXPR_UNARY_CAST) {
7492                                 type_t      *const type = expression->base.type;
7493                                 type_kind_t  const kind = type->kind;
7494                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
7495                                         unsigned flags;
7496                                         unsigned size;
7497                                         if (kind == TYPE_ATOMIC) {
7498                                                 atomic_type_kind_t const akind = type->atomic.akind;
7499                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
7500                                                 size  = get_atomic_type_size(akind);
7501                                         } else {
7502                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
7503                                                 size  = get_atomic_type_size(get_intptr_kind());
7504                                         }
7505
7506                                         do {
7507                                                 expression_t *const value      = expression->unary.value;
7508                                                 type_t       *const value_type = value->base.type;
7509                                                 type_kind_t   const value_kind = value_type->kind;
7510
7511                                                 unsigned value_flags;
7512                                                 unsigned value_size;
7513                                                 if (value_kind == TYPE_ATOMIC) {
7514                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
7515                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
7516                                                         value_size  = get_atomic_type_size(value_akind);
7517                                                 } else if (value_kind == TYPE_POINTER) {
7518                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
7519                                                         value_size  = get_atomic_type_size(get_intptr_kind());
7520                                                 } else {
7521                                                         break;
7522                                                 }
7523
7524                                                 if (value_flags != flags || value_size != size)
7525                                                         break;
7526
7527                                                 expression = value;
7528                                         } while (expression->kind == EXPR_UNARY_CAST);
7529                                 }
7530                         }
7531
7532                         if (!is_lvalue(expression)) {
7533                                 errorf(&expression->base.source_position,
7534                                        "asm output argument is not an lvalue");
7535                         }
7536                 }
7537                 argument->expression = expression;
7538                 expect(')');
7539
7540                 set_address_taken(expression, true);
7541
7542                 if (last != NULL) {
7543                         last->next = argument;
7544                 } else {
7545                         result = argument;
7546                 }
7547                 last = argument;
7548
7549                 if (token.type != ',')
7550                         break;
7551                 eat(',');
7552         }
7553
7554         return result;
7555 end_error:
7556         return NULL;
7557 }
7558
7559 /**
7560  * Parse a asm statement clobber specification.
7561  */
7562 static asm_clobber_t *parse_asm_clobbers(void)
7563 {
7564         asm_clobber_t *result = NULL;
7565         asm_clobber_t *last   = NULL;
7566
7567         while(token.type == T_STRING_LITERAL) {
7568                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7569                 clobber->clobber       = parse_string_literals();
7570
7571                 if (last != NULL) {
7572                         last->next = clobber;
7573                 } else {
7574                         result = clobber;
7575                 }
7576                 last = clobber;
7577
7578                 if (token.type != ',')
7579                         break;
7580                 eat(',');
7581         }
7582
7583         return result;
7584 }
7585
7586 /**
7587  * Parse an asm statement.
7588  */
7589 static statement_t *parse_asm_statement(void)
7590 {
7591         eat(T_asm);
7592
7593         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
7594         statement->base.source_position = token.source_position;
7595
7596         asm_statement_t *asm_statement = &statement->asms;
7597
7598         if (token.type == T_volatile) {
7599                 next_token();
7600                 asm_statement->is_volatile = true;
7601         }
7602
7603         expect('(');
7604         add_anchor_token(')');
7605         add_anchor_token(':');
7606         asm_statement->asm_text = parse_string_literals();
7607
7608         if (token.type != ':') {
7609                 rem_anchor_token(':');
7610                 goto end_of_asm;
7611         }
7612         eat(':');
7613
7614         asm_statement->outputs = parse_asm_arguments(true);
7615         if (token.type != ':') {
7616                 rem_anchor_token(':');
7617                 goto end_of_asm;
7618         }
7619         eat(':');
7620
7621         asm_statement->inputs = parse_asm_arguments(false);
7622         if (token.type != ':') {
7623                 rem_anchor_token(':');
7624                 goto end_of_asm;
7625         }
7626         rem_anchor_token(':');
7627         eat(':');
7628
7629         asm_statement->clobbers = parse_asm_clobbers();
7630
7631 end_of_asm:
7632         rem_anchor_token(')');
7633         expect(')');
7634         expect(';');
7635
7636         if (asm_statement->outputs == NULL) {
7637                 /* GCC: An 'asm' instruction without any output operands will be treated
7638                  * identically to a volatile 'asm' instruction. */
7639                 asm_statement->is_volatile = true;
7640         }
7641
7642         return statement;
7643 end_error:
7644         return create_invalid_statement();
7645 }
7646
7647 /**
7648  * Parse a case statement.
7649  */
7650 static statement_t *parse_case_statement(void)
7651 {
7652         eat(T_case);
7653
7654         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7655
7656         statement->base.source_position  = token.source_position;
7657         statement->case_label.expression = parse_expression();
7658
7659         if (c_mode & _GNUC) {
7660                 if (token.type == T_DOTDOTDOT) {
7661                         next_token();
7662                         statement->case_label.end_range = parse_expression();
7663                 }
7664         }
7665
7666         expect(':');
7667
7668         if (! is_constant_expression(statement->case_label.expression)) {
7669                 errorf(&statement->base.source_position,
7670                        "case label does not reduce to an integer constant");
7671         } else {
7672                 /* TODO: check if the case label is already known */
7673                 if (current_switch != NULL) {
7674                         /* link all cases into the switch statement */
7675                         if (current_switch->last_case == NULL) {
7676                                 current_switch->first_case =
7677                                 current_switch->last_case  = &statement->case_label;
7678                         } else {
7679                                 current_switch->last_case->next = &statement->case_label;
7680                         }
7681                 } else {
7682                         errorf(&statement->base.source_position,
7683                                "case label not within a switch statement");
7684                 }
7685         }
7686         statement->case_label.statement = parse_statement();
7687
7688         return statement;
7689 end_error:
7690         return create_invalid_statement();
7691 }
7692
7693 /**
7694  * Finds an existing default label of a switch statement.
7695  */
7696 static case_label_statement_t *
7697 find_default_label(const switch_statement_t *statement)
7698 {
7699         case_label_statement_t *label = statement->first_case;
7700         for ( ; label != NULL; label = label->next) {
7701                 if (label->expression == NULL)
7702                         return label;
7703         }
7704         return NULL;
7705 }
7706
7707 /**
7708  * Parse a default statement.
7709  */
7710 static statement_t *parse_default_statement(void)
7711 {
7712         eat(T_default);
7713
7714         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7715
7716         statement->base.source_position = token.source_position;
7717
7718         expect(':');
7719         if (current_switch != NULL) {
7720                 const case_label_statement_t *def_label = find_default_label(current_switch);
7721                 if (def_label != NULL) {
7722                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7723                                &def_label->base.source_position);
7724                 } else {
7725                         /* link all cases into the switch statement */
7726                         if (current_switch->last_case == NULL) {
7727                                 current_switch->first_case =
7728                                         current_switch->last_case  = &statement->case_label;
7729                         } else {
7730                                 current_switch->last_case->next = &statement->case_label;
7731                         }
7732                 }
7733         } else {
7734                 errorf(&statement->base.source_position,
7735                         "'default' label not within a switch statement");
7736         }
7737         statement->case_label.statement = parse_statement();
7738
7739         return statement;
7740 end_error:
7741         return create_invalid_statement();
7742 }
7743
7744 /**
7745  * Return the declaration for a given label symbol or create a new one.
7746  *
7747  * @param symbol  the symbol of the label
7748  */
7749 static declaration_t *get_label(symbol_t *symbol)
7750 {
7751         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7752         assert(current_function != NULL);
7753         /* if we found a label in the same function, then we already created the
7754          * declaration */
7755         if (candidate != NULL
7756                         && candidate->parent_scope == &current_function->scope) {
7757                 return candidate;
7758         }
7759
7760         /* otherwise we need to create a new one */
7761         declaration_t *const declaration = allocate_declaration_zero();
7762         declaration->namespc       = NAMESPACE_LABEL;
7763         declaration->symbol        = symbol;
7764
7765         label_push(declaration);
7766
7767         return declaration;
7768 }
7769
7770 /**
7771  * Parse a label statement.
7772  */
7773 static statement_t *parse_label_statement(void)
7774 {
7775         assert(token.type == T_IDENTIFIER);
7776         symbol_t *symbol = token.v.symbol;
7777         next_token();
7778
7779         declaration_t *label = get_label(symbol);
7780
7781         /* if source position is already set then the label is defined twice,
7782          * otherwise it was just mentioned in a goto so far */
7783         if (label->source_position.input_name != NULL) {
7784                 errorf(HERE, "duplicate label '%Y' (declared %P)",
7785                        symbol, &label->source_position);
7786         } else {
7787                 label->source_position = token.source_position;
7788         }
7789
7790         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7791
7792         statement->base.source_position = token.source_position;
7793         statement->label.label          = label;
7794
7795         eat(':');
7796
7797         if (token.type == '}') {
7798                 /* TODO only warn? */
7799                 if (false) {
7800                         warningf(HERE, "label at end of compound statement");
7801                         statement->label.statement = create_empty_statement();
7802                 } else {
7803                         errorf(HERE, "label at end of compound statement");
7804                         statement->label.statement = create_invalid_statement();
7805                 }
7806         } else if (token.type == ';') {
7807                 /* Eat an empty statement here, to avoid the warning about an empty
7808                  * statement after a label.  label:; is commonly used to have a label
7809                  * before a closing brace. */
7810                 statement->label.statement = create_empty_statement();
7811                 next_token();
7812         } else {
7813                 statement->label.statement = parse_statement();
7814         }
7815
7816         /* remember the labels in a list for later checking */
7817         if (label_last == NULL) {
7818                 label_first = &statement->label;
7819         } else {
7820                 label_last->next = &statement->label;
7821         }
7822         label_last = &statement->label;
7823
7824         return statement;
7825 }
7826
7827 /**
7828  * Parse an if statement.
7829  */
7830 static statement_t *parse_if(void)
7831 {
7832         eat(T_if);
7833
7834         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
7835         statement->base.source_position = token.source_position;
7836
7837         expect('(');
7838         add_anchor_token(')');
7839         statement->ifs.condition = parse_expression();
7840         rem_anchor_token(')');
7841         expect(')');
7842
7843         add_anchor_token(T_else);
7844         statement->ifs.true_statement = parse_statement();
7845         rem_anchor_token(T_else);
7846
7847         if (token.type == T_else) {
7848                 next_token();
7849                 statement->ifs.false_statement = parse_statement();
7850         }
7851
7852         return statement;
7853 end_error:
7854         return create_invalid_statement();
7855 }
7856
7857 /**
7858  * Parse a switch statement.
7859  */
7860 static statement_t *parse_switch(void)
7861 {
7862         eat(T_switch);
7863
7864         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
7865         statement->base.source_position = token.source_position;
7866
7867         expect('(');
7868         expression_t *const expr = parse_expression();
7869         type_t       *      type = skip_typeref(expr->base.type);
7870         if (is_type_integer(type)) {
7871                 type = promote_integer(type);
7872         } else if (is_type_valid(type)) {
7873                 errorf(&expr->base.source_position,
7874                        "switch quantity is not an integer, but '%T'", type);
7875                 type = type_error_type;
7876         }
7877         statement->switchs.expression = create_implicit_cast(expr, type);
7878         expect(')');
7879
7880         switch_statement_t *rem = current_switch;
7881         current_switch          = &statement->switchs;
7882         statement->switchs.body = parse_statement();
7883         current_switch          = rem;
7884
7885         if (warning.switch_default &&
7886            find_default_label(&statement->switchs) == NULL) {
7887                 warningf(&statement->base.source_position, "switch has no default case");
7888         }
7889
7890         return statement;
7891 end_error:
7892         return create_invalid_statement();
7893 }
7894
7895 static statement_t *parse_loop_body(statement_t *const loop)
7896 {
7897         statement_t *const rem = current_loop;
7898         current_loop = loop;
7899
7900         statement_t *const body = parse_statement();
7901
7902         current_loop = rem;
7903         return body;
7904 }
7905
7906 /**
7907  * Parse a while statement.
7908  */
7909 static statement_t *parse_while(void)
7910 {
7911         eat(T_while);
7912
7913         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
7914         statement->base.source_position = token.source_position;
7915
7916         expect('(');
7917         add_anchor_token(')');
7918         statement->whiles.condition = parse_expression();
7919         rem_anchor_token(')');
7920         expect(')');
7921
7922         statement->whiles.body = parse_loop_body(statement);
7923
7924         return statement;
7925 end_error:
7926         return create_invalid_statement();
7927 }
7928
7929 /**
7930  * Parse a do statement.
7931  */
7932 static statement_t *parse_do(void)
7933 {
7934         eat(T_do);
7935
7936         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7937
7938         statement->base.source_position = token.source_position;
7939
7940         add_anchor_token(T_while);
7941         statement->do_while.body = parse_loop_body(statement);
7942         rem_anchor_token(T_while);
7943
7944         expect(T_while);
7945         expect('(');
7946         add_anchor_token(')');
7947         statement->do_while.condition = parse_expression();
7948         rem_anchor_token(')');
7949         expect(')');
7950         expect(';');
7951
7952         return statement;
7953 end_error:
7954         return create_invalid_statement();
7955 }
7956
7957 /**
7958  * Parse a for statement.
7959  */
7960 static statement_t *parse_for(void)
7961 {
7962         eat(T_for);
7963
7964         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
7965         statement->base.source_position = token.source_position;
7966
7967         int      top        = environment_top();
7968         scope_t *last_scope = scope;
7969         set_scope(&statement->fors.scope);
7970
7971         expect('(');
7972         add_anchor_token(')');
7973
7974         if (token.type != ';') {
7975                 if (is_declaration_specifier(&token, false)) {
7976                         parse_declaration(record_declaration);
7977                 } else {
7978                         add_anchor_token(';');
7979                         expression_t *const init = parse_expression();
7980                         statement->fors.initialisation = init;
7981                         if (warning.unused_value && !expression_has_effect(init)) {
7982                                 warningf(&init->base.source_position,
7983                                          "initialisation of 'for'-statement has no effect");
7984                         }
7985                         rem_anchor_token(';');
7986                         expect(';');
7987                 }
7988         } else {
7989                 expect(';');
7990         }
7991
7992         if (token.type != ';') {
7993                 add_anchor_token(';');
7994                 statement->fors.condition = parse_expression();
7995                 rem_anchor_token(';');
7996         }
7997         expect(';');
7998         if (token.type != ')') {
7999                 expression_t *const step = parse_expression();
8000                 statement->fors.step = step;
8001                 if (warning.unused_value && !expression_has_effect(step)) {
8002                         warningf(&step->base.source_position,
8003                                  "step of 'for'-statement has no effect");
8004                 }
8005         }
8006         rem_anchor_token(')');
8007         expect(')');
8008         statement->fors.body = parse_loop_body(statement);
8009
8010         assert(scope == &statement->fors.scope);
8011         set_scope(last_scope);
8012         environment_pop_to(top);
8013
8014         return statement;
8015
8016 end_error:
8017         rem_anchor_token(')');
8018         assert(scope == &statement->fors.scope);
8019         set_scope(last_scope);
8020         environment_pop_to(top);
8021
8022         return create_invalid_statement();
8023 }
8024
8025 /**
8026  * Parse a goto statement.
8027  */
8028 static statement_t *parse_goto(void)
8029 {
8030         eat(T_goto);
8031
8032         if (token.type != T_IDENTIFIER) {
8033                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8034                 eat_statement();
8035                 goto end_error;
8036         }
8037         symbol_t *symbol = token.v.symbol;
8038         next_token();
8039
8040         declaration_t *label = get_label(symbol);
8041
8042         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
8043         statement->base.source_position = token.source_position;
8044
8045         statement->gotos.label = label;
8046
8047         /* remember the goto's in a list for later checking */
8048         if (goto_last == NULL) {
8049                 goto_first = &statement->gotos;
8050         } else {
8051                 goto_last->next = &statement->gotos;
8052         }
8053         goto_last = &statement->gotos;
8054
8055         expect(';');
8056
8057         return statement;
8058 end_error:
8059         return create_invalid_statement();
8060 }
8061
8062 /**
8063  * Parse a continue statement.
8064  */
8065 static statement_t *parse_continue(void)
8066 {
8067         statement_t *statement;
8068         if (current_loop == NULL) {
8069                 errorf(HERE, "continue statement not within loop");
8070                 statement = create_invalid_statement();
8071         } else {
8072                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
8073
8074                 statement->base.source_position = token.source_position;
8075         }
8076
8077         eat(T_continue);
8078         expect(';');
8079
8080         return statement;
8081 end_error:
8082         return create_invalid_statement();
8083 }
8084
8085 /**
8086  * Parse a break statement.
8087  */
8088 static statement_t *parse_break(void)
8089 {
8090         statement_t *statement;
8091         if (current_switch == NULL && current_loop == NULL) {
8092                 errorf(HERE, "break statement not within loop or switch");
8093                 statement = create_invalid_statement();
8094         } else {
8095                 statement = allocate_statement_zero(STATEMENT_BREAK);
8096
8097                 statement->base.source_position = token.source_position;
8098         }
8099
8100         eat(T_break);
8101         expect(';');
8102
8103         return statement;
8104 end_error:
8105         return create_invalid_statement();
8106 }
8107
8108 /**
8109  * Parse a __leave statement.
8110  */
8111 static statement_t *parse_leave(void)
8112 {
8113         statement_t *statement;
8114         if (current_try == NULL) {
8115                 errorf(HERE, "__leave statement not within __try");
8116                 statement = create_invalid_statement();
8117         } else {
8118                 statement = allocate_statement_zero(STATEMENT_LEAVE);
8119
8120                 statement->base.source_position = token.source_position;
8121         }
8122
8123         eat(T___leave);
8124         expect(';');
8125
8126         return statement;
8127 end_error:
8128         return create_invalid_statement();
8129 }
8130
8131 /**
8132  * Check if a given declaration represents a local variable.
8133  */
8134 static bool is_local_var_declaration(const declaration_t *declaration)
8135 {
8136         switch ((storage_class_tag_t) declaration->storage_class) {
8137         case STORAGE_CLASS_AUTO:
8138         case STORAGE_CLASS_REGISTER: {
8139                 const type_t *type = skip_typeref(declaration->type);
8140                 if (is_type_function(type)) {
8141                         return false;
8142                 } else {
8143                         return true;
8144                 }
8145         }
8146         default:
8147                 return false;
8148         }
8149 }
8150
8151 /**
8152  * Check if a given declaration represents a variable.
8153  */
8154 static bool is_var_declaration(const declaration_t *declaration)
8155 {
8156         if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
8157                 return false;
8158
8159         const type_t *type = skip_typeref(declaration->type);
8160         return !is_type_function(type);
8161 }
8162
8163 /**
8164  * Check if a given expression represents a local variable.
8165  */
8166 static bool is_local_variable(const expression_t *expression)
8167 {
8168         if (expression->base.kind != EXPR_REFERENCE) {
8169                 return false;
8170         }
8171         const declaration_t *declaration = expression->reference.declaration;
8172         return is_local_var_declaration(declaration);
8173 }
8174
8175 /**
8176  * Check if a given expression represents a local variable and
8177  * return its declaration then, else return NULL.
8178  */
8179 declaration_t *expr_is_variable(const expression_t *expression)
8180 {
8181         if (expression->base.kind != EXPR_REFERENCE) {
8182                 return NULL;
8183         }
8184         declaration_t *declaration = expression->reference.declaration;
8185         if (is_var_declaration(declaration))
8186                 return declaration;
8187         return NULL;
8188 }
8189
8190 /**
8191  * Parse a return statement.
8192  */
8193 static statement_t *parse_return(void)
8194 {
8195         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
8196         statement->base.source_position = token.source_position;
8197
8198         eat(T_return);
8199
8200         expression_t *return_value = NULL;
8201         if (token.type != ';') {
8202                 return_value = parse_expression();
8203         }
8204         expect(';');
8205
8206         const type_t *const func_type = current_function->type;
8207         assert(is_type_function(func_type));
8208         type_t *const return_type = skip_typeref(func_type->function.return_type);
8209
8210         if (return_value != NULL) {
8211                 type_t *return_value_type = skip_typeref(return_value->base.type);
8212
8213                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8214                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8215                         warningf(&statement->base.source_position,
8216                                  "'return' with a value, in function returning void");
8217                         return_value = NULL;
8218                 } else {
8219                         assign_error_t error = semantic_assign(return_type, return_value);
8220                         report_assign_error(error, return_type, return_value, "'return'",
8221                                             &statement->base.source_position);
8222                         return_value = create_implicit_cast(return_value, return_type);
8223                 }
8224                 /* check for returning address of a local var */
8225                 if (return_value != NULL &&
8226                                 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8227                         const expression_t *expression = return_value->unary.value;
8228                         if (is_local_variable(expression)) {
8229                                 warningf(&statement->base.source_position,
8230                                          "function returns address of local variable");
8231                         }
8232                 }
8233         } else {
8234                 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8235                         warningf(&statement->base.source_position,
8236                                  "'return' without value, in function returning non-void");
8237                 }
8238         }
8239         statement->returns.value = return_value;
8240
8241         return statement;
8242 end_error:
8243         return create_invalid_statement();
8244 }
8245
8246 /**
8247  * Parse a declaration statement.
8248  */
8249 static statement_t *parse_declaration_statement(void)
8250 {
8251         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8252
8253         statement->base.source_position = token.source_position;
8254
8255         declaration_t *before = last_declaration;
8256         parse_declaration(record_declaration);
8257
8258         if (before == NULL) {
8259                 statement->declaration.declarations_begin = scope->declarations;
8260         } else {
8261                 statement->declaration.declarations_begin = before->next;
8262         }
8263         statement->declaration.declarations_end = last_declaration;
8264
8265         return statement;
8266 }
8267
8268 /**
8269  * Parse an expression statement, ie. expr ';'.
8270  */
8271 static statement_t *parse_expression_statement(void)
8272 {
8273         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8274
8275         statement->base.source_position  = token.source_position;
8276         expression_t *const expr         = parse_expression();
8277         statement->expression.expression = expr;
8278
8279         expect(';');
8280
8281         return statement;
8282 end_error:
8283         return create_invalid_statement();
8284 }
8285
8286 /**
8287  * Parse a microsoft __try { } __finally { } or
8288  * __try{ } __except() { }
8289  */
8290 static statement_t *parse_ms_try_statment(void)
8291 {
8292         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8293
8294         statement->base.source_position  = token.source_position;
8295         eat(T___try);
8296
8297         ms_try_statement_t *rem = current_try;
8298         current_try = &statement->ms_try;
8299         statement->ms_try.try_statement = parse_compound_statement(false);
8300         current_try = rem;
8301
8302         if (token.type == T___except) {
8303                 eat(T___except);
8304                 expect('(');
8305                 add_anchor_token(')');
8306                 expression_t *const expr = parse_expression();
8307                 type_t       *      type = skip_typeref(expr->base.type);
8308                 if (is_type_integer(type)) {
8309                         type = promote_integer(type);
8310                 } else if (is_type_valid(type)) {
8311                         errorf(&expr->base.source_position,
8312                                "__expect expression is not an integer, but '%T'", type);
8313                         type = type_error_type;
8314                 }
8315                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8316                 rem_anchor_token(')');
8317                 expect(')');
8318                 statement->ms_try.final_statement = parse_compound_statement(false);
8319         } else if (token.type == T__finally) {
8320                 eat(T___finally);
8321                 statement->ms_try.final_statement = parse_compound_statement(false);
8322         } else {
8323                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8324                 return create_invalid_statement();
8325         }
8326         return statement;
8327 end_error:
8328         return create_invalid_statement();
8329 }
8330
8331 static statement_t *parse_empty_statement(void)
8332 {
8333         if (warning.empty_statement) {
8334                 warningf(HERE, "statement is empty");
8335         }
8336         eat(';');
8337         return create_empty_statement();
8338 }
8339
8340 /**
8341  * Parse a statement.
8342  * There's also parse_statement() which additionally checks for
8343  * "statement has no effect" warnings
8344  */
8345 static statement_t *intern_parse_statement(void)
8346 {
8347         statement_t *statement = NULL;
8348
8349         /* declaration or statement */
8350         add_anchor_token(';');
8351         switch (token.type) {
8352         case T_IDENTIFIER:
8353                 if (look_ahead(1)->type == ':') {
8354                         statement = parse_label_statement();
8355                 } else if (is_typedef_symbol(token.v.symbol)) {
8356                         statement = parse_declaration_statement();
8357                 } else {
8358                         statement = parse_expression_statement();
8359                 }
8360                 break;
8361
8362         case T___extension__:
8363                 /* This can be a prefix to a declaration or an expression statement.
8364                  * We simply eat it now and parse the rest with tail recursion. */
8365                 do {
8366                         next_token();
8367                 } while (token.type == T___extension__);
8368                 statement = parse_statement();
8369                 break;
8370
8371         DECLARATION_START
8372                 statement = parse_declaration_statement();
8373                 break;
8374
8375         case ';':        statement = parse_empty_statement();         break;
8376         case '{':        statement = parse_compound_statement(false); break;
8377         case T___leave:  statement = parse_leave();                   break;
8378         case T___try:    statement = parse_ms_try_statment();         break;
8379         case T_asm:      statement = parse_asm_statement();           break;
8380         case T_break:    statement = parse_break();                   break;
8381         case T_case:     statement = parse_case_statement();          break;
8382         case T_continue: statement = parse_continue();                break;
8383         case T_default:  statement = parse_default_statement();       break;
8384         case T_do:       statement = parse_do();                      break;
8385         case T_for:      statement = parse_for();                     break;
8386         case T_goto:     statement = parse_goto();                    break;
8387         case T_if:       statement = parse_if ();                     break;
8388         case T_return:   statement = parse_return();                  break;
8389         case T_switch:   statement = parse_switch();                  break;
8390         case T_while:    statement = parse_while();                   break;
8391         default:         statement = parse_expression_statement();    break;
8392         }
8393         rem_anchor_token(';');
8394
8395         assert(statement != NULL
8396                         && statement->base.source_position.input_name != NULL);
8397
8398         return statement;
8399 }
8400
8401 /**
8402  * parse a statement and emits "statement has no effect" warning if needed
8403  * (This is really a wrapper around intern_parse_statement with check for 1
8404  *  single warning. It is needed, because for statement expressions we have
8405  *  to avoid the warning on the last statement)
8406  */
8407 static statement_t *parse_statement(void)
8408 {
8409         statement_t *statement = intern_parse_statement();
8410
8411         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8412                 expression_t *expression = statement->expression.expression;
8413                 if (!expression_has_effect(expression)) {
8414                         warningf(&expression->base.source_position,
8415                                         "statement has no effect");
8416                 }
8417         }
8418
8419         return statement;
8420 }
8421
8422 /**
8423  * Parse a compound statement.
8424  */
8425 static statement_t *parse_compound_statement(bool inside_expression_statement)
8426 {
8427         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8428
8429         statement->base.source_position = token.source_position;
8430
8431         eat('{');
8432         add_anchor_token('}');
8433
8434         int      top        = environment_top();
8435         scope_t *last_scope = scope;
8436         set_scope(&statement->compound.scope);
8437
8438         statement_t *last_statement = NULL;
8439
8440         while (token.type != '}' && token.type != T_EOF) {
8441                 statement_t *sub_statement = intern_parse_statement();
8442                 if (is_invalid_statement(sub_statement)) {
8443                         /* an error occurred. if we are at an anchor, return */
8444                         if (at_anchor())
8445                                 goto end_error;
8446                         continue;
8447                 }
8448
8449                 if (last_statement != NULL) {
8450                         last_statement->base.next = sub_statement;
8451                 } else {
8452                         statement->compound.statements = sub_statement;
8453                 }
8454
8455                 while (sub_statement->base.next != NULL)
8456                         sub_statement = sub_statement->base.next;
8457
8458                 last_statement = sub_statement;
8459         }
8460
8461         if (token.type == '}') {
8462                 next_token();
8463         } else {
8464                 errorf(&statement->base.source_position,
8465                        "end of file while looking for closing '}'");
8466         }
8467
8468         /* look over all statements again to produce no effect warnings */
8469         if (warning.unused_value) {
8470                 statement_t *sub_statement = statement->compound.statements;
8471                 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8472                         if (sub_statement->kind != STATEMENT_EXPRESSION)
8473                                 continue;
8474                         /* don't emit a warning for the last expression in an expression
8475                          * statement as it has always an effect */
8476                         if (inside_expression_statement && sub_statement->base.next == NULL)
8477                                 continue;
8478
8479                         expression_t *expression = sub_statement->expression.expression;
8480                         if (!expression_has_effect(expression)) {
8481                                 warningf(&expression->base.source_position,
8482                                          "statement has no effect");
8483                         }
8484                 }
8485         }
8486
8487 end_error:
8488         rem_anchor_token('}');
8489         assert(scope == &statement->compound.scope);
8490         set_scope(last_scope);
8491         environment_pop_to(top);
8492
8493         return statement;
8494 }
8495
8496 /**
8497  * Initialize builtin types.
8498  */
8499 static void initialize_builtin_types(void)
8500 {
8501         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
8502         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
8503         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
8504         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
8505         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
8506         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8507         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
8508         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
8509
8510         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
8511         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8512         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
8513         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
8514 }
8515
8516 /**
8517  * Check for unused global static functions and variables
8518  */
8519 static void check_unused_globals(void)
8520 {
8521         if (!warning.unused_function && !warning.unused_variable)
8522                 return;
8523
8524         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8525                 if (decl->used                  ||
8526                     decl->modifiers & DM_UNUSED ||
8527                     decl->modifiers & DM_USED   ||
8528                     decl->storage_class != STORAGE_CLASS_STATIC)
8529                         continue;
8530
8531                 type_t *const type = decl->type;
8532                 const char *s;
8533                 if (is_type_function(skip_typeref(type))) {
8534                         if (!warning.unused_function || decl->is_inline)
8535                                 continue;
8536
8537                         s = (decl->init.statement != NULL ? "defined" : "declared");
8538                 } else {
8539                         if (!warning.unused_variable)
8540                                 continue;
8541
8542                         s = "defined";
8543                 }
8544
8545                 warningf(&decl->source_position, "'%#T' %s but not used",
8546                         type, decl->symbol, s);
8547         }
8548 }
8549
8550 static void parse_global_asm(void)
8551 {
8552         eat(T_asm);
8553         expect('(');
8554
8555         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
8556         statement->base.source_position = token.source_position;
8557         statement->asms.asm_text        = parse_string_literals();
8558         statement->base.next            = unit->global_asm;
8559         unit->global_asm                = statement;
8560
8561         expect(')');
8562         expect(';');
8563
8564 end_error:;
8565 }
8566
8567 /**
8568  * Parse a translation unit.
8569  */
8570 static void parse_translation_unit(void)
8571 {
8572         for (;;) switch (token.type) {
8573                 DECLARATION_START
8574                 case T_IDENTIFIER:
8575                 case T___extension__:
8576                         parse_external_declaration();
8577                         break;
8578
8579                 case T_asm:
8580                         parse_global_asm();
8581                         break;
8582
8583                 case T_EOF:
8584                         return;
8585
8586                 case ';':
8587                         /* TODO error in strict mode */
8588                         warningf(HERE, "stray ';' outside of function");
8589                         next_token();
8590                         break;
8591
8592                 default:
8593                         errorf(HERE, "stray %K outside of function", &token);
8594                         if (token.type == '(' || token.type == '{' || token.type == '[')
8595                                 eat_until_matching_token(token.type);
8596                         next_token();
8597                         break;
8598         }
8599 }
8600
8601 /**
8602  * Parse the input.
8603  *
8604  * @return  the translation unit or NULL if errors occurred.
8605  */
8606 void start_parsing(void)
8607 {
8608         environment_stack = NEW_ARR_F(stack_entry_t, 0);
8609         label_stack       = NEW_ARR_F(stack_entry_t, 0);
8610         diagnostic_count  = 0;
8611         error_count       = 0;
8612         warning_count     = 0;
8613
8614         type_set_output(stderr);
8615         ast_set_output(stderr);
8616
8617         assert(unit == NULL);
8618         unit = allocate_ast_zero(sizeof(unit[0]));
8619
8620         assert(global_scope == NULL);
8621         global_scope = &unit->scope;
8622
8623         assert(scope == NULL);
8624         set_scope(&unit->scope);
8625
8626         initialize_builtin_types();
8627 }
8628
8629 translation_unit_t *finish_parsing(void)
8630 {
8631         assert(scope == &unit->scope);
8632         scope          = NULL;
8633         last_declaration = NULL;
8634
8635         assert(global_scope == &unit->scope);
8636         check_unused_globals();
8637         global_scope = NULL;
8638
8639         DEL_ARR_F(environment_stack);
8640         DEL_ARR_F(label_stack);
8641
8642         translation_unit_t *result = unit;
8643         unit = NULL;
8644         return result;
8645 }
8646
8647 void parse(void)
8648 {
8649         lookahead_bufpos = 0;
8650         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8651                 next_token();
8652         }
8653         parse_translation_unit();
8654 }
8655
8656 /**
8657  * Initialize the parser.
8658  */
8659 void init_parser(void)
8660 {
8661         if (c_mode & _MS) {
8662                 /* add predefined symbols for extended-decl-modifier */
8663                 sym_align      = symbol_table_insert("align");
8664                 sym_allocate   = symbol_table_insert("allocate");
8665                 sym_dllimport  = symbol_table_insert("dllimport");
8666                 sym_dllexport  = symbol_table_insert("dllexport");
8667                 sym_naked      = symbol_table_insert("naked");
8668                 sym_noinline   = symbol_table_insert("noinline");
8669                 sym_noreturn   = symbol_table_insert("noreturn");
8670                 sym_nothrow    = symbol_table_insert("nothrow");
8671                 sym_novtable   = symbol_table_insert("novtable");
8672                 sym_property   = symbol_table_insert("property");
8673                 sym_get        = symbol_table_insert("get");
8674                 sym_put        = symbol_table_insert("put");
8675                 sym_selectany  = symbol_table_insert("selectany");
8676                 sym_thread     = symbol_table_insert("thread");
8677                 sym_uuid       = symbol_table_insert("uuid");
8678                 sym_deprecated = symbol_table_insert("deprecated");
8679                 sym_restrict   = symbol_table_insert("restrict");
8680                 sym_noalias    = symbol_table_insert("noalias");
8681         }
8682         memset(token_anchor_set, 0, sizeof(token_anchor_set));
8683
8684         init_expression_parsers();
8685         obstack_init(&temp_obst);
8686
8687         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8688         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8689 }
8690
8691 /**
8692  * Terminate the parser.
8693  */
8694 void exit_parser(void)
8695 {
8696         obstack_free(&temp_obst, NULL);
8697 }