made error output for missing labels gcc like
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "diagnostic.h"
8 #include "format_check.h"
9 #include "parser.h"
10 #include "lexer.h"
11 #include "token_t.h"
12 #include "types.h"
13 #include "type_t.h"
14 #include "type_hash.h"
15 #include "ast_t.h"
16 #include "lang_features.h"
17 #include "adt/bitfiddle.h"
18 #include "adt/error.h"
19 #include "adt/array.h"
20
21 //#define PRINT_TOKENS
22 //#define ABORT_ON_ERROR
23 #define MAX_LOOKAHEAD 2
24
25 typedef struct {
26         declaration_t *old_declaration;
27         symbol_t      *symbol;
28         unsigned short namespc;
29 } stack_entry_t;
30
31 typedef struct declaration_specifiers_t  declaration_specifiers_t;
32 struct declaration_specifiers_t {
33         source_position_t  source_position;
34         unsigned char      storage_class;
35         bool               is_inline;
36         decl_modifiers_t   decl_modifiers;
37         type_t            *type;
38 };
39
40 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
41
42 static token_t             token;
43 static token_t             lookahead_buffer[MAX_LOOKAHEAD];
44 static int                 lookahead_bufpos;
45 static stack_entry_t      *environment_stack = NULL;
46 static stack_entry_t      *label_stack       = NULL;
47 static context_t          *global_context    = NULL;
48 static context_t          *context           = NULL;
49 static declaration_t      *last_declaration  = NULL;
50 static declaration_t      *current_function  = NULL;
51 static switch_statement_t *current_switch    = NULL;
52 static statement_t        *current_loop      = NULL;
53 static goto_statement_t   *goto_first        = NULL;
54 static goto_statement_t   *goto_last         = NULL;
55 static struct obstack  temp_obst;
56
57 /** The current source position. */
58 #define HERE token.source_position
59
60 static type_t *type_valist;
61
62 static statement_t *parse_compound_statement(void);
63 static statement_t *parse_statement(void);
64
65 static expression_t *parse_sub_expression(unsigned precedence);
66 static expression_t *parse_expression(void);
67 static type_t       *parse_typename(void);
68
69 static void parse_compound_type_entries(void);
70 static declaration_t *parse_declarator(
71                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
72 static declaration_t *record_declaration(declaration_t *declaration);
73
74 static void semantic_comparison(binary_expression_t *expression);
75
76 #define STORAGE_CLASSES     \
77         case T_typedef:         \
78         case T_extern:          \
79         case T_static:          \
80         case T_auto:            \
81         case T_register:
82
83 #define TYPE_QUALIFIERS     \
84         case T_const:           \
85         case T_restrict:        \
86         case T_volatile:        \
87         case T_inline:          \
88         case T_forceinline:
89
90 #ifdef PROVIDE_COMPLEX
91 #define COMPLEX_SPECIFIERS  \
92         case T__Complex:
93 #define IMAGINARY_SPECIFIERS \
94         case T__Imaginary:
95 #else
96 #define COMPLEX_SPECIFIERS
97 #define IMAGINARY_SPECIFIERS
98 #endif
99
100 #define TYPE_SPECIFIERS       \
101         case T_void:              \
102         case T_char:              \
103         case T_short:             \
104         case T_int:               \
105         case T_long:              \
106         case T_float:             \
107         case T_double:            \
108         case T_signed:            \
109         case T_unsigned:          \
110         case T__Bool:             \
111         case T_struct:            \
112         case T_union:             \
113         case T_enum:              \
114         case T___typeof__:        \
115         case T___builtin_va_list: \
116         COMPLEX_SPECIFIERS        \
117         IMAGINARY_SPECIFIERS
118
119 #define DECLARATION_START   \
120         STORAGE_CLASSES         \
121         TYPE_QUALIFIERS         \
122         TYPE_SPECIFIERS
123
124 #define TYPENAME_START      \
125         TYPE_QUALIFIERS         \
126         TYPE_SPECIFIERS
127
128 /**
129  * Allocate an AST node with given size and
130  * initialize all fields with zero.
131  */
132 static void *allocate_ast_zero(size_t size)
133 {
134         void *res = allocate_ast(size);
135         memset(res, 0, size);
136         return res;
137 }
138
139 /**
140  * Returns the size of a statement node.
141  *
142  * @param kind  the statement kind
143  */
144 static size_t get_statement_struct_size(statement_kind_t kind)
145 {
146         static const size_t sizes[] = {
147                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
148                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
149                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
150                 [STATEMENT_IF]          = sizeof(if_statement_t),
151                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
152                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
153                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
154                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
155                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
156                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
157                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
158                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
159                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
160                 [STATEMENT_FOR]         = sizeof(for_statement_t),
161                 [STATEMENT_ASM]         = sizeof(asm_statement_t)
162         };
163         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
164         assert(sizes[kind] != 0);
165         return sizes[kind];
166 }
167
168 /**
169  * Allocate a statement node of given kind and initialize all
170  * fields with zero.
171  */
172 static statement_t *allocate_statement_zero(statement_kind_t kind)
173 {
174         size_t       size = get_statement_struct_size(kind);
175         statement_t *res  = allocate_ast_zero(size);
176
177         res->base.kind = kind;
178         return res;
179 }
180
181 /**
182  * Returns the size of an expression node.
183  *
184  * @param kind  the expression kind
185  */
186 static size_t get_expression_struct_size(expression_kind_t kind)
187 {
188         static const size_t sizes[] = {
189                 [EXPR_INVALID]             = sizeof(expression_base_t),
190                 [EXPR_REFERENCE]           = sizeof(reference_expression_t),
191                 [EXPR_CONST]               = sizeof(const_expression_t),
192                 [EXPR_STRING_LITERAL]      = sizeof(string_literal_expression_t),
193                 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
194                 [EXPR_CALL]                = sizeof(call_expression_t),
195                 [EXPR_UNARY_FIRST]         = sizeof(unary_expression_t),
196                 [EXPR_BINARY_FIRST]        = sizeof(binary_expression_t),
197                 [EXPR_CONDITIONAL]         = sizeof(conditional_expression_t),
198                 [EXPR_SELECT]              = sizeof(select_expression_t),
199                 [EXPR_ARRAY_ACCESS]        = sizeof(array_access_expression_t),
200                 [EXPR_SIZEOF]              = sizeof(sizeof_expression_t),
201                 [EXPR_CLASSIFY_TYPE]       = sizeof(classify_type_expression_t),
202                 [EXPR_FUNCTION]            = sizeof(string_literal_expression_t),
203                 [EXPR_PRETTY_FUNCTION]     = sizeof(string_literal_expression_t),
204                 [EXPR_BUILTIN_SYMBOL]      = sizeof(builtin_symbol_expression_t),
205                 [EXPR_BUILTIN_CONSTANT_P]  = sizeof(builtin_constant_expression_t),
206                 [EXPR_BUILTIN_PREFETCH]    = sizeof(builtin_prefetch_expression_t),
207                 [EXPR_OFFSETOF]            = sizeof(offsetof_expression_t),
208                 [EXPR_VA_START]            = sizeof(va_start_expression_t),
209                 [EXPR_VA_ARG]              = sizeof(va_arg_expression_t),
210                 [EXPR_STATEMENT]           = sizeof(statement_expression_t),
211         };
212         if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
213                 return sizes[EXPR_UNARY_FIRST];
214         }
215         if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
216                 return sizes[EXPR_BINARY_FIRST];
217         }
218         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
219         assert(sizes[kind] != 0);
220         return sizes[kind];
221 }
222
223 /**
224  * Allocate an expression node of given kind and initialize all
225  * fields with zero.
226  */
227 static expression_t *allocate_expression_zero(expression_kind_t kind)
228 {
229         size_t        size = get_expression_struct_size(kind);
230         expression_t *res  = allocate_ast_zero(size);
231
232         res->base.kind = kind;
233         return res;
234 }
235
236 /**
237  * Returns the size of a type node.
238  *
239  * @param kind  the type kind
240  */
241 static size_t get_type_struct_size(type_kind_t kind)
242 {
243         static const size_t sizes[] = {
244                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
245                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
246                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
247                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
248                 [TYPE_ENUM]            = sizeof(enum_type_t),
249                 [TYPE_FUNCTION]        = sizeof(function_type_t),
250                 [TYPE_POINTER]         = sizeof(pointer_type_t),
251                 [TYPE_ARRAY]           = sizeof(array_type_t),
252                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
253                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
254                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
255         };
256         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
257         assert(kind <= TYPE_TYPEOF);
258         assert(sizes[kind] != 0);
259         return sizes[kind];
260 }
261
262 /**
263  * Allocate a type node of given kind and initialize all
264  * fields with zero.
265  */
266 static type_t *allocate_type_zero(type_kind_t kind)
267 {
268         size_t  size = get_type_struct_size(kind);
269         type_t *res  = obstack_alloc(type_obst, size);
270         memset(res, 0, size);
271
272         res->base.kind = kind;
273         return res;
274 }
275
276 /**
277  * Returns the size of an initializer node.
278  *
279  * @param kind  the initializer kind
280  */
281 static size_t get_initializer_size(initializer_kind_t kind)
282 {
283         static const size_t sizes[] = {
284                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
285                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
286                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
287                 [INITIALIZER_LIST]        = sizeof(initializer_list_t)
288         };
289         assert(kind < sizeof(sizes) / sizeof(*sizes));
290         assert(sizes[kind] != 0);
291         return sizes[kind];
292 }
293
294 /**
295  * Allocate an initializer node of given kind and initialize all
296  * fields with zero.
297  */
298 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
299 {
300         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
301         result->kind          = kind;
302
303         return result;
304 }
305
306 /**
307  * Free a type from the type obstack.
308  */
309 static void free_type(void *type)
310 {
311         obstack_free(type_obst, type);
312 }
313
314 /**
315  * Returns the index of the top element of the environment stack.
316  */
317 static size_t environment_top(void)
318 {
319         return ARR_LEN(environment_stack);
320 }
321
322 /**
323  * Returns the index of the top element of the label stack.
324  */
325 static size_t label_top(void)
326 {
327         return ARR_LEN(label_stack);
328 }
329
330
331 /**
332  * Return the next token.
333  */
334 static inline void next_token(void)
335 {
336         token                              = lookahead_buffer[lookahead_bufpos];
337         lookahead_buffer[lookahead_bufpos] = lexer_token;
338         lexer_next_token();
339
340         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
341
342 #ifdef PRINT_TOKENS
343         print_token(stderr, &token);
344         fprintf(stderr, "\n");
345 #endif
346 }
347
348 /**
349  * Return the next token with a given lookahead.
350  */
351 static inline const token_t *look_ahead(int num)
352 {
353         assert(num > 0 && num <= MAX_LOOKAHEAD);
354         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
355         return &lookahead_buffer[pos];
356 }
357
358 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
359
360 /**
361  * Report a parse error because an expected token was not found.
362  */
363 static void parse_error_expected(const char *message, ...)
364 {
365         if(message != NULL) {
366                 errorf(HERE, "%s", message);
367         }
368         va_list ap;
369         va_start(ap, message);
370         errorf(HERE, "got '%K', expected %#k", &token, &ap, ", ");
371         va_end(ap);
372 }
373
374 /**
375  * Report a type error.
376  */
377 static void type_error(const char *msg, const source_position_t source_position,
378                        type_t *type)
379 {
380         errorf(source_position, "%s, but found type '%T'", msg, type);
381 }
382
383 /**
384  * Report an incompatible type.
385  */
386 static void type_error_incompatible(const char *msg,
387                 const source_position_t source_position, type_t *type1, type_t *type2)
388 {
389         errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
390 }
391
392 /**
393  * Eat an complete block, ie. '{ ... }'.
394  */
395 static void eat_block(void)
396 {
397         if(token.type == '{')
398                 next_token();
399
400         while(token.type != '}') {
401                 if(token.type == T_EOF)
402                         return;
403                 if(token.type == '{') {
404                         eat_block();
405                         continue;
406                 }
407                 next_token();
408         }
409         eat('}');
410 }
411
412 /**
413  * Eat a statement until an ';' token.
414  */
415 static void eat_statement(void)
416 {
417         while(token.type != ';') {
418                 if(token.type == T_EOF)
419                         return;
420                 if(token.type == '}')
421                         return;
422                 if(token.type == '{') {
423                         eat_block();
424                         continue;
425                 }
426                 next_token();
427         }
428         eat(';');
429 }
430
431 /**
432  * Eat a parenthesed term, ie. '( ... )'.
433  */
434 static void eat_paren(void)
435 {
436         if(token.type == '(')
437                 next_token();
438
439         while(token.type != ')') {
440                 if(token.type == T_EOF)
441                         return;
442                 if(token.type == ')' || token.type == ';' || token.type == '}') {
443                         return;
444                 }
445                 if(token.type == '(') {
446                         eat_paren();
447                         continue;
448                 }
449                 if(token.type == '{') {
450                         eat_block();
451                         continue;
452                 }
453                 next_token();
454         }
455         eat(')');
456 }
457
458 #define expect(expected)                           \
459     if(UNLIKELY(token.type != (expected))) {       \
460         parse_error_expected(NULL, (expected), 0); \
461         eat_statement();                           \
462         return NULL;                               \
463     }                                              \
464     next_token();
465
466 #define expect_fail(expected)                      \
467     if(UNLIKELY(token.type != (expected))) {       \
468         parse_error_expected(NULL, (expected), 0); \
469         eat_statement();                           \
470         goto fail;                                 \
471     }                                              \
472     next_token();
473
474 #define expect_block(expected)                     \
475     if(UNLIKELY(token.type != (expected))) {       \
476         parse_error_expected(NULL, (expected), 0); \
477         eat_block();                               \
478         return NULL;                               \
479     }                                              \
480     next_token();
481
482 #define expect_void(expected)                      \
483     if(UNLIKELY(token.type != (expected))) {       \
484         parse_error_expected(NULL, (expected), 0); \
485         eat_statement();                           \
486         return;                                    \
487     }                                              \
488     next_token();
489
490 static void set_context(context_t *new_context)
491 {
492         context = new_context;
493
494         last_declaration = new_context->declarations;
495         if(last_declaration != NULL) {
496                 while(last_declaration->next != NULL) {
497                         last_declaration = last_declaration->next;
498                 }
499         }
500 }
501
502 /**
503  * Search a symbol in a given namespace and returns its declaration or
504  * NULL if this symbol was not found.
505  */
506 static declaration_t *get_declaration(const symbol_t *const symbol, const namespace_t namespc)
507 {
508         declaration_t *declaration = symbol->declaration;
509         for( ; declaration != NULL; declaration = declaration->symbol_next) {
510                 if(declaration->namespc == namespc)
511                         return declaration;
512         }
513
514         return NULL;
515 }
516
517 /**
518  * pushs an environment_entry on the environment stack and links the
519  * corresponding symbol to the new entry
520  */
521 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
522 {
523         symbol_t    *symbol    = declaration->symbol;
524         namespace_t  namespc = (namespace_t)declaration->namespc;
525
526         /* remember old declaration */
527         stack_entry_t entry;
528         entry.symbol          = symbol;
529         entry.old_declaration = symbol->declaration;
530         entry.namespc         = (unsigned short) namespc;
531         ARR_APP1(stack_entry_t, *stack_ptr, entry);
532
533         /* replace/add declaration into declaration list of the symbol */
534         if(symbol->declaration == NULL) {
535                 symbol->declaration = declaration;
536         } else {
537                 declaration_t *iter_last = NULL;
538                 declaration_t *iter      = symbol->declaration;
539                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
540                         /* replace an entry? */
541                         if(iter->namespc == namespc) {
542                                 if(iter_last == NULL) {
543                                         symbol->declaration = declaration;
544                                 } else {
545                                         iter_last->symbol_next = declaration;
546                                 }
547                                 declaration->symbol_next = iter->symbol_next;
548                                 break;
549                         }
550                 }
551                 if(iter == NULL) {
552                         assert(iter_last->symbol_next == NULL);
553                         iter_last->symbol_next = declaration;
554                 }
555         }
556 }
557
558 static void environment_push(declaration_t *declaration)
559 {
560         assert(declaration->source_position.input_name != NULL);
561         assert(declaration->parent_context != NULL);
562         stack_push(&environment_stack, declaration);
563 }
564
565 static void label_push(declaration_t *declaration)
566 {
567         declaration->parent_context = &current_function->context;
568         stack_push(&label_stack, declaration);
569 }
570
571 /**
572  * pops symbols from the environment stack until @p new_top is the top element
573  */
574 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
575 {
576         stack_entry_t *stack = *stack_ptr;
577         size_t         top   = ARR_LEN(stack);
578         size_t         i;
579
580         assert(new_top <= top);
581         if(new_top == top)
582                 return;
583
584         for(i = top; i > new_top; --i) {
585                 stack_entry_t *entry = &stack[i - 1];
586
587                 declaration_t *old_declaration = entry->old_declaration;
588                 symbol_t      *symbol          = entry->symbol;
589                 namespace_t    namespc         = (namespace_t)entry->namespc;
590
591                 /* replace/remove declaration */
592                 declaration_t *declaration = symbol->declaration;
593                 assert(declaration != NULL);
594                 if(declaration->namespc == namespc) {
595                         if(old_declaration == NULL) {
596                                 symbol->declaration = declaration->symbol_next;
597                         } else {
598                                 symbol->declaration = old_declaration;
599                         }
600                 } else {
601                         declaration_t *iter_last = declaration;
602                         declaration_t *iter      = declaration->symbol_next;
603                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
604                                 /* replace an entry? */
605                                 if(iter->namespc == namespc) {
606                                         assert(iter_last != NULL);
607                                         iter_last->symbol_next = old_declaration;
608                                         old_declaration->symbol_next = iter->symbol_next;
609                                         break;
610                                 }
611                         }
612                         assert(iter != NULL);
613                 }
614         }
615
616         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
617 }
618
619 static void environment_pop_to(size_t new_top)
620 {
621         stack_pop_to(&environment_stack, new_top);
622 }
623
624 static void label_pop_to(size_t new_top)
625 {
626         stack_pop_to(&label_stack, new_top);
627 }
628
629
630 static int get_rank(const type_t *type)
631 {
632         assert(!is_typeref(type));
633         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
634          * and esp. footnote 108). However we can't fold constants (yet), so we
635          * can't decide whether unsigned int is possible, while int always works.
636          * (unsigned int would be preferable when possible... for stuff like
637          *  struct { enum { ... } bla : 4; } ) */
638         if(type->kind == TYPE_ENUM)
639                 return ATOMIC_TYPE_INT;
640
641         assert(type->kind == TYPE_ATOMIC);
642         const atomic_type_t *atomic_type = &type->atomic;
643         atomic_type_kind_t   atype       = atomic_type->akind;
644         return atype;
645 }
646
647 static type_t *promote_integer(type_t *type)
648 {
649         if(type->kind == TYPE_BITFIELD)
650                 return promote_integer(type->bitfield.base);
651
652         if(get_rank(type) < ATOMIC_TYPE_INT)
653                 type = type_int;
654
655         return type;
656 }
657
658 /**
659  * Create a cast expression.
660  *
661  * @param expression  the expression to cast
662  * @param dest_type   the destination type
663  */
664 static expression_t *create_cast_expression(expression_t *expression,
665                                             type_t *dest_type)
666 {
667         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
668
669         cast->unary.value   = expression;
670         cast->base.datatype = dest_type;
671
672         return cast;
673 }
674
675 /**
676  * Check if a given expression represents the 0 pointer constant.
677  */
678 static bool is_null_pointer_constant(const expression_t *expression)
679 {
680         /* skip void* cast */
681         if(expression->kind == EXPR_UNARY_CAST
682                         || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
683                 expression = expression->unary.value;
684         }
685
686         /* TODO: not correct yet, should be any constant integer expression
687          * which evaluates to 0 */
688         if (expression->kind != EXPR_CONST)
689                 return false;
690
691         type_t *const type = skip_typeref(expression->base.datatype);
692         if (!is_type_integer(type))
693                 return false;
694
695         return expression->conste.v.int_value == 0;
696 }
697
698 /**
699  * Create an implicit cast expression.
700  *
701  * @param expression  the expression to cast
702  * @param dest_type   the destination type
703  */
704 static expression_t *create_implicit_cast(expression_t *expression,
705                                           type_t *dest_type)
706 {
707         type_t *source_type = expression->base.datatype;
708
709         if(source_type == NULL)
710                 return expression;
711
712         source_type = skip_typeref(source_type);
713         dest_type   = skip_typeref(dest_type);
714
715         if(source_type == dest_type)
716                 return expression;
717
718         switch (dest_type->kind) {
719                 case TYPE_ENUM:
720                         /* TODO warning for implicitly converting to enum */
721                 case TYPE_BITFIELD:
722                 case TYPE_ATOMIC:
723                         if (source_type->kind != TYPE_ATOMIC &&
724                                         source_type->kind != TYPE_ENUM &&
725                                         source_type->kind != TYPE_BITFIELD) {
726                                 panic("casting of non-atomic types not implemented yet");
727                         }
728
729                         if(is_type_floating(dest_type) && !is_type_scalar(source_type)) {
730                                 type_error_incompatible("can't cast types",
731                                                 expression->base.source_position, source_type,
732                                                 dest_type);
733                                 return expression;
734                         }
735
736                         return create_cast_expression(expression, dest_type);
737
738                 case TYPE_POINTER:
739                         switch (source_type->kind) {
740                                 case TYPE_ATOMIC:
741                                         if (is_null_pointer_constant(expression)) {
742                                                 return create_cast_expression(expression, dest_type);
743                                         }
744                                         break;
745
746                                 case TYPE_POINTER:
747                                         if (pointers_compatible(source_type, dest_type)) {
748                                                 return create_cast_expression(expression, dest_type);
749                                         }
750                                         break;
751
752                                 case TYPE_ARRAY: {
753                                         array_type_t   *array_type   = &source_type->array;
754                                         pointer_type_t *pointer_type = &dest_type->pointer;
755                                         if (types_compatible(array_type->element_type,
756                                                                                  pointer_type->points_to)) {
757                                                 return create_cast_expression(expression, dest_type);
758                                         }
759                                         break;
760                                 }
761
762                                 default:
763                                         panic("casting of non-atomic types not implemented yet");
764                         }
765
766                         type_error_incompatible("can't implicitly cast types",
767                                         expression->base.source_position, source_type, dest_type);
768                         return expression;
769
770                 default:
771                         panic("casting of non-atomic types not implemented yet");
772         }
773 }
774
775 /** Implements the rules from Â§ 6.5.16.1 */
776 static void semantic_assign(type_t *orig_type_left, expression_t **right,
777                             const char *context)
778 {
779         type_t *orig_type_right = (*right)->base.datatype;
780
781         if(orig_type_right == NULL)
782                 return;
783
784         type_t *const type_left  = skip_typeref(orig_type_left);
785         type_t *const type_right = skip_typeref(orig_type_right);
786
787         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
788             (is_type_pointer(type_left) && is_null_pointer_constant(*right)) ||
789             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
790                 && is_type_pointer(type_right))) {
791                 *right = create_implicit_cast(*right, type_left);
792                 return;
793         }
794
795         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
796                 pointer_type_t *pointer_type_left  = &type_left->pointer;
797                 pointer_type_t *pointer_type_right = &type_right->pointer;
798                 type_t         *points_to_left     = pointer_type_left->points_to;
799                 type_t         *points_to_right    = pointer_type_right->points_to;
800
801                 points_to_left  = skip_typeref(points_to_left);
802                 points_to_right = skip_typeref(points_to_right);
803
804                 /* the left type has all qualifiers from the right type */
805                 unsigned missing_qualifiers
806                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
807                 if(missing_qualifiers != 0) {
808                         errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
809                         return;
810                 }
811
812                 points_to_left  = get_unqualified_type(points_to_left);
813                 points_to_right = get_unqualified_type(points_to_right);
814
815                 if(!is_type_atomic(points_to_left, ATOMIC_TYPE_VOID)
816                                 && !is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)
817                                 && !types_compatible(points_to_left, points_to_right)) {
818                         goto incompatible_assign_types;
819                 }
820
821                 *right = create_implicit_cast(*right, type_left);
822                 return;
823         }
824
825         if (is_type_compound(type_left)
826                         && types_compatible(type_left, type_right)) {
827                 *right = create_implicit_cast(*right, type_left);
828                 return;
829         }
830
831 incompatible_assign_types:
832         /* TODO: improve error message */
833         errorf(HERE, "incompatible types in %s", context);
834         errorf(HERE, "'%T' <- '%T'", orig_type_left, orig_type_right);
835 }
836
837 static expression_t *parse_constant_expression(void)
838 {
839         /* start parsing at precedence 7 (conditional expression) */
840         expression_t *result = parse_sub_expression(7);
841
842         if(!is_constant_expression(result)) {
843                 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
844         }
845
846         return result;
847 }
848
849 static expression_t *parse_assignment_expression(void)
850 {
851         /* start parsing at precedence 2 (assignment expression) */
852         return parse_sub_expression(2);
853 }
854
855 static type_t *make_global_typedef(const char *name, type_t *type)
856 {
857         symbol_t *const symbol       = symbol_table_insert(name);
858
859         declaration_t *declaration   = allocate_ast_zero(sizeof(declaration[0]));
860         declaration->namespc         = NAMESPACE_NORMAL;
861         declaration->storage_class   = STORAGE_CLASS_TYPEDEF;
862         declaration->type            = type;
863         declaration->symbol          = symbol;
864         declaration->source_position = builtin_source_position;
865
866         record_declaration(declaration);
867
868         type_t *typedef_type               = allocate_type_zero(TYPE_TYPEDEF);
869         typedef_type->typedeft.declaration = declaration;
870
871         return typedef_type;
872 }
873
874 static const char *parse_string_literals(void)
875 {
876         assert(token.type == T_STRING_LITERAL);
877         const char *result = token.v.string;
878
879         next_token();
880
881         while(token.type == T_STRING_LITERAL) {
882                 result = concat_strings(result, token.v.string);
883                 next_token();
884         }
885
886         return result;
887 }
888
889 static void parse_attributes(void)
890 {
891         while(true) {
892                 switch(token.type) {
893                 case T___attribute__: {
894                         next_token();
895
896                         expect_void('(');
897                         int depth = 1;
898                         while(depth > 0) {
899                                 switch(token.type) {
900                                 case T_EOF:
901                                         errorf(HERE, "EOF while parsing attribute");
902                                         break;
903                                 case '(':
904                                         next_token();
905                                         depth++;
906                                         break;
907                                 case ')':
908                                         next_token();
909                                         depth--;
910                                         break;
911                                 default:
912                                         next_token();
913                                 }
914                         }
915                         break;
916                 }
917                 case T_asm:
918                         next_token();
919                         expect_void('(');
920                         if(token.type != T_STRING_LITERAL) {
921                                 parse_error_expected("while parsing assembler attribute",
922                                                      T_STRING_LITERAL);
923                                 eat_paren();
924                                 break;
925                         } else {
926                                 parse_string_literals();
927                         }
928                         expect_void(')');
929                         break;
930                 default:
931                         goto attributes_finished;
932                 }
933         }
934
935 attributes_finished:
936         ;
937 }
938
939 #if 0
940 static designator_t *parse_designation(void)
941 {
942         if(token.type != '[' && token.type != '.')
943                 return NULL;
944
945         designator_t *result = NULL;
946         designator_t *last   = NULL;
947
948         while(1) {
949                 designator_t *designator;
950                 switch(token.type) {
951                 case '[':
952                         designator = allocate_ast_zero(sizeof(designator[0]));
953                         next_token();
954                         designator->array_access = parse_constant_expression();
955                         expect(']');
956                         break;
957                 case '.':
958                         designator = allocate_ast_zero(sizeof(designator[0]));
959                         next_token();
960                         if(token.type != T_IDENTIFIER) {
961                                 parse_error_expected("while parsing designator",
962                                                      T_IDENTIFIER, 0);
963                                 return NULL;
964                         }
965                         designator->symbol = token.v.symbol;
966                         next_token();
967                         break;
968                 default:
969                         expect('=');
970                         return result;
971                 }
972
973                 assert(designator != NULL);
974                 if(last != NULL) {
975                         last->next = designator;
976                 } else {
977                         result = designator;
978                 }
979                 last = designator;
980         }
981 }
982 #endif
983
984 static initializer_t *initializer_from_string(array_type_t *type,
985                                               const char *string)
986 {
987         /* TODO: check len vs. size of array type */
988         (void) type;
989
990         initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
991         initializer->string.string = string;
992
993         return initializer;
994 }
995
996 static initializer_t *initializer_from_wide_string(array_type_t *const type,
997                                                    wide_string_t *const string)
998 {
999         /* TODO: check len vs. size of array type */
1000         (void) type;
1001
1002         initializer_t *const initializer =
1003                 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1004         initializer->wide_string.string = *string;
1005
1006         return initializer;
1007 }
1008
1009 static initializer_t *initializer_from_expression(type_t *type,
1010                                                   expression_t *expression)
1011 {
1012         /* TODO check that expression is a constant expression */
1013
1014         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
1015         type_t *const expr_type = expression->base.datatype;
1016         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1017                 array_type_t *const array_type   = &type->array;
1018                 type_t       *const element_type = skip_typeref(array_type->element_type);
1019
1020                 if (element_type->kind == TYPE_ATOMIC) {
1021                         switch (expression->kind) {
1022                                 case EXPR_STRING_LITERAL:
1023                                         if (element_type->atomic.akind == ATOMIC_TYPE_CHAR) {
1024                                                 return initializer_from_string(array_type,
1025                                                         expression->string.value);
1026                                         }
1027
1028                                 case EXPR_WIDE_STRING_LITERAL: {
1029                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1030                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
1031                                                 return initializer_from_wide_string(array_type,
1032                                                         &expression->wide_string.value);
1033                                         }
1034                                 }
1035
1036                                 default:
1037                                         break;
1038                         }
1039                 }
1040         }
1041
1042         type_t *expression_type = skip_typeref(expression->base.datatype);
1043         if(is_type_scalar(type) || types_compatible(type, expression_type)) {
1044                 semantic_assign(type, &expression, "initializer");
1045
1046                 initializer_t *result = allocate_initializer_zero(INITIALIZER_VALUE);
1047                 result->value.value   = expression;
1048
1049                 return result;
1050         }
1051
1052         return NULL;
1053 }
1054
1055 static initializer_t *parse_sub_initializer(type_t *type,
1056                                             expression_t *expression,
1057                                             type_t *expression_type);
1058
1059 static initializer_t *parse_sub_initializer_elem(type_t *type)
1060 {
1061         if(token.type == '{') {
1062                 return parse_sub_initializer(type, NULL, NULL);
1063         }
1064
1065         expression_t *expression      = parse_assignment_expression();
1066         type_t       *expression_type = skip_typeref(expression->base.datatype);
1067
1068         return parse_sub_initializer(type, expression, expression_type);
1069 }
1070
1071 static bool had_initializer_brace_warning;
1072
1073 static void skip_designator(void)
1074 {
1075         while(1) {
1076                 if(token.type == '.') {
1077                         next_token();
1078                         if(token.type == T_IDENTIFIER)
1079                                 next_token();
1080                 } else if(token.type == '[') {
1081                         next_token();
1082                         parse_constant_expression();
1083                         if(token.type == ']')
1084                                 next_token();
1085                 } else {
1086                         break;
1087                 }
1088         }
1089 }
1090
1091 static initializer_t *parse_sub_initializer(type_t *type,
1092                                             expression_t *expression,
1093                                             type_t *expression_type)
1094 {
1095         if(is_type_scalar(type)) {
1096                 /* there might be extra {} hierarchies */
1097                 if(token.type == '{') {
1098                         next_token();
1099                         if(!had_initializer_brace_warning) {
1100                                 warningf(HERE, "braces around scalar initializer");
1101                                 had_initializer_brace_warning = true;
1102                         }
1103                         initializer_t *result = parse_sub_initializer(type, NULL, NULL);
1104                         if(token.type == ',') {
1105                                 next_token();
1106                                 /* TODO: warn about excessive elements */
1107                         }
1108                         expect_block('}');
1109                         return result;
1110                 }
1111
1112                 if(expression == NULL) {
1113                         expression = parse_assignment_expression();
1114                 }
1115                 return initializer_from_expression(type, expression);
1116         }
1117
1118         /* does the expression match the currently looked at object to initialize */
1119         if(expression != NULL) {
1120                 initializer_t *result = initializer_from_expression(type, expression);
1121                 if(result != NULL)
1122                         return result;
1123         }
1124
1125         bool read_paren = false;
1126         if(token.type == '{') {
1127                 next_token();
1128                 read_paren = true;
1129         }
1130
1131         /* descend into subtype */
1132         initializer_t  *result = NULL;
1133         initializer_t **elems;
1134         if(is_type_array(type)) {
1135                 array_type_t *array_type   = &type->array;
1136                 type_t       *element_type = array_type->element_type;
1137                 element_type               = skip_typeref(element_type);
1138
1139                 if(token.type == '.') {
1140                         errorf(HERE,
1141                                "compound designator in initializer for array type '%T'",
1142                                type);
1143                         skip_designator();
1144                 }
1145
1146                 initializer_t *sub;
1147                 had_initializer_brace_warning = false;
1148                 if(expression == NULL) {
1149                         sub = parse_sub_initializer_elem(element_type);
1150                 } else {
1151                         sub = parse_sub_initializer(element_type, expression,
1152                                                     expression_type);
1153                 }
1154
1155                 /* didn't match the subtypes -> try the parent type */
1156                 if(sub == NULL) {
1157                         assert(!read_paren);
1158                         return NULL;
1159                 }
1160
1161                 elems = NEW_ARR_F(initializer_t*, 0);
1162                 ARR_APP1(initializer_t*, elems, sub);
1163
1164                 while(true) {
1165                         if(token.type == '}')
1166                                 break;
1167                         expect_block(',');
1168                         if(token.type == '}')
1169                                 break;
1170
1171                         sub = parse_sub_initializer_elem(element_type);
1172                         if(sub == NULL) {
1173                                 /* TODO error, do nicer cleanup */
1174                                 errorf(HERE, "member initializer didn't match");
1175                                 DEL_ARR_F(elems);
1176                                 return NULL;
1177                         }
1178                         ARR_APP1(initializer_t*, elems, sub);
1179                 }
1180         } else {
1181                 assert(is_type_compound(type));
1182                 compound_type_t *compound_type = &type->compound;
1183                 context_t       *context       = &compound_type->declaration->context;
1184
1185                 if(token.type == '[') {
1186                         errorf(HERE,
1187                                "array designator in initializer for compound type '%T'",
1188                                type);
1189                         skip_designator();
1190                 }
1191
1192                 declaration_t *first = context->declarations;
1193                 if(first == NULL)
1194                         return NULL;
1195                 type_t *first_type = first->type;
1196                 first_type         = skip_typeref(first_type);
1197
1198                 initializer_t *sub;
1199                 had_initializer_brace_warning = false;
1200                 if(expression == NULL) {
1201                         sub = parse_sub_initializer_elem(first_type);
1202                 } else {
1203                         sub = parse_sub_initializer(first_type, expression,expression_type);
1204                 }
1205
1206                 /* didn't match the subtypes -> try our parent type */
1207                 if(sub == NULL) {
1208                         assert(!read_paren);
1209                         return NULL;
1210                 }
1211
1212                 elems = NEW_ARR_F(initializer_t*, 0);
1213                 ARR_APP1(initializer_t*, elems, sub);
1214
1215                 declaration_t *iter  = first->next;
1216                 for( ; iter != NULL; iter = iter->next) {
1217                         if(iter->symbol == NULL)
1218                                 continue;
1219                         if(iter->namespc != NAMESPACE_NORMAL)
1220                                 continue;
1221
1222                         if(token.type == '}')
1223                                 break;
1224                         expect_block(',');
1225                         if(token.type == '}')
1226                                 break;
1227
1228                         type_t *iter_type = iter->type;
1229                         iter_type         = skip_typeref(iter_type);
1230
1231                         sub = parse_sub_initializer_elem(iter_type);
1232                         if(sub == NULL) {
1233                                 /* TODO error, do nicer cleanup */
1234                                 errorf(HERE, "member initializer didn't match");
1235                                 DEL_ARR_F(elems);
1236                                 return NULL;
1237                         }
1238                         ARR_APP1(initializer_t*, elems, sub);
1239                 }
1240         }
1241
1242         int    len        = ARR_LEN(elems);
1243         size_t elems_size = sizeof(initializer_t*) * len;
1244
1245         initializer_list_t *init = allocate_ast_zero(sizeof(init[0]) + elems_size);
1246
1247         init->initializer.kind = INITIALIZER_LIST;
1248         init->len              = len;
1249         memcpy(init->initializers, elems, elems_size);
1250         DEL_ARR_F(elems);
1251
1252         result = (initializer_t*) init;
1253
1254         if(read_paren) {
1255                 if(token.type == ',')
1256                         next_token();
1257                 expect('}');
1258         }
1259         return result;
1260 }
1261
1262 static initializer_t *parse_initializer(type_t *type)
1263 {
1264         initializer_t *result;
1265
1266         type = skip_typeref(type);
1267
1268         if(token.type != '{') {
1269                 expression_t  *expression  = parse_assignment_expression();
1270                 initializer_t *initializer = initializer_from_expression(type, expression);
1271                 if(initializer == NULL) {
1272                         errorf(HERE, "initializer expression '%E', type '%T' is incompatible with type '%T'", expression, expression->base.datatype, type);
1273                 }
1274                 return initializer;
1275         }
1276
1277         if(is_type_scalar(type)) {
1278                 /* Â§ 6.7.8.11 */
1279                 eat('{');
1280
1281                 expression_t *expression = parse_assignment_expression();
1282                 result = initializer_from_expression(type, expression);
1283
1284                 if(token.type == ',')
1285                         next_token();
1286
1287                 expect('}');
1288                 return result;
1289         } else {
1290                 result = parse_sub_initializer(type, NULL, NULL);
1291         }
1292
1293         return result;
1294 }
1295
1296 static declaration_t *append_declaration(declaration_t *declaration);
1297
1298 static declaration_t *parse_compound_type_specifier(bool is_struct)
1299 {
1300         if(is_struct) {
1301                 eat(T_struct);
1302         } else {
1303                 eat(T_union);
1304         }
1305
1306         symbol_t      *symbol      = NULL;
1307         declaration_t *declaration = NULL;
1308
1309         if (token.type == T___attribute__) {
1310                 /* TODO */
1311                 parse_attributes();
1312         }
1313
1314         if(token.type == T_IDENTIFIER) {
1315                 symbol = token.v.symbol;
1316                 next_token();
1317
1318                 if(is_struct) {
1319                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1320                 } else {
1321                         declaration = get_declaration(symbol, NAMESPACE_UNION);
1322                 }
1323         } else if(token.type != '{') {
1324                 if(is_struct) {
1325                         parse_error_expected("while parsing struct type specifier",
1326                                              T_IDENTIFIER, '{', 0);
1327                 } else {
1328                         parse_error_expected("while parsing union type specifier",
1329                                              T_IDENTIFIER, '{', 0);
1330                 }
1331
1332                 return NULL;
1333         }
1334
1335         if(declaration == NULL) {
1336                 declaration = allocate_ast_zero(sizeof(declaration[0]));
1337
1338                 if(is_struct) {
1339                         declaration->namespc = NAMESPACE_STRUCT;
1340                 } else {
1341                         declaration->namespc = NAMESPACE_UNION;
1342                 }
1343                 declaration->source_position = token.source_position;
1344                 declaration->symbol          = symbol;
1345                 declaration->parent_context  = context;
1346                 if (symbol != NULL) {
1347                         environment_push(declaration);
1348                 }
1349                 append_declaration(declaration);
1350         }
1351
1352         if(token.type == '{') {
1353                 if(declaration->init.is_defined) {
1354                         assert(symbol != NULL);
1355                         errorf(HERE, "multiple definition of '%s %Y'",
1356                                is_struct ? "struct" : "union", symbol);
1357                         declaration->context.declarations = NULL;
1358                 }
1359                 declaration->init.is_defined = true;
1360
1361                 int         top          = environment_top();
1362                 context_t  *last_context = context;
1363                 set_context(&declaration->context);
1364
1365                 parse_compound_type_entries();
1366                 parse_attributes();
1367
1368                 assert(context == &declaration->context);
1369                 set_context(last_context);
1370                 environment_pop_to(top);
1371         }
1372
1373         return declaration;
1374 }
1375
1376 static void parse_enum_entries(enum_type_t *const enum_type)
1377 {
1378         eat('{');
1379
1380         if(token.type == '}') {
1381                 next_token();
1382                 errorf(HERE, "empty enum not allowed");
1383                 return;
1384         }
1385
1386         do {
1387                 declaration_t *entry = allocate_ast_zero(sizeof(entry[0]));
1388
1389                 if(token.type != T_IDENTIFIER) {
1390                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1391                         eat_block();
1392                         return;
1393                 }
1394                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
1395                 entry->type            = (type_t*) enum_type;
1396                 entry->symbol          = token.v.symbol;
1397                 entry->source_position = token.source_position;
1398                 next_token();
1399
1400                 if(token.type == '=') {
1401                         next_token();
1402                         entry->init.enum_value = parse_constant_expression();
1403
1404                         /* TODO semantic */
1405                 }
1406
1407                 record_declaration(entry);
1408
1409                 if(token.type != ',')
1410                         break;
1411                 next_token();
1412         } while(token.type != '}');
1413
1414         expect_void('}');
1415 }
1416
1417 static type_t *parse_enum_specifier(void)
1418 {
1419         eat(T_enum);
1420
1421         declaration_t *declaration;
1422         symbol_t      *symbol;
1423
1424         if(token.type == T_IDENTIFIER) {
1425                 symbol = token.v.symbol;
1426                 next_token();
1427
1428                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1429         } else if(token.type != '{') {
1430                 parse_error_expected("while parsing enum type specifier",
1431                                      T_IDENTIFIER, '{', 0);
1432                 return NULL;
1433         } else {
1434                 declaration = NULL;
1435                 symbol      = NULL;
1436         }
1437
1438         if(declaration == NULL) {
1439                 declaration = allocate_ast_zero(sizeof(declaration[0]));
1440
1441                 declaration->namespc       = NAMESPACE_ENUM;
1442                 declaration->source_position = token.source_position;
1443                 declaration->symbol          = symbol;
1444                 declaration->parent_context  = context;
1445         }
1446
1447         type_t *const type      = allocate_type_zero(TYPE_ENUM);
1448         type->enumt.declaration = declaration;
1449
1450         if(token.type == '{') {
1451                 if(declaration->init.is_defined) {
1452                         errorf(HERE, "multiple definitions of enum %Y", symbol);
1453                 }
1454                 if (symbol != NULL) {
1455                         environment_push(declaration);
1456                 }
1457                 append_declaration(declaration);
1458                 declaration->init.is_defined = 1;
1459
1460                 parse_enum_entries(&type->enumt);
1461                 parse_attributes();
1462         }
1463
1464         return type;
1465 }
1466
1467 /**
1468  * if a symbol is a typedef to another type, return true
1469  */
1470 static bool is_typedef_symbol(symbol_t *symbol)
1471 {
1472         const declaration_t *const declaration =
1473                 get_declaration(symbol, NAMESPACE_NORMAL);
1474         return
1475                 declaration != NULL &&
1476                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1477 }
1478
1479 static type_t *parse_typeof(void)
1480 {
1481         eat(T___typeof__);
1482
1483         type_t *type;
1484
1485         expect('(');
1486
1487         expression_t *expression  = NULL;
1488
1489 restart:
1490         switch(token.type) {
1491         case T___extension__:
1492                 /* this can be a prefix to a typename or an expression */
1493                 /* we simply eat it now. */
1494                 do {
1495                         next_token();
1496                 } while(token.type == T___extension__);
1497                 goto restart;
1498
1499         case T_IDENTIFIER:
1500                 if(is_typedef_symbol(token.v.symbol)) {
1501                         type = parse_typename();
1502                 } else {
1503                         expression = parse_expression();
1504                         type       = expression->base.datatype;
1505                 }
1506                 break;
1507
1508         TYPENAME_START
1509                 type = parse_typename();
1510                 break;
1511
1512         default:
1513                 expression = parse_expression();
1514                 type       = expression->base.datatype;
1515                 break;
1516         }
1517
1518         expect(')');
1519
1520         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF);
1521         typeof_type->typeoft.expression  = expression;
1522         typeof_type->typeoft.typeof_type = type;
1523
1524         return typeof_type;
1525 }
1526
1527 typedef enum {
1528         SPECIFIER_SIGNED    = 1 << 0,
1529         SPECIFIER_UNSIGNED  = 1 << 1,
1530         SPECIFIER_LONG      = 1 << 2,
1531         SPECIFIER_INT       = 1 << 3,
1532         SPECIFIER_DOUBLE    = 1 << 4,
1533         SPECIFIER_CHAR      = 1 << 5,
1534         SPECIFIER_SHORT     = 1 << 6,
1535         SPECIFIER_LONG_LONG = 1 << 7,
1536         SPECIFIER_FLOAT     = 1 << 8,
1537         SPECIFIER_BOOL      = 1 << 9,
1538         SPECIFIER_VOID      = 1 << 10,
1539 #ifdef PROVIDE_COMPLEX
1540         SPECIFIER_COMPLEX   = 1 << 11,
1541         SPECIFIER_IMAGINARY = 1 << 12,
1542 #endif
1543 } specifiers_t;
1544
1545 static type_t *create_builtin_type(symbol_t *const symbol,
1546                                    type_t *const real_type)
1547 {
1548         type_t *type            = allocate_type_zero(TYPE_BUILTIN);
1549         type->builtin.symbol    = symbol;
1550         type->builtin.real_type = real_type;
1551
1552         type_t *result = typehash_insert(type);
1553         if (type != result) {
1554                 free_type(type);
1555         }
1556
1557         return result;
1558 }
1559
1560 static type_t *get_typedef_type(symbol_t *symbol)
1561 {
1562         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1563         if(declaration == NULL
1564                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1565                 return NULL;
1566
1567         type_t *type               = allocate_type_zero(TYPE_TYPEDEF);
1568         type->typedeft.declaration = declaration;
1569
1570         return type;
1571 }
1572
1573 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1574 {
1575         type_t   *type            = NULL;
1576         unsigned  type_qualifiers = 0;
1577         unsigned  type_specifiers = 0;
1578         int       newtype         = 0;
1579
1580         specifiers->source_position = token.source_position;
1581
1582         while(true) {
1583                 switch(token.type) {
1584
1585                 /* storage class */
1586 #define MATCH_STORAGE_CLASS(token, class)                                \
1587                 case token:                                                      \
1588                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1589                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
1590                         }                                                            \
1591                         specifiers->storage_class = class;                           \
1592                         next_token();                                                \
1593                         break;
1594
1595                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1596                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1597                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1598                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1599                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1600
1601                 case T___thread:
1602                         switch (specifiers->storage_class) {
1603                                 case STORAGE_CLASS_NONE:
1604                                         specifiers->storage_class = STORAGE_CLASS_THREAD;
1605                                         break;
1606
1607                                 case STORAGE_CLASS_EXTERN:
1608                                         specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
1609                                         break;
1610
1611                                 case STORAGE_CLASS_STATIC:
1612                                         specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
1613                                         break;
1614
1615                                 default:
1616                                         errorf(HERE, "multiple storage classes in declaration specifiers");
1617                                         break;
1618                         }
1619                         next_token();
1620                         break;
1621
1622                 /* type qualifiers */
1623 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1624                 case token:                                                     \
1625                         type_qualifiers |= qualifier;                               \
1626                         next_token();                                               \
1627                         break;
1628
1629                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1630                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1631                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1632
1633                 case T___extension__:
1634                         /* TODO */
1635                         next_token();
1636                         break;
1637
1638                 /* type specifiers */
1639 #define MATCH_SPECIFIER(token, specifier, name)                         \
1640                 case token:                                                     \
1641                         next_token();                                               \
1642                         if(type_specifiers & specifier) {                           \
1643                                 errorf(HERE, "multiple " name " type specifiers given"); \
1644                         } else {                                                    \
1645                                 type_specifiers |= specifier;                           \
1646                         }                                                           \
1647                         break;
1648
1649                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1650                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1651                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1652                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1653                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1654                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1655                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1656                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1657                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1658 #ifdef PROVIDE_COMPLEX
1659                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1660                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1661 #endif
1662                 case T_forceinline:
1663                         /* only in microsoft mode */
1664                         specifiers->decl_modifiers |= DM_FORCEINLINE;
1665
1666                 case T_inline:
1667                         next_token();
1668                         specifiers->is_inline = true;
1669                         break;
1670
1671                 case T_long:
1672                         next_token();
1673                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1674                                 errorf(HERE, "multiple type specifiers given");
1675                         } else if(type_specifiers & SPECIFIER_LONG) {
1676                                 type_specifiers |= SPECIFIER_LONG_LONG;
1677                         } else {
1678                                 type_specifiers |= SPECIFIER_LONG;
1679                         }
1680                         break;
1681
1682                 /* TODO: if type != NULL for the following rules should issue
1683                  * an error */
1684                 case T_struct: {
1685                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1686
1687                         type->compound.declaration = parse_compound_type_specifier(true);
1688                         break;
1689                 }
1690                 case T_union: {
1691                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
1692
1693                         type->compound.declaration = parse_compound_type_specifier(false);
1694                         break;
1695                 }
1696                 case T_enum:
1697                         type = parse_enum_specifier();
1698                         break;
1699                 case T___typeof__:
1700                         type = parse_typeof();
1701                         break;
1702                 case T___builtin_va_list:
1703                         type = duplicate_type(type_valist);
1704                         next_token();
1705                         break;
1706
1707                 case T___attribute__:
1708                         /* TODO */
1709                         parse_attributes();
1710                         break;
1711
1712                 case T_IDENTIFIER: {
1713                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1714
1715                         if(typedef_type == NULL)
1716                                 goto finish_specifiers;
1717
1718                         next_token();
1719                         type = typedef_type;
1720                         break;
1721                 }
1722
1723                 /* function specifier */
1724                 default:
1725                         goto finish_specifiers;
1726                 }
1727         }
1728
1729 finish_specifiers:
1730
1731         if(type == NULL) {
1732                 atomic_type_kind_t atomic_type;
1733
1734                 /* match valid basic types */
1735                 switch(type_specifiers) {
1736                 case SPECIFIER_VOID:
1737                         atomic_type = ATOMIC_TYPE_VOID;
1738                         break;
1739                 case SPECIFIER_CHAR:
1740                         atomic_type = ATOMIC_TYPE_CHAR;
1741                         break;
1742                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1743                         atomic_type = ATOMIC_TYPE_SCHAR;
1744                         break;
1745                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1746                         atomic_type = ATOMIC_TYPE_UCHAR;
1747                         break;
1748                 case SPECIFIER_SHORT:
1749                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1750                 case SPECIFIER_SHORT | SPECIFIER_INT:
1751                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1752                         atomic_type = ATOMIC_TYPE_SHORT;
1753                         break;
1754                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1755                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1756                         atomic_type = ATOMIC_TYPE_USHORT;
1757                         break;
1758                 case SPECIFIER_INT:
1759                 case SPECIFIER_SIGNED:
1760                 case SPECIFIER_SIGNED | SPECIFIER_INT:
1761                         atomic_type = ATOMIC_TYPE_INT;
1762                         break;
1763                 case SPECIFIER_UNSIGNED:
1764                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
1765                         atomic_type = ATOMIC_TYPE_UINT;
1766                         break;
1767                 case SPECIFIER_LONG:
1768                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
1769                 case SPECIFIER_LONG | SPECIFIER_INT:
1770                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1771                         atomic_type = ATOMIC_TYPE_LONG;
1772                         break;
1773                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
1774                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
1775                         atomic_type = ATOMIC_TYPE_ULONG;
1776                         break;
1777                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1778                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1779                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
1780                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1781                         | SPECIFIER_INT:
1782                         atomic_type = ATOMIC_TYPE_LONGLONG;
1783                         break;
1784                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
1785                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
1786                         | SPECIFIER_INT:
1787                         atomic_type = ATOMIC_TYPE_ULONGLONG;
1788                         break;
1789                 case SPECIFIER_FLOAT:
1790                         atomic_type = ATOMIC_TYPE_FLOAT;
1791                         break;
1792                 case SPECIFIER_DOUBLE:
1793                         atomic_type = ATOMIC_TYPE_DOUBLE;
1794                         break;
1795                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
1796                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
1797                         break;
1798                 case SPECIFIER_BOOL:
1799                         atomic_type = ATOMIC_TYPE_BOOL;
1800                         break;
1801 #ifdef PROVIDE_COMPLEX
1802                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
1803                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
1804                         break;
1805                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1806                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
1807                         break;
1808                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
1809                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
1810                         break;
1811                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
1812                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
1813                         break;
1814                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1815                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
1816                         break;
1817                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
1818                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
1819                         break;
1820 #endif
1821                 default:
1822                         /* invalid specifier combination, give an error message */
1823                         if(type_specifiers == 0) {
1824                                 if (! strict_mode) {
1825                                         warningf(HERE, "no type specifiers in declaration, using int");
1826                                         atomic_type = ATOMIC_TYPE_INT;
1827                                         break;
1828                                 } else {
1829                                         errorf(HERE, "no type specifiers given in declaration");
1830                                 }
1831                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
1832                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
1833                                 errorf(HERE, "signed and unsigned specifiers gives");
1834                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
1835                                 errorf(HERE, "only integer types can be signed or unsigned");
1836                         } else {
1837                                 errorf(HERE, "multiple datatypes in declaration");
1838                         }
1839                         atomic_type = ATOMIC_TYPE_INVALID;
1840                 }
1841
1842                 type               = allocate_type_zero(TYPE_ATOMIC);
1843                 type->atomic.akind = atomic_type;
1844                 newtype            = 1;
1845         } else {
1846                 if(type_specifiers != 0) {
1847                         errorf(HERE, "multiple datatypes in declaration");
1848                 }
1849         }
1850
1851         type->base.qualifiers = type_qualifiers;
1852
1853         type_t *result = typehash_insert(type);
1854         if(newtype && result != type) {
1855                 free_type(type);
1856         }
1857
1858         specifiers->type = result;
1859 }
1860
1861 static type_qualifiers_t parse_type_qualifiers(void)
1862 {
1863         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
1864
1865         while(true) {
1866                 switch(token.type) {
1867                 /* type qualifiers */
1868                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1869                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1870                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1871
1872                 default:
1873                         return type_qualifiers;
1874                 }
1875         }
1876 }
1877
1878 static declaration_t *parse_identifier_list(void)
1879 {
1880         declaration_t *declarations     = NULL;
1881         declaration_t *last_declaration = NULL;
1882         do {
1883                 declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
1884
1885                 declaration->source_position = token.source_position;
1886                 declaration->symbol          = token.v.symbol;
1887                 next_token();
1888
1889                 if(last_declaration != NULL) {
1890                         last_declaration->next = declaration;
1891                 } else {
1892                         declarations = declaration;
1893                 }
1894                 last_declaration = declaration;
1895
1896                 if(token.type != ',')
1897                         break;
1898                 next_token();
1899         } while(token.type == T_IDENTIFIER);
1900
1901         return declarations;
1902 }
1903
1904 static void semantic_parameter(declaration_t *declaration)
1905 {
1906         /* TODO: improve error messages */
1907
1908         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
1909                 errorf(HERE, "typedef not allowed in parameter list");
1910         } else if(declaration->storage_class != STORAGE_CLASS_NONE
1911                         && declaration->storage_class != STORAGE_CLASS_REGISTER) {
1912                 errorf(HERE, "parameter may only have none or register storage class");
1913         }
1914
1915         type_t *orig_type = declaration->type;
1916         if(orig_type == NULL)
1917                 return;
1918         type_t *type = skip_typeref(orig_type);
1919
1920         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
1921          * into a pointer. Â§ 6.7.5.3 (7) */
1922         if (is_type_array(type)) {
1923                 const array_type_t *arr_type     = &type->array;
1924                 type_t             *element_type = arr_type->element_type;
1925
1926                 type = make_pointer_type(element_type, type->base.qualifiers);
1927
1928                 declaration->type = type;
1929         }
1930
1931         if(is_type_incomplete(type)) {
1932                 errorf(HERE, "incomplete type ('%T') not allowed for parameter '%Y'",
1933                        orig_type, declaration->symbol);
1934         }
1935 }
1936
1937 static declaration_t *parse_parameter(void)
1938 {
1939         declaration_specifiers_t specifiers;
1940         memset(&specifiers, 0, sizeof(specifiers));
1941
1942         parse_declaration_specifiers(&specifiers);
1943
1944         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
1945
1946         semantic_parameter(declaration);
1947
1948         return declaration;
1949 }
1950
1951 static declaration_t *parse_parameters(function_type_t *type)
1952 {
1953         if(token.type == T_IDENTIFIER) {
1954                 symbol_t *symbol = token.v.symbol;
1955                 if(!is_typedef_symbol(symbol)) {
1956                         type->kr_style_parameters = true;
1957                         return parse_identifier_list();
1958                 }
1959         }
1960
1961         if(token.type == ')') {
1962                 type->unspecified_parameters = 1;
1963                 return NULL;
1964         }
1965         if(token.type == T_void && look_ahead(1)->type == ')') {
1966                 next_token();
1967                 return NULL;
1968         }
1969
1970         declaration_t        *declarations = NULL;
1971         declaration_t        *declaration;
1972         declaration_t        *last_declaration = NULL;
1973         function_parameter_t *parameter;
1974         function_parameter_t *last_parameter = NULL;
1975
1976         while(true) {
1977                 switch(token.type) {
1978                 case T_DOTDOTDOT:
1979                         next_token();
1980                         type->variadic = 1;
1981                         return declarations;
1982
1983                 case T_IDENTIFIER:
1984                 case T___extension__:
1985                 DECLARATION_START
1986                         declaration = parse_parameter();
1987
1988                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
1989                         memset(parameter, 0, sizeof(parameter[0]));
1990                         parameter->type = declaration->type;
1991
1992                         if(last_parameter != NULL) {
1993                                 last_declaration->next = declaration;
1994                                 last_parameter->next   = parameter;
1995                         } else {
1996                                 type->parameters = parameter;
1997                                 declarations     = declaration;
1998                         }
1999                         last_parameter   = parameter;
2000                         last_declaration = declaration;
2001                         break;
2002
2003                 default:
2004                         return declarations;
2005                 }
2006                 if(token.type != ',')
2007                         return declarations;
2008                 next_token();
2009         }
2010 }
2011
2012 typedef enum {
2013         CONSTRUCT_INVALID,
2014         CONSTRUCT_POINTER,
2015         CONSTRUCT_FUNCTION,
2016         CONSTRUCT_ARRAY
2017 } construct_type_type_t;
2018
2019 typedef struct construct_type_t construct_type_t;
2020 struct construct_type_t {
2021         construct_type_type_t  type;
2022         construct_type_t      *next;
2023 };
2024
2025 typedef struct parsed_pointer_t parsed_pointer_t;
2026 struct parsed_pointer_t {
2027         construct_type_t  construct_type;
2028         type_qualifiers_t type_qualifiers;
2029 };
2030
2031 typedef struct construct_function_type_t construct_function_type_t;
2032 struct construct_function_type_t {
2033         construct_type_t  construct_type;
2034         type_t           *function_type;
2035 };
2036
2037 typedef struct parsed_array_t parsed_array_t;
2038 struct parsed_array_t {
2039         construct_type_t  construct_type;
2040         type_qualifiers_t type_qualifiers;
2041         bool              is_static;
2042         bool              is_variable;
2043         expression_t     *size;
2044 };
2045
2046 typedef struct construct_base_type_t construct_base_type_t;
2047 struct construct_base_type_t {
2048         construct_type_t  construct_type;
2049         type_t           *type;
2050 };
2051
2052 static construct_type_t *parse_pointer_declarator(void)
2053 {
2054         eat('*');
2055
2056         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2057         memset(pointer, 0, sizeof(pointer[0]));
2058         pointer->construct_type.type = CONSTRUCT_POINTER;
2059         pointer->type_qualifiers     = parse_type_qualifiers();
2060
2061         return (construct_type_t*) pointer;
2062 }
2063
2064 static construct_type_t *parse_array_declarator(void)
2065 {
2066         eat('[');
2067
2068         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2069         memset(array, 0, sizeof(array[0]));
2070         array->construct_type.type = CONSTRUCT_ARRAY;
2071
2072         if(token.type == T_static) {
2073                 array->is_static = true;
2074                 next_token();
2075         }
2076
2077         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2078         if(type_qualifiers != 0) {
2079                 if(token.type == T_static) {
2080                         array->is_static = true;
2081                         next_token();
2082                 }
2083         }
2084         array->type_qualifiers = type_qualifiers;
2085
2086         if(token.type == '*' && look_ahead(1)->type == ']') {
2087                 array->is_variable = true;
2088                 next_token();
2089         } else if(token.type != ']') {
2090                 array->size = parse_assignment_expression();
2091         }
2092
2093         expect(']');
2094
2095         return (construct_type_t*) array;
2096 }
2097
2098 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2099 {
2100         eat('(');
2101
2102         type_t *type = allocate_type_zero(TYPE_FUNCTION);
2103
2104         declaration_t *parameters = parse_parameters(&type->function);
2105         if(declaration != NULL) {
2106                 declaration->context.declarations = parameters;
2107         }
2108
2109         construct_function_type_t *construct_function_type =
2110                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2111         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2112         construct_function_type->construct_type.type = CONSTRUCT_FUNCTION;
2113         construct_function_type->function_type       = type;
2114
2115         expect(')');
2116
2117         return (construct_type_t*) construct_function_type;
2118 }
2119
2120 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2121                 bool may_be_abstract)
2122 {
2123         /* construct a single linked list of construct_type_t's which describe
2124          * how to construct the final declarator type */
2125         construct_type_t *first = NULL;
2126         construct_type_t *last  = NULL;
2127
2128         /* pointers */
2129         while(token.type == '*') {
2130                 construct_type_t *type = parse_pointer_declarator();
2131
2132                 if(last == NULL) {
2133                         first = type;
2134                         last  = type;
2135                 } else {
2136                         last->next = type;
2137                         last       = type;
2138                 }
2139         }
2140
2141         /* TODO: find out if this is correct */
2142         parse_attributes();
2143
2144         construct_type_t *inner_types = NULL;
2145
2146         switch(token.type) {
2147         case T_IDENTIFIER:
2148                 if(declaration == NULL) {
2149                         errorf(HERE, "no identifier expected in typename");
2150                 } else {
2151                         declaration->symbol          = token.v.symbol;
2152                         declaration->source_position = token.source_position;
2153                 }
2154                 next_token();
2155                 break;
2156         case '(':
2157                 next_token();
2158                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2159                 expect(')');
2160                 break;
2161         default:
2162                 if(may_be_abstract)
2163                         break;
2164                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2165                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2166                  * eat '}' */
2167                 if(token.type == '}' && current_function == NULL) {
2168                         next_token();
2169                 } else {
2170                         eat_statement();
2171                 }
2172                 return NULL;
2173         }
2174
2175         construct_type_t *p = last;
2176
2177         while(true) {
2178                 construct_type_t *type;
2179                 switch(token.type) {
2180                 case '(':
2181                         type = parse_function_declarator(declaration);
2182                         break;
2183                 case '[':
2184                         type = parse_array_declarator();
2185                         break;
2186                 default:
2187                         goto declarator_finished;
2188                 }
2189
2190                 /* insert in the middle of the list (behind p) */
2191                 if(p != NULL) {
2192                         type->next = p->next;
2193                         p->next    = type;
2194                 } else {
2195                         type->next = first;
2196                         first      = type;
2197                 }
2198                 if(last == p) {
2199                         last = type;
2200                 }
2201         }
2202
2203 declarator_finished:
2204         parse_attributes();
2205
2206         /* append inner_types at the end of the list, we don't to set last anymore
2207          * as it's not needed anymore */
2208         if(last == NULL) {
2209                 assert(first == NULL);
2210                 first = inner_types;
2211         } else {
2212                 last->next = inner_types;
2213         }
2214
2215         return first;
2216 }
2217
2218 static type_t *construct_declarator_type(construct_type_t *construct_list,
2219                                          type_t *type)
2220 {
2221         construct_type_t *iter = construct_list;
2222         for( ; iter != NULL; iter = iter->next) {
2223                 switch(iter->type) {
2224                 case CONSTRUCT_INVALID:
2225                         panic("invalid type construction found");
2226                 case CONSTRUCT_FUNCTION: {
2227                         construct_function_type_t *construct_function_type
2228                                 = (construct_function_type_t*) iter;
2229
2230                         type_t *function_type = construct_function_type->function_type;
2231
2232                         function_type->function.return_type = type;
2233
2234                         type = function_type;
2235                         break;
2236                 }
2237
2238                 case CONSTRUCT_POINTER: {
2239                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2240                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER);
2241                         pointer_type->pointer.points_to  = type;
2242                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2243
2244                         type = pointer_type;
2245                         break;
2246                 }
2247
2248                 case CONSTRUCT_ARRAY: {
2249                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2250                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY);
2251
2252                         array_type->base.qualifiers    = parsed_array->type_qualifiers;
2253                         array_type->array.element_type = type;
2254                         array_type->array.is_static    = parsed_array->is_static;
2255                         array_type->array.is_variable  = parsed_array->is_variable;
2256                         array_type->array.size         = parsed_array->size;
2257
2258                         type = array_type;
2259                         break;
2260                 }
2261                 }
2262
2263                 type_t *hashed_type = typehash_insert(type);
2264                 if(hashed_type != type) {
2265                         /* the function type was constructed earlier freeing it here will
2266                          * destroy other types... */
2267                         if(iter->type != CONSTRUCT_FUNCTION) {
2268                                 free_type(type);
2269                         }
2270                         type = hashed_type;
2271                 }
2272         }
2273
2274         return type;
2275 }
2276
2277 static declaration_t *parse_declarator(
2278                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2279 {
2280         type_t        *type         = specifiers->type;
2281         declaration_t *declaration  = allocate_ast_zero(sizeof(declaration[0]));
2282         declaration->storage_class  = specifiers->storage_class;
2283         declaration->modifiers      = specifiers->decl_modifiers;
2284         declaration->is_inline      = specifiers->is_inline;
2285
2286         construct_type_t *construct_type
2287                 = parse_inner_declarator(declaration, may_be_abstract);
2288         declaration->type = construct_declarator_type(construct_type, type);
2289
2290         if(construct_type != NULL) {
2291                 obstack_free(&temp_obst, construct_type);
2292         }
2293
2294         return declaration;
2295 }
2296
2297 static type_t *parse_abstract_declarator(type_t *base_type)
2298 {
2299         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2300
2301         type_t *result = construct_declarator_type(construct_type, base_type);
2302         if(construct_type != NULL) {
2303                 obstack_free(&temp_obst, construct_type);
2304         }
2305
2306         return result;
2307 }
2308
2309 static declaration_t *append_declaration(declaration_t* const declaration)
2310 {
2311         if (last_declaration != NULL) {
2312                 last_declaration->next = declaration;
2313         } else {
2314                 context->declarations = declaration;
2315         }
2316         last_declaration = declaration;
2317         return declaration;
2318 }
2319
2320 static declaration_t *internal_record_declaration(
2321         declaration_t *const declaration,
2322         const bool is_function_definition)
2323 {
2324         const symbol_t *const symbol  = declaration->symbol;
2325         const namespace_t     namespc = (namespace_t)declaration->namespc;
2326
2327         const type_t *const type = skip_typeref(declaration->type);
2328         if (is_type_function(type) && type->function.unspecified_parameters) {
2329                 warningf(declaration->source_position,
2330                          "function declaration '%#T' is not a prototype",
2331                          type, declaration->symbol);
2332         }
2333
2334         declaration_t *const previous_declaration = get_declaration(symbol, namespc);
2335         assert(declaration != previous_declaration);
2336         if (previous_declaration != NULL
2337                         && previous_declaration->parent_context == context) {
2338                 /* can happen for K&R style declarations */
2339                 if(previous_declaration->type == NULL) {
2340                         previous_declaration->type = declaration->type;
2341                 }
2342
2343                 const type_t *const prev_type = skip_typeref(previous_declaration->type);
2344                 if (!types_compatible(type, prev_type)) {
2345                         errorf(declaration->source_position,
2346                                 "declaration '%#T' is incompatible with previous declaration '%#T'",
2347                                 type, symbol, previous_declaration->type, symbol);
2348                         errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2349                 } else {
2350                         unsigned old_storage_class = previous_declaration->storage_class;
2351                         unsigned new_storage_class = declaration->storage_class;
2352
2353                         /* pretend no storage class means extern for function declarations
2354                          * (except if the previous declaration is neither none nor extern) */
2355                         if (is_type_function(type)) {
2356                                 switch (old_storage_class) {
2357                                         case STORAGE_CLASS_NONE:
2358                                                 old_storage_class = STORAGE_CLASS_EXTERN;
2359
2360                                         case STORAGE_CLASS_EXTERN:
2361                                                 if (new_storage_class == STORAGE_CLASS_NONE && !is_function_definition) {
2362                                                         new_storage_class = STORAGE_CLASS_EXTERN;
2363                                                 }
2364                                                 break;
2365
2366                                         default: break;
2367                                 }
2368                         }
2369
2370                         if (old_storage_class == STORAGE_CLASS_EXTERN &&
2371                             new_storage_class == STORAGE_CLASS_EXTERN) {
2372 warn_redundant_declaration:
2373                                         warningf(declaration->source_position, "redundant declaration for '%Y'", symbol);
2374                                         warningf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2375                         } else if (current_function == NULL) {
2376                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
2377                                     new_storage_class == STORAGE_CLASS_STATIC) {
2378                                         errorf(declaration->source_position, "static declaration of '%Y' follows non-static declaration", symbol);
2379                                         errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2380                                 } else {
2381                                         if (old_storage_class != STORAGE_CLASS_EXTERN) {
2382                                                 goto warn_redundant_declaration;
2383                                         }
2384                                         if (new_storage_class == STORAGE_CLASS_NONE) {
2385                                                 previous_declaration->storage_class = STORAGE_CLASS_NONE;
2386                                         }
2387                                 }
2388                         } else {
2389                                 if (old_storage_class == new_storage_class) {
2390                                         errorf(declaration->source_position, "redeclaration of '%Y'", symbol);
2391                                 } else {
2392                                         errorf(declaration->source_position, "redeclaration of '%Y' with different linkage", symbol);
2393                                 }
2394                                 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2395                         }
2396                 }
2397                 return previous_declaration;
2398         }
2399
2400         assert(declaration->parent_context == NULL);
2401         assert(declaration->symbol != NULL);
2402         assert(context != NULL);
2403
2404         declaration->parent_context = context;
2405
2406         environment_push(declaration);
2407         return append_declaration(declaration);
2408 }
2409
2410 static declaration_t *record_declaration(declaration_t *declaration)
2411 {
2412         return internal_record_declaration(declaration, false);
2413 }
2414
2415 static declaration_t *record_function_definition(declaration_t *const declaration)
2416 {
2417         return internal_record_declaration(declaration, true);
2418 }
2419
2420 static void parser_error_multiple_definition(declaration_t *declaration,
2421                 const source_position_t source_position)
2422 {
2423         errorf(source_position, "multiple definition of symbol '%Y'",
2424                declaration->symbol);
2425         errorf(declaration->source_position,
2426                "this is the location of the previous definition.");
2427 }
2428
2429 static bool is_declaration_specifier(const token_t *token,
2430                                      bool only_type_specifiers)
2431 {
2432         switch(token->type) {
2433                 TYPE_SPECIFIERS
2434                         return true;
2435                 case T_IDENTIFIER:
2436                         return is_typedef_symbol(token->v.symbol);
2437
2438                 case T___extension__:
2439                 STORAGE_CLASSES
2440                 TYPE_QUALIFIERS
2441                         return !only_type_specifiers;
2442
2443                 default:
2444                         return false;
2445         }
2446 }
2447
2448 static void parse_init_declarator_rest(declaration_t *declaration)
2449 {
2450         eat('=');
2451
2452         type_t *orig_type = declaration->type;
2453         type_t *type      = NULL;
2454         if(orig_type != NULL)
2455                 type = skip_typeref(orig_type);
2456
2457         if(declaration->init.initializer != NULL) {
2458                 parser_error_multiple_definition(declaration, token.source_position);
2459         }
2460
2461         initializer_t *initializer = parse_initializer(type);
2462
2463         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
2464          * the array type size */
2465         if(type != NULL && is_type_array(type) && initializer != NULL) {
2466                 array_type_t *array_type = &type->array;
2467
2468                 if(array_type->size == NULL) {
2469                         expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2470
2471                         cnst->base.datatype = type_size_t;
2472
2473                         switch (initializer->kind) {
2474                                 case INITIALIZER_LIST: {
2475                                         initializer_list_t *const list = &initializer->list;
2476                                         cnst->conste.v.int_value = list->len;
2477                                         break;
2478                                 }
2479
2480                                 case INITIALIZER_STRING: {
2481                                         initializer_string_t *const string = &initializer->string;
2482                                         cnst->conste.v.int_value = strlen(string->string) + 1;
2483                                         break;
2484                                 }
2485
2486                                 case INITIALIZER_WIDE_STRING: {
2487                                         initializer_wide_string_t *const string = &initializer->wide_string;
2488                                         cnst->conste.v.int_value = string->string.size;
2489                                         break;
2490                                 }
2491
2492                                 default:
2493                                         panic("invalid initializer type");
2494                         }
2495
2496                         array_type->size = cnst;
2497                 }
2498         }
2499
2500         if(type != NULL && is_type_function(type)) {
2501                 errorf(declaration->source_position,
2502                        "initializers not allowed for function types at declator '%Y' (type '%T')",
2503                        declaration->symbol, orig_type);
2504         } else {
2505                 declaration->init.initializer = initializer;
2506         }
2507 }
2508
2509 /* parse rest of a declaration without any declarator */
2510 static void parse_anonymous_declaration_rest(
2511                 const declaration_specifiers_t *specifiers,
2512                 parsed_declaration_func finished_declaration)
2513 {
2514         eat(';');
2515
2516         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
2517
2518         declaration->type            = specifiers->type;
2519         declaration->storage_class   = specifiers->storage_class;
2520         declaration->source_position = specifiers->source_position;
2521
2522         if (declaration->storage_class != STORAGE_CLASS_NONE) {
2523                 warningf(declaration->source_position, "useless storage class in empty declaration");
2524         }
2525
2526         type_t *type = declaration->type;
2527         switch (type->kind) {
2528                 case TYPE_COMPOUND_STRUCT:
2529                 case TYPE_COMPOUND_UNION: {
2530                         const compound_type_t *compound_type = &type->compound;
2531                         if (compound_type->declaration->symbol == NULL) {
2532                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
2533                         }
2534                         break;
2535                 }
2536
2537                 case TYPE_ENUM:
2538                         break;
2539
2540                 default:
2541                         warningf(declaration->source_position, "empty declaration");
2542                         break;
2543         }
2544
2545         finished_declaration(declaration);
2546 }
2547
2548 static void parse_declaration_rest(declaration_t *ndeclaration,
2549                 const declaration_specifiers_t *specifiers,
2550                 parsed_declaration_func finished_declaration)
2551 {
2552         while(true) {
2553                 declaration_t *declaration = finished_declaration(ndeclaration);
2554
2555                 type_t *orig_type = declaration->type;
2556                 type_t *type      = skip_typeref(orig_type);
2557
2558                 if(type->kind != TYPE_FUNCTION && declaration->is_inline) {
2559                         warningf(declaration->source_position,
2560                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2561                 }
2562
2563                 if(token.type == '=') {
2564                         parse_init_declarator_rest(declaration);
2565                 }
2566
2567                 if(token.type != ',')
2568                         break;
2569                 eat(',');
2570
2571                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2572         }
2573         expect_void(';');
2574 }
2575
2576 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2577 {
2578         symbol_t *symbol  = declaration->symbol;
2579         if(symbol == NULL) {
2580                 errorf(HERE, "anonymous declaration not valid as function parameter");
2581                 return declaration;
2582         }
2583         namespace_t namespc = (namespace_t) declaration->namespc;
2584         if(namespc != NAMESPACE_NORMAL) {
2585                 return record_declaration(declaration);
2586         }
2587
2588         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2589         if(previous_declaration == NULL ||
2590                         previous_declaration->parent_context != context) {
2591                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2592                        symbol);
2593                 return declaration;
2594         }
2595
2596         if(previous_declaration->type == NULL) {
2597                 previous_declaration->type           = declaration->type;
2598                 previous_declaration->storage_class  = declaration->storage_class;
2599                 previous_declaration->parent_context = context;
2600                 return previous_declaration;
2601         } else {
2602                 return record_declaration(declaration);
2603         }
2604 }
2605
2606 static void parse_declaration(parsed_declaration_func finished_declaration)
2607 {
2608         declaration_specifiers_t specifiers;
2609         memset(&specifiers, 0, sizeof(specifiers));
2610         parse_declaration_specifiers(&specifiers);
2611
2612         if(token.type == ';') {
2613                 parse_anonymous_declaration_rest(&specifiers, finished_declaration);
2614         } else {
2615                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2616                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2617         }
2618 }
2619
2620 static void parse_kr_declaration_list(declaration_t *declaration)
2621 {
2622         type_t *type = skip_typeref(declaration->type);
2623         if(!is_type_function(type))
2624                 return;
2625
2626         if(!type->function.kr_style_parameters)
2627                 return;
2628
2629         /* push function parameters */
2630         int         top          = environment_top();
2631         context_t  *last_context = context;
2632         set_context(&declaration->context);
2633
2634         declaration_t *parameter = declaration->context.declarations;
2635         for( ; parameter != NULL; parameter = parameter->next) {
2636                 assert(parameter->parent_context == NULL);
2637                 parameter->parent_context = context;
2638                 environment_push(parameter);
2639         }
2640
2641         /* parse declaration list */
2642         while(is_declaration_specifier(&token, false)) {
2643                 parse_declaration(finished_kr_declaration);
2644         }
2645
2646         /* pop function parameters */
2647         assert(context == &declaration->context);
2648         set_context(last_context);
2649         environment_pop_to(top);
2650
2651         /* update function type */
2652         type_t *new_type = duplicate_type(type);
2653         new_type->function.kr_style_parameters = false;
2654
2655         function_parameter_t *parameters     = NULL;
2656         function_parameter_t *last_parameter = NULL;
2657
2658         declaration_t *parameter_declaration = declaration->context.declarations;
2659         for( ; parameter_declaration != NULL;
2660                         parameter_declaration = parameter_declaration->next) {
2661                 type_t *parameter_type = parameter_declaration->type;
2662                 if(parameter_type == NULL) {
2663                         if (strict_mode) {
2664                                 errorf(HERE, "no type specified for function parameter '%Y'",
2665                                        parameter_declaration->symbol);
2666                         } else {
2667                                 warningf(HERE, "no type specified for function parameter '%Y', using int",
2668                                          parameter_declaration->symbol);
2669                                 parameter_type              = type_int;
2670                                 parameter_declaration->type = parameter_type;
2671                         }
2672                 }
2673
2674                 semantic_parameter(parameter_declaration);
2675                 parameter_type = parameter_declaration->type;
2676
2677                 function_parameter_t *function_parameter
2678                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2679                 memset(function_parameter, 0, sizeof(function_parameter[0]));
2680
2681                 function_parameter->type = parameter_type;
2682                 if(last_parameter != NULL) {
2683                         last_parameter->next = function_parameter;
2684                 } else {
2685                         parameters = function_parameter;
2686                 }
2687                 last_parameter = function_parameter;
2688         }
2689         new_type->function.parameters = parameters;
2690
2691         type = typehash_insert(new_type);
2692         if(type != new_type) {
2693                 obstack_free(type_obst, new_type);
2694         }
2695
2696         declaration->type = type;
2697 }
2698
2699 /**
2700  * Check if all labels are defined in the current function.
2701  */
2702 static void check_for_missing_labels(void)
2703 {
2704         bool first_err = true;
2705         for (const goto_statement_t *goto_statement = goto_first;
2706              goto_statement != NULL;
2707              goto_statement = goto_statement->next) {
2708                  const declaration_t *label = goto_statement->label;
2709
2710                  if (label->source_position.input_name == NULL) {
2711                          if (first_err) {
2712                                  first_err = false;
2713                                  diagnosticf("%s: In function '%Y':\n",
2714                                          current_function->source_position.input_name,
2715                                          current_function->symbol);
2716                          }
2717                          errorf(goto_statement->statement.source_position,
2718                                  "label '%Y' used but not defined", label->symbol);
2719                  }
2720         }
2721         goto_first = goto_last = NULL;
2722 }
2723
2724 static void parse_external_declaration(void)
2725 {
2726         /* function-definitions and declarations both start with declaration
2727          * specifiers */
2728         declaration_specifiers_t specifiers;
2729         memset(&specifiers, 0, sizeof(specifiers));
2730         parse_declaration_specifiers(&specifiers);
2731
2732         /* must be a declaration */
2733         if(token.type == ';') {
2734                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
2735                 return;
2736         }
2737
2738         /* declarator is common to both function-definitions and declarations */
2739         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2740
2741         /* must be a declaration */
2742         if(token.type == ',' || token.type == '=' || token.type == ';') {
2743                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
2744                 return;
2745         }
2746
2747         /* must be a function definition */
2748         parse_kr_declaration_list(ndeclaration);
2749
2750         if(token.type != '{') {
2751                 parse_error_expected("while parsing function definition", '{', 0);
2752                 eat_statement();
2753                 return;
2754         }
2755
2756         type_t *type = ndeclaration->type;
2757         if(type == NULL) {
2758                 eat_block();
2759                 return;
2760         }
2761
2762         /* note that we don't skip typerefs: the standard doesn't allow them here
2763          * (so we can't use is_type_function here) */
2764         if(type->kind != TYPE_FUNCTION) {
2765                 errorf(HERE, "declarator '%#T' has a body but is not a function type",
2766                        type, ndeclaration->symbol);
2767                 eat_block();
2768                 return;
2769         }
2770
2771         /* Â§ 6.7.5.3 (14) a function definition with () means no
2772          * parameters (and not unspecified parameters) */
2773         if(type->function.unspecified_parameters) {
2774                 type_t *duplicate = duplicate_type(type);
2775                 duplicate->function.unspecified_parameters = false;
2776
2777                 type = typehash_insert(duplicate);
2778                 if(type != duplicate) {
2779                         obstack_free(type_obst, duplicate);
2780                 }
2781                 ndeclaration->type = type;
2782         }
2783
2784         declaration_t *const declaration = record_function_definition(ndeclaration);
2785         if(ndeclaration != declaration) {
2786                 declaration->context = ndeclaration->context;
2787         }
2788         type = skip_typeref(declaration->type);
2789
2790         /* push function parameters and switch context */
2791         int         top          = environment_top();
2792         context_t  *last_context = context;
2793         set_context(&declaration->context);
2794
2795         declaration_t *parameter = declaration->context.declarations;
2796         for( ; parameter != NULL; parameter = parameter->next) {
2797                 if(parameter->parent_context == &ndeclaration->context) {
2798                         parameter->parent_context = context;
2799                 }
2800                 assert(parameter->parent_context == NULL
2801                                 || parameter->parent_context == context);
2802                 parameter->parent_context = context;
2803                 environment_push(parameter);
2804         }
2805
2806         if(declaration->init.statement != NULL) {
2807                 parser_error_multiple_definition(declaration, token.source_position);
2808                 eat_block();
2809                 goto end_of_parse_external_declaration;
2810         } else {
2811                 /* parse function body */
2812                 int            label_stack_top      = label_top();
2813                 declaration_t *old_current_function = current_function;
2814                 current_function                    = declaration;
2815
2816                 declaration->init.statement = parse_compound_statement();
2817                 check_for_missing_labels();
2818
2819                 assert(current_function == declaration);
2820                 current_function = old_current_function;
2821                 label_pop_to(label_stack_top);
2822         }
2823
2824 end_of_parse_external_declaration:
2825         assert(context == &declaration->context);
2826         set_context(last_context);
2827         environment_pop_to(top);
2828 }
2829
2830 static type_t *make_bitfield_type(type_t *base, expression_t *size)
2831 {
2832         type_t *type        = allocate_type_zero(TYPE_BITFIELD);
2833         type->bitfield.base = base;
2834         type->bitfield.size = size;
2835
2836         return type;
2837 }
2838
2839 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2840 {
2841         /* TODO: check constraints for struct declarations (in specifiers) */
2842         while(1) {
2843                 declaration_t *declaration;
2844
2845                 if(token.type == ':') {
2846                         next_token();
2847
2848                         type_t *base_type = specifiers->type;
2849                         expression_t *size = parse_constant_expression();
2850
2851                         type_t *type = make_bitfield_type(base_type, size);
2852
2853                         declaration = allocate_ast_zero(sizeof(declaration[0]));
2854
2855                         declaration->namespc         = NAMESPACE_NORMAL;
2856                         declaration->storage_class   = STORAGE_CLASS_NONE;
2857                         declaration->source_position = token.source_position;
2858                         declaration->modifiers       = specifiers->decl_modifiers;
2859                         declaration->type            = type;
2860
2861                         record_declaration(declaration);
2862                 } else {
2863                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
2864
2865                         if(token.type == ':') {
2866                                 next_token();
2867                                 expression_t *size = parse_constant_expression();
2868
2869                                 type_t *type = make_bitfield_type(declaration->type, size);
2870                                 declaration->type = type;
2871                         }
2872                 }
2873                 record_declaration(declaration);
2874
2875                 if(token.type != ',')
2876                         break;
2877                 next_token();
2878         }
2879         expect_void(';');
2880 }
2881
2882 static void parse_compound_type_entries(void)
2883 {
2884         eat('{');
2885
2886         while(token.type != '}' && token.type != T_EOF) {
2887                 declaration_specifiers_t specifiers;
2888                 memset(&specifiers, 0, sizeof(specifiers));
2889                 parse_declaration_specifiers(&specifiers);
2890
2891                 parse_struct_declarators(&specifiers);
2892         }
2893         if(token.type == T_EOF) {
2894                 errorf(HERE, "EOF while parsing struct");
2895         }
2896         next_token();
2897 }
2898
2899 static type_t *parse_typename(void)
2900 {
2901         declaration_specifiers_t specifiers;
2902         memset(&specifiers, 0, sizeof(specifiers));
2903         parse_declaration_specifiers(&specifiers);
2904         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2905                 /* TODO: improve error message, user does probably not know what a
2906                  * storage class is...
2907                  */
2908                 errorf(HERE, "typename may not have a storage class");
2909         }
2910
2911         type_t *result = parse_abstract_declarator(specifiers.type);
2912
2913         return result;
2914 }
2915
2916
2917
2918
2919 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2920 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2921                                                           expression_t *left);
2922
2923 typedef struct expression_parser_function_t expression_parser_function_t;
2924 struct expression_parser_function_t {
2925         unsigned                         precedence;
2926         parse_expression_function        parser;
2927         unsigned                         infix_precedence;
2928         parse_expression_infix_function  infix_parser;
2929 };
2930
2931 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2932
2933 /**
2934  * Creates a new invalid expression.
2935  */
2936 static expression_t *create_invalid_expression(void)
2937 {
2938         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2939         expression->base.source_position = token.source_position;
2940         return expression;
2941 }
2942
2943 static expression_t *expected_expression_error(void)
2944 {
2945         errorf(HERE, "expected expression, got token '%K'", &token);
2946
2947         next_token();
2948
2949         return create_invalid_expression();
2950 }
2951
2952 /**
2953  * Parse a string constant.
2954  */
2955 static expression_t *parse_string_const(void)
2956 {
2957         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2958         cnst->base.datatype = type_string;
2959         cnst->string.value  = parse_string_literals();
2960
2961         return cnst;
2962 }
2963
2964 /**
2965  * Parse a wide string constant.
2966  */
2967 static expression_t *parse_wide_string_const(void)
2968 {
2969         expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
2970         cnst->base.datatype      = type_wchar_t_ptr;
2971         cnst->wide_string.value  = token.v.wide_string; /* TODO concatenate */
2972         next_token();
2973         return cnst;
2974 }
2975
2976 /**
2977  * Parse an integer constant.
2978  */
2979 static expression_t *parse_int_const(void)
2980 {
2981         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2982         cnst->base.datatype      = token.datatype;
2983         cnst->conste.v.int_value = token.v.intvalue;
2984
2985         next_token();
2986
2987         return cnst;
2988 }
2989
2990 /**
2991  * Parse a float constant.
2992  */
2993 static expression_t *parse_float_const(void)
2994 {
2995         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2996         cnst->base.datatype        = token.datatype;
2997         cnst->conste.v.float_value = token.v.floatvalue;
2998
2999         next_token();
3000
3001         return cnst;
3002 }
3003
3004 static declaration_t *create_implicit_function(symbol_t *symbol,
3005                 const source_position_t source_position)
3006 {
3007         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
3008         ntype->function.return_type            = type_int;
3009         ntype->function.unspecified_parameters = true;
3010
3011         type_t *type = typehash_insert(ntype);
3012         if(type != ntype) {
3013                 free_type(ntype);
3014         }
3015
3016         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
3017
3018         declaration->storage_class   = STORAGE_CLASS_EXTERN;
3019         declaration->type            = type;
3020         declaration->symbol          = symbol;
3021         declaration->source_position = source_position;
3022         declaration->parent_context  = global_context;
3023
3024         context_t *old_context = context;
3025         set_context(global_context);
3026
3027         environment_push(declaration);
3028         /* prepend the declaration to the global declarations list */
3029         declaration->next     = context->declarations;
3030         context->declarations = declaration;
3031
3032         assert(context == global_context);
3033         set_context(old_context);
3034
3035         return declaration;
3036 }
3037
3038 /**
3039  * Creates a return_type (func)(argument_type) function type if not
3040  * already exists.
3041  *
3042  * @param return_type    the return type
3043  * @param argument_type  the argument type
3044  */
3045 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3046 {
3047         function_parameter_t *parameter
3048                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3049         memset(parameter, 0, sizeof(parameter[0]));
3050         parameter->type = argument_type;
3051
3052         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
3053         type->function.return_type = return_type;
3054         type->function.parameters  = parameter;
3055
3056         type_t *result = typehash_insert(type);
3057         if(result != type) {
3058                 free_type(type);
3059         }
3060
3061         return result;
3062 }
3063
3064 /**
3065  * Creates a function type for some function like builtins.
3066  *
3067  * @param symbol   the symbol describing the builtin
3068  */
3069 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3070 {
3071         switch(symbol->ID) {
3072         case T___builtin_alloca:
3073                 return make_function_1_type(type_void_ptr, type_size_t);
3074         case T___builtin_nan:
3075                 return make_function_1_type(type_double, type_string);
3076         case T___builtin_nanf:
3077                 return make_function_1_type(type_float, type_string);
3078         case T___builtin_nand:
3079                 return make_function_1_type(type_long_double, type_string);
3080         case T___builtin_va_end:
3081                 return make_function_1_type(type_void, type_valist);
3082         default:
3083                 panic("not implemented builtin symbol found");
3084         }
3085 }
3086
3087 /**
3088  * Performs automatic type cast as described in Â§ 6.3.2.1.
3089  *
3090  * @param orig_type  the original type
3091  */
3092 static type_t *automatic_type_conversion(type_t *orig_type)
3093 {
3094         if(orig_type == NULL)
3095                 return NULL;
3096
3097         type_t *type = skip_typeref(orig_type);
3098         if(is_type_array(type)) {
3099                 array_type_t *array_type   = &type->array;
3100                 type_t       *element_type = array_type->element_type;
3101                 unsigned      qualifiers   = array_type->type.qualifiers;
3102
3103                 return make_pointer_type(element_type, qualifiers);
3104         }
3105
3106         if(is_type_function(type)) {
3107                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3108         }
3109
3110         return orig_type;
3111 }
3112
3113 /**
3114  * reverts the automatic casts of array to pointer types and function
3115  * to function-pointer types as defined Â§ 6.3.2.1
3116  */
3117 type_t *revert_automatic_type_conversion(const expression_t *expression)
3118 {
3119         if(expression->base.datatype == NULL)
3120                 return NULL;
3121
3122         switch(expression->kind) {
3123         case EXPR_REFERENCE: {
3124                 const reference_expression_t *ref = &expression->reference;
3125                 return ref->declaration->type;
3126         }
3127         case EXPR_SELECT: {
3128                 const select_expression_t *select = &expression->select;
3129                 return select->compound_entry->type;
3130         }
3131         case EXPR_UNARY_DEREFERENCE: {
3132                 expression_t   *value        = expression->unary.value;
3133                 type_t         *type         = skip_typeref(value->base.datatype);
3134                 pointer_type_t *pointer_type = &type->pointer;
3135
3136                 return pointer_type->points_to;
3137         }
3138         case EXPR_BUILTIN_SYMBOL: {
3139                 const builtin_symbol_expression_t *builtin
3140                         = &expression->builtin_symbol;
3141                 return get_builtin_symbol_type(builtin->symbol);
3142         }
3143         case EXPR_ARRAY_ACCESS: {
3144                 const array_access_expression_t *array_access
3145                         = &expression->array_access;
3146                 const expression_t *array_ref = array_access->array_ref;
3147                 type_t *type_left  = skip_typeref(array_ref->base.datatype);
3148                 assert(is_type_pointer(type_left));
3149                 pointer_type_t *pointer_type = &type_left->pointer;
3150                 return pointer_type->points_to;
3151         }
3152
3153         default:
3154                 break;
3155         }
3156
3157         return expression->base.datatype;
3158 }
3159
3160 static expression_t *parse_reference(void)
3161 {
3162         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3163
3164         reference_expression_t *ref = &expression->reference;
3165         ref->symbol = token.v.symbol;
3166
3167         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3168
3169         source_position_t source_position = token.source_position;
3170         next_token();
3171
3172         if(declaration == NULL) {
3173                 if (! strict_mode && token.type == '(') {
3174                         /* an implicitly defined function */
3175                         warningf(HERE, "implicit declaration of function '%Y'",
3176                                  ref->symbol);
3177
3178                         declaration = create_implicit_function(ref->symbol,
3179                                                                source_position);
3180                 } else {
3181                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3182                         return expression;
3183                 }
3184         }
3185
3186         type_t *type         = declaration->type;
3187
3188         /* we always do the auto-type conversions; the & and sizeof parser contains
3189          * code to revert this! */
3190         type = automatic_type_conversion(type);
3191
3192         ref->declaration         = declaration;
3193         ref->expression.datatype = type;
3194
3195         return expression;
3196 }
3197
3198 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3199 {
3200         (void) expression;
3201         (void) dest_type;
3202         /* TODO check if explicit cast is allowed and issue warnings/errors */
3203 }
3204
3205 static expression_t *parse_cast(void)
3206 {
3207         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3208
3209         cast->base.source_position = token.source_position;
3210
3211         type_t *type  = parse_typename();
3212
3213         expect(')');
3214         expression_t *value = parse_sub_expression(20);
3215
3216         check_cast_allowed(value, type);
3217
3218         cast->base.datatype = type;
3219         cast->unary.value   = value;
3220
3221         return cast;
3222 }
3223
3224 static expression_t *parse_statement_expression(void)
3225 {
3226         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3227
3228         statement_t *statement          = parse_compound_statement();
3229         expression->statement.statement = statement;
3230         if(statement == NULL) {
3231                 expect(')');
3232                 return NULL;
3233         }
3234
3235         assert(statement->kind == STATEMENT_COMPOUND);
3236         compound_statement_t *compound_statement = &statement->compound;
3237
3238         /* find last statement and use it's type */
3239         const statement_t *last_statement = NULL;
3240         const statement_t *iter           = compound_statement->statements;
3241         for( ; iter != NULL; iter = iter->base.next) {
3242                 last_statement = iter;
3243         }
3244
3245         if(last_statement->kind == STATEMENT_EXPRESSION) {
3246                 const expression_statement_t *expression_statement
3247                         = &last_statement->expression;
3248                 expression->base.datatype
3249                         = expression_statement->expression->base.datatype;
3250         } else {
3251                 expression->base.datatype = type_void;
3252         }
3253
3254         expect(')');
3255
3256         return expression;
3257 }
3258
3259 static expression_t *parse_brace_expression(void)
3260 {
3261         eat('(');
3262
3263         switch(token.type) {
3264         case '{':
3265                 /* gcc extension: a statement expression */
3266                 return parse_statement_expression();
3267
3268         TYPE_QUALIFIERS
3269         TYPE_SPECIFIERS
3270                 return parse_cast();
3271         case T_IDENTIFIER:
3272                 if(is_typedef_symbol(token.v.symbol)) {
3273                         return parse_cast();
3274                 }
3275         }
3276
3277         expression_t *result = parse_expression();
3278         expect(')');
3279
3280         return result;
3281 }
3282
3283 static expression_t *parse_function_keyword(void)
3284 {
3285         next_token();
3286         /* TODO */
3287
3288         if (current_function == NULL) {
3289                 errorf(HERE, "'__func__' used outside of a function");
3290         }
3291
3292         string_literal_expression_t *expression
3293                 = allocate_ast_zero(sizeof(expression[0]));
3294
3295         expression->expression.kind     = EXPR_FUNCTION;
3296         expression->expression.datatype = type_string;
3297         expression->value               = current_function->symbol->string;
3298
3299         return (expression_t*) expression;
3300 }
3301
3302 static expression_t *parse_pretty_function_keyword(void)
3303 {
3304         eat(T___PRETTY_FUNCTION__);
3305         /* TODO */
3306
3307         if (current_function == NULL) {
3308                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3309         }
3310
3311         string_literal_expression_t *expression
3312                 = allocate_ast_zero(sizeof(expression[0]));
3313
3314         expression->expression.kind     = EXPR_PRETTY_FUNCTION;
3315         expression->expression.datatype = type_string;
3316         expression->value               = current_function->symbol->string;
3317
3318         return (expression_t*) expression;
3319 }
3320
3321 static designator_t *parse_designator(void)
3322 {
3323         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3324
3325         if(token.type != T_IDENTIFIER) {
3326                 parse_error_expected("while parsing member designator",
3327                                      T_IDENTIFIER, 0);
3328                 eat_paren();
3329                 return NULL;
3330         }
3331         result->symbol = token.v.symbol;
3332         next_token();
3333
3334         designator_t *last_designator = result;
3335         while(true) {
3336                 if(token.type == '.') {
3337                         next_token();
3338                         if(token.type != T_IDENTIFIER) {
3339                                 parse_error_expected("while parsing member designator",
3340                                                      T_IDENTIFIER, 0);
3341                                 eat_paren();
3342                                 return NULL;
3343                         }
3344                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3345                         designator->symbol       = token.v.symbol;
3346                         next_token();
3347
3348                         last_designator->next = designator;
3349                         last_designator       = designator;
3350                         continue;
3351                 }
3352                 if(token.type == '[') {
3353                         next_token();
3354                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3355                         designator->array_access = parse_expression();
3356                         if(designator->array_access == NULL) {
3357                                 eat_paren();
3358                                 return NULL;
3359                         }
3360                         expect(']');
3361
3362                         last_designator->next = designator;
3363                         last_designator       = designator;
3364                         continue;
3365                 }
3366                 break;
3367         }
3368
3369         return result;
3370 }
3371
3372 static expression_t *parse_offsetof(void)
3373 {
3374         eat(T___builtin_offsetof);
3375
3376         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3377         expression->base.datatype = type_size_t;
3378
3379         expect('(');
3380         expression->offsetofe.type = parse_typename();
3381         expect(',');
3382         expression->offsetofe.designator = parse_designator();
3383         expect(')');
3384
3385         return expression;
3386 }
3387
3388 static expression_t *parse_va_start(void)
3389 {
3390         eat(T___builtin_va_start);
3391
3392         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3393
3394         expect('(');
3395         expression->va_starte.ap = parse_assignment_expression();
3396         expect(',');
3397         expression_t *const expr = parse_assignment_expression();
3398         if (expr->kind == EXPR_REFERENCE) {
3399                 declaration_t *const decl = expr->reference.declaration;
3400                 if (decl->parent_context == &current_function->context &&
3401                     decl->next == NULL) {
3402                         expression->va_starte.parameter = decl;
3403                         expect(')');
3404                         return expression;
3405                 }
3406         }
3407         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3408
3409         return create_invalid_expression();
3410 }
3411
3412 static expression_t *parse_va_arg(void)
3413 {
3414         eat(T___builtin_va_arg);
3415
3416         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3417
3418         expect('(');
3419         expression->va_arge.ap = parse_assignment_expression();
3420         expect(',');
3421         expression->base.datatype = parse_typename();
3422         expect(')');
3423
3424         return expression;
3425 }
3426
3427 static expression_t *parse_builtin_symbol(void)
3428 {
3429         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3430
3431         symbol_t *symbol = token.v.symbol;
3432
3433         expression->builtin_symbol.symbol = symbol;
3434         next_token();
3435
3436         type_t *type = get_builtin_symbol_type(symbol);
3437         type = automatic_type_conversion(type);
3438
3439         expression->base.datatype = type;
3440         return expression;
3441 }
3442
3443 static expression_t *parse_builtin_constant(void)
3444 {
3445         eat(T___builtin_constant_p);
3446
3447         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3448
3449         expect('(');
3450         expression->builtin_constant.value = parse_assignment_expression();
3451         expect(')');
3452         expression->base.datatype = type_int;
3453
3454         return expression;
3455 }
3456
3457 static expression_t *parse_builtin_prefetch(void)
3458 {
3459         eat(T___builtin_prefetch);
3460
3461         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3462
3463         expect('(');
3464         expression->builtin_prefetch.adr = parse_assignment_expression();
3465         if (token.type == ',') {
3466                 next_token();
3467                 expression->builtin_prefetch.rw = parse_assignment_expression();
3468         }
3469         if (token.type == ',') {
3470                 next_token();
3471                 expression->builtin_prefetch.locality = parse_assignment_expression();
3472         }
3473         expect(')');
3474         expression->base.datatype = type_void;
3475
3476         return expression;
3477 }
3478
3479 static expression_t *parse_compare_builtin(void)
3480 {
3481         expression_t *expression;
3482
3483         switch(token.type) {
3484         case T___builtin_isgreater:
3485                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3486                 break;
3487         case T___builtin_isgreaterequal:
3488                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3489                 break;
3490         case T___builtin_isless:
3491                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
3492                 break;
3493         case T___builtin_islessequal:
3494                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
3495                 break;
3496         case T___builtin_islessgreater:
3497                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
3498                 break;
3499         case T___builtin_isunordered:
3500                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
3501                 break;
3502         default:
3503                 panic("invalid compare builtin found");
3504                 break;
3505         }
3506         next_token();
3507
3508         expect('(');
3509         expression->binary.left = parse_assignment_expression();
3510         expect(',');
3511         expression->binary.right = parse_assignment_expression();
3512         expect(')');
3513
3514         type_t *orig_type_left  = expression->binary.left->base.datatype;
3515         type_t *orig_type_right = expression->binary.right->base.datatype;
3516         if(orig_type_left == NULL || orig_type_right == NULL)
3517                 return expression;
3518
3519         type_t *type_left  = skip_typeref(orig_type_left);
3520         type_t *type_right = skip_typeref(orig_type_right);
3521         if(!is_type_floating(type_left) && !is_type_floating(type_right)) {
3522                 type_error_incompatible("invalid operands in comparison",
3523                                         token.source_position, type_left, type_right);
3524         } else {
3525                 semantic_comparison(&expression->binary);
3526         }
3527
3528         return expression;
3529 }
3530
3531 static expression_t *parse_builtin_expect(void)
3532 {
3533         eat(T___builtin_expect);
3534
3535         expression_t *expression
3536                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
3537
3538         expect('(');
3539         expression->binary.left = parse_assignment_expression();
3540         expect(',');
3541         expression->binary.right = parse_constant_expression();
3542         expect(')');
3543
3544         expression->base.datatype = expression->binary.left->base.datatype;
3545
3546         return expression;
3547 }
3548
3549 static expression_t *parse_assume(void) {
3550         eat(T_assume);
3551
3552         expression_t *expression
3553                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
3554
3555         expect('(');
3556         expression->unary.value = parse_assignment_expression();
3557         expect(')');
3558
3559         expression->base.datatype = type_void;
3560         return expression;
3561 }
3562
3563 static expression_t *parse_alignof(void) {
3564         eat(T___alignof__);
3565
3566         expression_t *expression
3567                 = allocate_expression_zero(EXPR_ALIGNOF);
3568
3569         expect('(');
3570         expression->alignofe.type = parse_typename();
3571         expect(')');
3572
3573         expression->base.datatype = type_size_t;
3574         return expression;
3575 }
3576
3577 static expression_t *parse_primary_expression(void)
3578 {
3579         switch(token.type) {
3580         case T_INTEGER:
3581                 return parse_int_const();
3582         case T_FLOATINGPOINT:
3583                 return parse_float_const();
3584         case T_STRING_LITERAL:
3585                 return parse_string_const();
3586         case T_WIDE_STRING_LITERAL:
3587                 return parse_wide_string_const();
3588         case T_IDENTIFIER:
3589                 return parse_reference();
3590         case T___FUNCTION__:
3591         case T___func__:
3592                 return parse_function_keyword();
3593         case T___PRETTY_FUNCTION__:
3594                 return parse_pretty_function_keyword();
3595         case T___builtin_offsetof:
3596                 return parse_offsetof();
3597         case T___builtin_va_start:
3598                 return parse_va_start();
3599         case T___builtin_va_arg:
3600                 return parse_va_arg();
3601         case T___builtin_expect:
3602                 return parse_builtin_expect();
3603         case T___builtin_nanf:
3604         case T___builtin_alloca:
3605         case T___builtin_va_end:
3606                 return parse_builtin_symbol();
3607         case T___builtin_isgreater:
3608         case T___builtin_isgreaterequal:
3609         case T___builtin_isless:
3610         case T___builtin_islessequal:
3611         case T___builtin_islessgreater:
3612         case T___builtin_isunordered:
3613                 return parse_compare_builtin();
3614         case T___builtin_constant_p:
3615                 return parse_builtin_constant();
3616         case T___builtin_prefetch:
3617                 return parse_builtin_prefetch();
3618         case T___alignof__:
3619                 return parse_alignof();
3620         case T_assume:
3621                 return parse_assume();
3622
3623         case '(':
3624                 return parse_brace_expression();
3625         }
3626
3627         errorf(HERE, "unexpected token '%K'", &token);
3628         eat_statement();
3629
3630         return create_invalid_expression();
3631 }
3632
3633 /**
3634  * Check if the expression has the character type and issue a warning then.
3635  */
3636 static void check_for_char_index_type(const expression_t *expression) {
3637         type_t *type      = expression->base.datatype;
3638         type_t *base_type = skip_typeref(type);
3639
3640         if (base_type->base.kind == TYPE_ATOMIC) {
3641                 if (base_type->atomic.akind == ATOMIC_TYPE_CHAR) {
3642                         warningf(expression->base.source_position,
3643                                 "array subscript has type '%T'", type);
3644                 }
3645         }
3646 }
3647
3648 static expression_t *parse_array_expression(unsigned precedence,
3649                                             expression_t *left)
3650 {
3651         (void) precedence;
3652
3653         eat('[');
3654
3655         expression_t *inside = parse_expression();
3656
3657         array_access_expression_t *array_access
3658                 = allocate_ast_zero(sizeof(array_access[0]));
3659
3660         array_access->expression.kind = EXPR_ARRAY_ACCESS;
3661
3662         type_t *type_left   = left->base.datatype;
3663         type_t *type_inside = inside->base.datatype;
3664         type_t *return_type = NULL;
3665
3666         if(type_left != NULL && type_inside != NULL) {
3667                 type_left   = skip_typeref(type_left);
3668                 type_inside = skip_typeref(type_inside);
3669
3670                 if(is_type_pointer(type_left)) {
3671                         pointer_type_t *pointer = &type_left->pointer;
3672                         return_type             = pointer->points_to;
3673                         array_access->array_ref = left;
3674                         array_access->index     = inside;
3675                         check_for_char_index_type(inside);
3676                 } else if(is_type_pointer(type_inside)) {
3677                         pointer_type_t *pointer = &type_inside->pointer;
3678                         return_type             = pointer->points_to;
3679                         array_access->array_ref = inside;
3680                         array_access->index     = left;
3681                         array_access->flipped   = true;
3682                         check_for_char_index_type(left);
3683                 } else {
3684                         errorf(HERE, "array access on object with non-pointer types '%T', '%T'", type_left, type_inside);
3685                 }
3686         } else {
3687                 array_access->array_ref = left;
3688                 array_access->index     = inside;
3689         }
3690
3691         if(token.type != ']') {
3692                 parse_error_expected("Problem while parsing array access", ']', 0);
3693                 return (expression_t*) array_access;
3694         }
3695         next_token();
3696
3697         return_type = automatic_type_conversion(return_type);
3698         array_access->expression.datatype = return_type;
3699
3700         return (expression_t*) array_access;
3701 }
3702
3703 static expression_t *parse_sizeof(unsigned precedence)
3704 {
3705         eat(T_sizeof);
3706
3707         sizeof_expression_t *sizeof_expression
3708                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3709         sizeof_expression->expression.kind     = EXPR_SIZEOF;
3710         sizeof_expression->expression.datatype = type_size_t;
3711
3712         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3713                 next_token();
3714                 sizeof_expression->type = parse_typename();
3715                 expect(')');
3716         } else {
3717                 expression_t *expression  = parse_sub_expression(precedence);
3718                 expression->base.datatype = revert_automatic_type_conversion(expression);
3719
3720                 sizeof_expression->type            = expression->base.datatype;
3721                 sizeof_expression->size_expression = expression;
3722         }
3723
3724         return (expression_t*) sizeof_expression;
3725 }
3726
3727 static expression_t *parse_select_expression(unsigned precedence,
3728                                              expression_t *compound)
3729 {
3730         (void) precedence;
3731         assert(token.type == '.' || token.type == T_MINUSGREATER);
3732
3733         bool is_pointer = (token.type == T_MINUSGREATER);
3734         next_token();
3735
3736         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3737         select->select.compound = compound;
3738
3739         if(token.type != T_IDENTIFIER) {
3740                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3741                 return select;
3742         }
3743         symbol_t *symbol      = token.v.symbol;
3744         select->select.symbol = symbol;
3745         next_token();
3746
3747         type_t *orig_type = compound->base.datatype;
3748         if(orig_type == NULL)
3749                 return create_invalid_expression();
3750
3751         type_t *type = skip_typeref(orig_type);
3752
3753         type_t *type_left = type;
3754         if(is_pointer) {
3755                 if(type->kind != TYPE_POINTER) {
3756                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
3757                         return create_invalid_expression();
3758                 }
3759                 pointer_type_t *pointer_type = &type->pointer;
3760                 type_left                    = pointer_type->points_to;
3761         }
3762         type_left = skip_typeref(type_left);
3763
3764         if(type_left->kind != TYPE_COMPOUND_STRUCT
3765                         && type_left->kind != TYPE_COMPOUND_UNION) {
3766                 errorf(HERE, "request for member '%Y' in something not a struct or "
3767                        "union, but '%T'", symbol, type_left);
3768                 return create_invalid_expression();
3769         }
3770
3771         compound_type_t *compound_type = &type_left->compound;
3772         declaration_t   *declaration   = compound_type->declaration;
3773
3774         if(!declaration->init.is_defined) {
3775                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
3776                        symbol, type_left);
3777                 return create_invalid_expression();
3778         }
3779
3780         declaration_t *iter = declaration->context.declarations;
3781         for( ; iter != NULL; iter = iter->next) {
3782                 if(iter->symbol == symbol) {
3783                         break;
3784                 }
3785         }
3786         if(iter == NULL) {
3787                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
3788                 return create_invalid_expression();
3789         }
3790
3791         /* we always do the auto-type conversions; the & and sizeof parser contains
3792          * code to revert this! */
3793         type_t *expression_type = automatic_type_conversion(iter->type);
3794
3795         select->select.compound_entry = iter;
3796         select->base.datatype         = expression_type;
3797
3798         if(expression_type->kind == TYPE_BITFIELD) {
3799                 expression_t *extract
3800                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
3801                 extract->unary.value   = select;
3802                 extract->base.datatype = expression_type->bitfield.base;
3803
3804                 return extract;
3805         }
3806
3807         return select;
3808 }
3809
3810 /**
3811  * Parse a call expression, ie. expression '( ... )'.
3812  *
3813  * @param expression  the function address
3814  */
3815 static expression_t *parse_call_expression(unsigned precedence,
3816                                            expression_t *expression)
3817 {
3818         (void) precedence;
3819         expression_t *result = allocate_expression_zero(EXPR_CALL);
3820
3821         call_expression_t *call = &result->call;
3822         call->function          = expression;
3823
3824         function_type_t *function_type = NULL;
3825         type_t          *orig_type     = expression->base.datatype;
3826         if(orig_type != NULL) {
3827                 type_t *type  = skip_typeref(orig_type);
3828
3829                 if(is_type_pointer(type)) {
3830                         pointer_type_t *pointer_type = &type->pointer;
3831
3832                         type = skip_typeref(pointer_type->points_to);
3833
3834                         if (is_type_function(type)) {
3835                                 function_type             = &type->function;
3836                                 call->expression.datatype = function_type->return_type;
3837                         }
3838                 }
3839                 if(function_type == NULL) {
3840                         errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
3841
3842                         function_type             = NULL;
3843                         call->expression.datatype = NULL;
3844                 }
3845         }
3846
3847         /* parse arguments */
3848         eat('(');
3849
3850         if(token.type != ')') {
3851                 call_argument_t *last_argument = NULL;
3852
3853                 while(true) {
3854                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3855
3856                         argument->expression = parse_assignment_expression();
3857                         if(last_argument == NULL) {
3858                                 call->arguments = argument;
3859                         } else {
3860                                 last_argument->next = argument;
3861                         }
3862                         last_argument = argument;
3863
3864                         if(token.type != ',')
3865                                 break;
3866                         next_token();
3867                 }
3868         }
3869         expect(')');
3870
3871         if(function_type != NULL) {
3872                 function_parameter_t *parameter = function_type->parameters;
3873                 call_argument_t      *argument  = call->arguments;
3874                 for( ; parameter != NULL && argument != NULL;
3875                                 parameter = parameter->next, argument = argument->next) {
3876                         type_t *expected_type = parameter->type;
3877                         /* TODO report context in error messages */
3878                         argument->expression = create_implicit_cast(argument->expression,
3879                                                                     expected_type);
3880                 }
3881                 /* too few parameters */
3882                 if(parameter != NULL) {
3883                         errorf(HERE, "too few arguments to function '%E'", expression);
3884                 } else if(argument != NULL) {
3885                         /* too many parameters */
3886                         if(!function_type->variadic
3887                                         && !function_type->unspecified_parameters) {
3888                                 errorf(HERE, "too many arguments to function '%E'", expression);
3889                         } else {
3890                                 /* do default promotion */
3891                                 for( ; argument != NULL; argument = argument->next) {
3892                                         type_t *type = argument->expression->base.datatype;
3893
3894                                         if(type == NULL)
3895                                                 continue;
3896
3897                                         type = skip_typeref(type);
3898                                         if(is_type_integer(type)) {
3899                                                 type = promote_integer(type);
3900                                         } else if(type == type_float) {
3901                                                 type = type_double;
3902                                         }
3903
3904                                         argument->expression
3905                                                 = create_implicit_cast(argument->expression, type);
3906                                 }
3907
3908                                 check_format(&result->call);
3909                         }
3910                 } else {
3911                         check_format(&result->call);
3912                 }
3913         }
3914
3915         return result;
3916 }
3917
3918 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3919
3920 static bool same_compound_type(const type_t *type1, const type_t *type2)
3921 {
3922         if(!is_type_compound(type1))
3923                 return false;
3924         if(type1->kind != type2->kind)
3925                 return false;
3926
3927         const compound_type_t *compound1 = &type1->compound;
3928         const compound_type_t *compound2 = &type2->compound;
3929
3930         return compound1->declaration == compound2->declaration;
3931 }
3932
3933 /**
3934  * Parse a conditional expression, ie. 'expression ? ... : ...'.
3935  *
3936  * @param expression  the conditional expression
3937  */
3938 static expression_t *parse_conditional_expression(unsigned precedence,
3939                                                   expression_t *expression)
3940 {
3941         eat('?');
3942
3943         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3944
3945         conditional_expression_t *conditional = &result->conditional;
3946         conditional->condition = expression;
3947
3948         /* 6.5.15.2 */
3949         type_t *condition_type_orig = expression->base.datatype;
3950         if(condition_type_orig != NULL) {
3951                 type_t *condition_type = skip_typeref(condition_type_orig);
3952                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3953                         type_error("expected a scalar type in conditional condition",
3954                                    expression->base.source_position, condition_type_orig);
3955                 }
3956         }
3957
3958         expression_t *true_expression = parse_expression();
3959         expect(':');
3960         expression_t *false_expression = parse_sub_expression(precedence);
3961
3962         conditional->true_expression  = true_expression;
3963         conditional->false_expression = false_expression;
3964
3965         type_t *orig_true_type  = true_expression->base.datatype;
3966         type_t *orig_false_type = false_expression->base.datatype;
3967         if(orig_true_type == NULL || orig_false_type == NULL)
3968                 return result;
3969
3970         type_t *true_type  = skip_typeref(orig_true_type);
3971         type_t *false_type = skip_typeref(orig_false_type);
3972
3973         /* 6.5.15.3 */
3974         type_t *result_type = NULL;
3975         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3976                 result_type = semantic_arithmetic(true_type, false_type);
3977
3978                 true_expression  = create_implicit_cast(true_expression, result_type);
3979                 false_expression = create_implicit_cast(false_expression, result_type);
3980
3981                 conditional->true_expression     = true_expression;
3982                 conditional->false_expression    = false_expression;
3983                 conditional->expression.datatype = result_type;
3984         } else if (same_compound_type(true_type, false_type)
3985                         || (is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3986                                 is_type_atomic(false_type, ATOMIC_TYPE_VOID))) {
3987                 /* just take 1 of the 2 types */
3988                 result_type = true_type;
3989         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3990                         && pointers_compatible(true_type, false_type)) {
3991                 /* ok */
3992                 result_type = true_type;
3993         } else {
3994                 /* TODO */
3995                 type_error_incompatible("while parsing conditional",
3996                                         expression->base.source_position, true_type,
3997                                         false_type);
3998         }
3999
4000         conditional->expression.datatype = result_type;
4001         return result;
4002 }
4003
4004 /**
4005  * Parse an extension expression.
4006  */
4007 static expression_t *parse_extension(unsigned precedence)
4008 {
4009         eat(T___extension__);
4010
4011         /* TODO enable extensions */
4012         expression_t *expression = parse_sub_expression(precedence);
4013         /* TODO disable extensions */
4014         return expression;
4015 }
4016
4017 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4018 {
4019         eat(T___builtin_classify_type);
4020
4021         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4022         result->base.datatype = type_int;
4023
4024         expect('(');
4025         expression_t *expression = parse_sub_expression(precedence);
4026         expect(')');
4027         result->classify_type.type_expression = expression;
4028
4029         return result;
4030 }
4031
4032 static void semantic_incdec(unary_expression_t *expression)
4033 {
4034         type_t *orig_type = expression->value->base.datatype;
4035         if(orig_type == NULL)
4036                 return;
4037
4038         type_t *type = skip_typeref(orig_type);
4039         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4040                 /* TODO: improve error message */
4041                 errorf(HERE, "operation needs an arithmetic or pointer type");
4042                 return;
4043         }
4044
4045         expression->expression.datatype = orig_type;
4046 }
4047
4048 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4049 {
4050         type_t *orig_type = expression->value->base.datatype;
4051         if(orig_type == NULL)
4052                 return;
4053
4054         type_t *type = skip_typeref(orig_type);
4055         if(!is_type_arithmetic(type)) {
4056                 /* TODO: improve error message */
4057                 errorf(HERE, "operation needs an arithmetic type");
4058                 return;
4059         }
4060
4061         expression->expression.datatype = orig_type;
4062 }
4063
4064 static void semantic_unexpr_scalar(unary_expression_t *expression)
4065 {
4066         type_t *orig_type = expression->value->base.datatype;
4067         if(orig_type == NULL)
4068                 return;
4069
4070         type_t *type = skip_typeref(orig_type);
4071         if (!is_type_scalar(type)) {
4072                 errorf(HERE, "operand of ! must be of scalar type");
4073                 return;
4074         }
4075
4076         expression->expression.datatype = orig_type;
4077 }
4078
4079 static void semantic_unexpr_integer(unary_expression_t *expression)
4080 {
4081         type_t *orig_type = expression->value->base.datatype;
4082         if(orig_type == NULL)
4083                 return;
4084
4085         type_t *type = skip_typeref(orig_type);
4086         if (!is_type_integer(type)) {
4087                 errorf(HERE, "operand of ~ must be of integer type");
4088                 return;
4089         }
4090
4091         expression->expression.datatype = orig_type;
4092 }
4093
4094 static void semantic_dereference(unary_expression_t *expression)
4095 {
4096         type_t *orig_type = expression->value->base.datatype;
4097         if(orig_type == NULL)
4098                 return;
4099
4100         type_t *type = skip_typeref(orig_type);
4101         if(!is_type_pointer(type)) {
4102                 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4103                 return;
4104         }
4105
4106         pointer_type_t *pointer_type = &type->pointer;
4107         type_t         *result_type  = pointer_type->points_to;
4108
4109         result_type = automatic_type_conversion(result_type);
4110         expression->expression.datatype = result_type;
4111 }
4112
4113 /**
4114  * Check the semantic of the address taken expression.
4115  */
4116 static void semantic_take_addr(unary_expression_t *expression)
4117 {
4118         expression_t *value  = expression->value;
4119         value->base.datatype = revert_automatic_type_conversion(value);
4120
4121         type_t *orig_type = value->base.datatype;
4122         if(orig_type == NULL)
4123                 return;
4124
4125         if(value->kind == EXPR_REFERENCE) {
4126                 reference_expression_t *reference   = (reference_expression_t*) value;
4127                 declaration_t          *declaration = reference->declaration;
4128                 if(declaration != NULL) {
4129                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4130                                 errorf(expression->expression.source_position,
4131                                         "address of register variable '%Y' requested",
4132                                         declaration->symbol);
4133                         }
4134                         declaration->address_taken = 1;
4135                 }
4136         }
4137
4138         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4139 }
4140
4141 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4142 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4143 {                                                                              \
4144         eat(token_type);                                                           \
4145                                                                                    \
4146         expression_t *unary_expression                                             \
4147                 = allocate_expression_zero(unexpression_type);                         \
4148         unary_expression->base.source_position = HERE;                             \
4149         unary_expression->unary.value = parse_sub_expression(precedence);          \
4150                                                                                    \
4151         sfunc(&unary_expression->unary);                                           \
4152                                                                                    \
4153         return unary_expression;                                                   \
4154 }
4155
4156 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4157                                semantic_unexpr_arithmetic)
4158 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4159                                semantic_unexpr_arithmetic)
4160 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4161                                semantic_unexpr_scalar)
4162 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4163                                semantic_dereference)
4164 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4165                                semantic_take_addr)
4166 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4167                                semantic_unexpr_integer)
4168 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4169                                semantic_incdec)
4170 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4171                                semantic_incdec)
4172
4173 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4174                                                sfunc)                         \
4175 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4176                                                expression_t *left)            \
4177 {                                                                             \
4178         (void) precedence;                                                        \
4179         eat(token_type);                                                          \
4180                                                                               \
4181         expression_t *unary_expression                                            \
4182                 = allocate_expression_zero(unexpression_type);                        \
4183         unary_expression->unary.value = left;                                     \
4184                                                                                   \
4185         sfunc(&unary_expression->unary);                                          \
4186                                                                               \
4187         return unary_expression;                                                  \
4188 }
4189
4190 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4191                                        EXPR_UNARY_POSTFIX_INCREMENT,
4192                                        semantic_incdec)
4193 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4194                                        EXPR_UNARY_POSTFIX_DECREMENT,
4195                                        semantic_incdec)
4196
4197 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4198 {
4199         /* TODO: handle complex + imaginary types */
4200
4201         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4202         if(type_left == type_long_double || type_right == type_long_double) {
4203                 return type_long_double;
4204         } else if(type_left == type_double || type_right == type_double) {
4205                 return type_double;
4206         } else if(type_left == type_float || type_right == type_float) {
4207                 return type_float;
4208         }
4209
4210         type_right = promote_integer(type_right);
4211         type_left  = promote_integer(type_left);
4212
4213         if(type_left == type_right)
4214                 return type_left;
4215
4216         bool signed_left  = is_type_signed(type_left);
4217         bool signed_right = is_type_signed(type_right);
4218         int  rank_left    = get_rank(type_left);
4219         int  rank_right   = get_rank(type_right);
4220         if(rank_left < rank_right) {
4221                 if(signed_left == signed_right || !signed_right) {
4222                         return type_right;
4223                 } else {
4224                         return type_left;
4225                 }
4226         } else {
4227                 if(signed_left == signed_right || !signed_left) {
4228                         return type_left;
4229                 } else {
4230                         return type_right;
4231                 }
4232         }
4233 }
4234
4235 /**
4236  * Check the semantic restrictions for a binary expression.
4237  */
4238 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4239 {
4240         expression_t *left       = expression->left;
4241         expression_t *right      = expression->right;
4242         type_t       *orig_type_left  = left->base.datatype;
4243         type_t       *orig_type_right = right->base.datatype;
4244
4245         if(orig_type_left == NULL || orig_type_right == NULL)
4246                 return;
4247
4248         type_t *type_left  = skip_typeref(orig_type_left);
4249         type_t *type_right = skip_typeref(orig_type_right);
4250
4251         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4252                 /* TODO: improve error message */
4253                 errorf(HERE, "operation needs arithmetic types");
4254                 return;
4255         }
4256
4257         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4258         expression->left  = create_implicit_cast(left, arithmetic_type);
4259         expression->right = create_implicit_cast(right, arithmetic_type);
4260         expression->expression.datatype = arithmetic_type;
4261 }
4262
4263 static void semantic_shift_op(binary_expression_t *expression)
4264 {
4265         expression_t *left       = expression->left;
4266         expression_t *right      = expression->right;
4267         type_t       *orig_type_left  = left->base.datatype;
4268         type_t       *orig_type_right = right->base.datatype;
4269
4270         if(orig_type_left == NULL || orig_type_right == NULL)
4271                 return;
4272
4273         type_t *type_left  = skip_typeref(orig_type_left);
4274         type_t *type_right = skip_typeref(orig_type_right);
4275
4276         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4277                 /* TODO: improve error message */
4278                 errorf(HERE, "operation needs integer types");
4279                 return;
4280         }
4281
4282         type_left  = promote_integer(type_left);
4283         type_right = promote_integer(type_right);
4284
4285         expression->left  = create_implicit_cast(left, type_left);
4286         expression->right = create_implicit_cast(right, type_right);
4287         expression->expression.datatype = type_left;
4288 }
4289
4290 static void semantic_add(binary_expression_t *expression)
4291 {
4292         expression_t *left            = expression->left;
4293         expression_t *right           = expression->right;
4294         type_t       *orig_type_left  = left->base.datatype;
4295         type_t       *orig_type_right = right->base.datatype;
4296
4297         if(orig_type_left == NULL || orig_type_right == NULL)
4298                 return;
4299
4300         type_t *type_left  = skip_typeref(orig_type_left);
4301         type_t *type_right = skip_typeref(orig_type_right);
4302
4303         /* Â§ 5.6.5 */
4304         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4305                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4306                 expression->left  = create_implicit_cast(left, arithmetic_type);
4307                 expression->right = create_implicit_cast(right, arithmetic_type);
4308                 expression->expression.datatype = arithmetic_type;
4309                 return;
4310         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4311                 expression->expression.datatype = type_left;
4312         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4313                 expression->expression.datatype = type_right;
4314         } else {
4315                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4316         }
4317 }
4318
4319 static void semantic_sub(binary_expression_t *expression)
4320 {
4321         expression_t *left            = expression->left;
4322         expression_t *right           = expression->right;
4323         type_t       *orig_type_left  = left->base.datatype;
4324         type_t       *orig_type_right = right->base.datatype;
4325
4326         if(orig_type_left == NULL || orig_type_right == NULL)
4327                 return;
4328
4329         type_t       *type_left       = skip_typeref(orig_type_left);
4330         type_t       *type_right      = skip_typeref(orig_type_right);
4331
4332         /* Â§ 5.6.5 */
4333         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4334                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4335                 expression->left  = create_implicit_cast(left, arithmetic_type);
4336                 expression->right = create_implicit_cast(right, arithmetic_type);
4337                 expression->expression.datatype = arithmetic_type;
4338                 return;
4339         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4340                 expression->expression.datatype = type_left;
4341         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4342                 if(!pointers_compatible(type_left, type_right)) {
4343                         errorf(HERE, "pointers to incompatible objects to binary - ('%T', '%T')", orig_type_left, orig_type_right);
4344                 } else {
4345                         expression->expression.datatype = type_ptrdiff_t;
4346                 }
4347         } else {
4348                 errorf(HERE, "invalid operands to binary - ('%T', '%T')", orig_type_left, orig_type_right);
4349         }
4350 }
4351
4352 static void semantic_comparison(binary_expression_t *expression)
4353 {
4354         expression_t *left            = expression->left;
4355         expression_t *right           = expression->right;
4356         type_t       *orig_type_left  = left->base.datatype;
4357         type_t       *orig_type_right = right->base.datatype;
4358
4359         if(orig_type_left == NULL || orig_type_right == NULL)
4360                 return;
4361
4362         type_t *type_left  = skip_typeref(orig_type_left);
4363         type_t *type_right = skip_typeref(orig_type_right);
4364
4365         /* TODO non-arithmetic types */
4366         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4367                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4368                 expression->left  = create_implicit_cast(left, arithmetic_type);
4369                 expression->right = create_implicit_cast(right, arithmetic_type);
4370                 expression->expression.datatype = arithmetic_type;
4371         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4372                 /* TODO check compatibility */
4373         } else if (is_type_pointer(type_left)) {
4374                 expression->right = create_implicit_cast(right, type_left);
4375         } else if (is_type_pointer(type_right)) {
4376                 expression->left = create_implicit_cast(left, type_right);
4377         } else {
4378                 type_error_incompatible("invalid operands in comparison",
4379                                         token.source_position, type_left, type_right);
4380         }
4381         expression->expression.datatype = type_int;
4382 }
4383
4384 static void semantic_arithmetic_assign(binary_expression_t *expression)
4385 {
4386         expression_t *left            = expression->left;
4387         expression_t *right           = expression->right;
4388         type_t       *orig_type_left  = left->base.datatype;
4389         type_t       *orig_type_right = right->base.datatype;
4390
4391         if(orig_type_left == NULL || orig_type_right == NULL)
4392                 return;
4393
4394         type_t *type_left  = skip_typeref(orig_type_left);
4395         type_t *type_right = skip_typeref(orig_type_right);
4396
4397         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4398                 /* TODO: improve error message */
4399                 errorf(HERE, "operation needs arithmetic types");
4400                 return;
4401         }
4402
4403         /* combined instructions are tricky. We can't create an implicit cast on
4404          * the left side, because we need the uncasted form for the store.
4405          * The ast2firm pass has to know that left_type must be right_type
4406          * for the arithmetic operation and create a cast by itself */
4407         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4408         expression->right       = create_implicit_cast(right, arithmetic_type);
4409         expression->expression.datatype = type_left;
4410 }
4411
4412 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4413 {
4414         expression_t *left            = expression->left;
4415         expression_t *right           = expression->right;
4416         type_t       *orig_type_left  = left->base.datatype;
4417         type_t       *orig_type_right = right->base.datatype;
4418
4419         if(orig_type_left == NULL || orig_type_right == NULL)
4420                 return;
4421
4422         type_t *type_left  = skip_typeref(orig_type_left);
4423         type_t *type_right = skip_typeref(orig_type_right);
4424
4425         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4426                 /* combined instructions are tricky. We can't create an implicit cast on
4427                  * the left side, because we need the uncasted form for the store.
4428                  * The ast2firm pass has to know that left_type must be right_type
4429                  * for the arithmetic operation and create a cast by itself */
4430                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4431                 expression->right = create_implicit_cast(right, arithmetic_type);
4432                 expression->expression.datatype = type_left;
4433         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4434                 expression->expression.datatype = type_left;
4435         } else {
4436                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4437                 return;
4438         }
4439 }
4440
4441 /**
4442  * Check the semantic restrictions of a logical expression.
4443  */
4444 static void semantic_logical_op(binary_expression_t *expression)
4445 {
4446         expression_t *left            = expression->left;
4447         expression_t *right           = expression->right;
4448         type_t       *orig_type_left  = left->base.datatype;
4449         type_t       *orig_type_right = right->base.datatype;
4450
4451         if(orig_type_left == NULL || orig_type_right == NULL)
4452                 return;
4453
4454         type_t *type_left  = skip_typeref(orig_type_left);
4455         type_t *type_right = skip_typeref(orig_type_right);
4456
4457         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4458                 /* TODO: improve error message */
4459                 errorf(HERE, "operation needs scalar types");
4460                 return;
4461         }
4462
4463         expression->expression.datatype = type_int;
4464 }
4465
4466 /**
4467  * Checks if a compound type has constant fields.
4468  */
4469 static bool has_const_fields(const compound_type_t *type)
4470 {
4471         const context_t     *context = &type->declaration->context;
4472         const declaration_t *declaration = context->declarations;
4473
4474         for (; declaration != NULL; declaration = declaration->next) {
4475                 if (declaration->namespc != NAMESPACE_NORMAL)
4476                         continue;
4477
4478                 const type_t *decl_type = skip_typeref(declaration->type);
4479                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4480                         return true;
4481         }
4482         /* TODO */
4483         return false;
4484 }
4485
4486 /**
4487  * Check the semantic restrictions of a binary assign expression.
4488  */
4489 static void semantic_binexpr_assign(binary_expression_t *expression)
4490 {
4491         expression_t *left           = expression->left;
4492         type_t       *orig_type_left = left->base.datatype;
4493
4494         if(orig_type_left == NULL)
4495                 return;
4496
4497         type_t *type_left = revert_automatic_type_conversion(left);
4498         type_left         = skip_typeref(orig_type_left);
4499
4500         /* must be a modifiable lvalue */
4501         if (is_type_array(type_left)) {
4502                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4503                 return;
4504         }
4505         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4506                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
4507                        orig_type_left);
4508                 return;
4509         }
4510         if(is_type_incomplete(type_left)) {
4511                 errorf(HERE,
4512                        "left-hand side of assignment '%E' has incomplete type '%T'",
4513                        left, orig_type_left);
4514                 return;
4515         }
4516         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4517                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
4518                        left, orig_type_left);
4519                 return;
4520         }
4521
4522         semantic_assign(orig_type_left, &expression->right, "assignment");
4523
4524         expression->expression.datatype = orig_type_left;
4525 }
4526
4527 static void semantic_comma(binary_expression_t *expression)
4528 {
4529         expression->expression.datatype = expression->right->base.datatype;
4530 }
4531
4532 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
4533 static expression_t *parse_##binexpression_type(unsigned precedence,      \
4534                                                 expression_t *left)       \
4535 {                                                                         \
4536         eat(token_type);                                                      \
4537                                                                           \
4538         expression_t *right = parse_sub_expression(precedence + lr);          \
4539                                                                           \
4540         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
4541         binexpr->binary.left  = left;                                         \
4542         binexpr->binary.right = right;                                        \
4543         sfunc(&binexpr->binary);                                              \
4544                                                                           \
4545         return binexpr;                                                       \
4546 }
4547
4548 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
4549 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
4550 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
4551 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
4552 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
4553 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
4554 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
4555 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
4556 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
4557
4558 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
4559                       semantic_comparison, 1)
4560 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
4561                       semantic_comparison, 1)
4562 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
4563                       semantic_comparison, 1)
4564 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
4565                       semantic_comparison, 1)
4566
4567 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
4568                       semantic_binexpr_arithmetic, 1)
4569 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
4570                       semantic_binexpr_arithmetic, 1)
4571 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
4572                       semantic_binexpr_arithmetic, 1)
4573 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
4574                       semantic_logical_op, 1)
4575 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
4576                       semantic_logical_op, 1)
4577 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
4578                       semantic_shift_op, 1)
4579 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
4580                       semantic_shift_op, 1)
4581 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
4582                       semantic_arithmetic_addsubb_assign, 0)
4583 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
4584                       semantic_arithmetic_addsubb_assign, 0)
4585 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
4586                       semantic_arithmetic_assign, 0)
4587 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
4588                       semantic_arithmetic_assign, 0)
4589 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
4590                       semantic_arithmetic_assign, 0)
4591 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
4592                       semantic_arithmetic_assign, 0)
4593 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4594                       semantic_arithmetic_assign, 0)
4595 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
4596                       semantic_arithmetic_assign, 0)
4597 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
4598                       semantic_arithmetic_assign, 0)
4599 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
4600                       semantic_arithmetic_assign, 0)
4601
4602 static expression_t *parse_sub_expression(unsigned precedence)
4603 {
4604         if(token.type < 0) {
4605                 return expected_expression_error();
4606         }
4607
4608         expression_parser_function_t *parser
4609                 = &expression_parsers[token.type];
4610         source_position_t             source_position = token.source_position;
4611         expression_t                 *left;
4612
4613         if(parser->parser != NULL) {
4614                 left = parser->parser(parser->precedence);
4615         } else {
4616                 left = parse_primary_expression();
4617         }
4618         assert(left != NULL);
4619         left->base.source_position = source_position;
4620
4621         while(true) {
4622                 if(token.type < 0) {
4623                         return expected_expression_error();
4624                 }
4625
4626                 parser = &expression_parsers[token.type];
4627                 if(parser->infix_parser == NULL)
4628                         break;
4629                 if(parser->infix_precedence < precedence)
4630                         break;
4631
4632                 left = parser->infix_parser(parser->infix_precedence, left);
4633
4634                 assert(left != NULL);
4635                 assert(left->kind != EXPR_UNKNOWN);
4636                 left->base.source_position = source_position;
4637         }
4638
4639         return left;
4640 }
4641
4642 /**
4643  * Parse an expression.
4644  */
4645 static expression_t *parse_expression(void)
4646 {
4647         return parse_sub_expression(1);
4648 }
4649
4650 /**
4651  * Register a parser for a prefix-like operator with given precedence.
4652  *
4653  * @param parser      the parser function
4654  * @param token_type  the token type of the prefix token
4655  * @param precedence  the precedence of the operator
4656  */
4657 static void register_expression_parser(parse_expression_function parser,
4658                                        int token_type, unsigned precedence)
4659 {
4660         expression_parser_function_t *entry = &expression_parsers[token_type];
4661
4662         if(entry->parser != NULL) {
4663                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4664                 panic("trying to register multiple expression parsers for a token");
4665         }
4666         entry->parser     = parser;
4667         entry->precedence = precedence;
4668 }
4669
4670 /**
4671  * Register a parser for an infix operator with given precedence.
4672  *
4673  * @param parser      the parser function
4674  * @param token_type  the token type of the infix operator
4675  * @param precedence  the precedence of the operator
4676  */
4677 static void register_infix_parser(parse_expression_infix_function parser,
4678                 int token_type, unsigned precedence)
4679 {
4680         expression_parser_function_t *entry = &expression_parsers[token_type];
4681
4682         if(entry->infix_parser != NULL) {
4683                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4684                 panic("trying to register multiple infix expression parsers for a "
4685                       "token");
4686         }
4687         entry->infix_parser     = parser;
4688         entry->infix_precedence = precedence;
4689 }
4690
4691 /**
4692  * Initialize the expression parsers.
4693  */
4694 static void init_expression_parsers(void)
4695 {
4696         memset(&expression_parsers, 0, sizeof(expression_parsers));
4697
4698         register_infix_parser(parse_array_expression,         '[',              30);
4699         register_infix_parser(parse_call_expression,          '(',              30);
4700         register_infix_parser(parse_select_expression,        '.',              30);
4701         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
4702         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
4703                                                               T_PLUSPLUS,       30);
4704         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
4705                                                               T_MINUSMINUS,     30);
4706
4707         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
4708         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
4709         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
4710         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
4711         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
4712         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
4713         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
4714         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
4715         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
4716         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
4717         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
4718         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
4719         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
4720                                                     T_EXCLAMATIONMARKEQUAL, 13);
4721         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
4722         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
4723         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
4724         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
4725         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
4726         register_infix_parser(parse_conditional_expression,   '?',               7);
4727         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
4728         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
4729         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
4730         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
4731         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
4732         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
4733         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
4734                                                                 T_LESSLESSEQUAL, 2);
4735         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4736                                                           T_GREATERGREATEREQUAL, 2);
4737         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
4738                                                                      T_ANDEQUAL, 2);
4739         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
4740                                                                     T_PIPEEQUAL, 2);
4741         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
4742                                                                    T_CARETEQUAL, 2);
4743
4744         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
4745
4746         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
4747         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
4748         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
4749         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
4750         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
4751         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
4752         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
4753                                                                   T_PLUSPLUS,   25);
4754         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
4755                                                                   T_MINUSMINUS, 25);
4756         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4757         register_expression_parser(parse_extension,            T___extension__, 25);
4758         register_expression_parser(parse_builtin_classify_type,
4759                                                      T___builtin_classify_type, 25);
4760 }
4761
4762 /**
4763  * Parse a asm statement constraints specification.
4764  */
4765 static asm_constraint_t *parse_asm_constraints(void)
4766 {
4767         asm_constraint_t *result = NULL;
4768         asm_constraint_t *last   = NULL;
4769
4770         while(token.type == T_STRING_LITERAL || token.type == '[') {
4771                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4772                 memset(constraint, 0, sizeof(constraint[0]));
4773
4774                 if(token.type == '[') {
4775                         eat('[');
4776                         if(token.type != T_IDENTIFIER) {
4777                                 parse_error_expected("while parsing asm constraint",
4778                                                      T_IDENTIFIER, 0);
4779                                 return NULL;
4780                         }
4781                         constraint->symbol = token.v.symbol;
4782
4783                         expect(']');
4784                 }
4785
4786                 constraint->constraints = parse_string_literals();
4787                 expect('(');
4788                 constraint->expression = parse_expression();
4789                 expect(')');
4790
4791                 if(last != NULL) {
4792                         last->next = constraint;
4793                 } else {
4794                         result = constraint;
4795                 }
4796                 last = constraint;
4797
4798                 if(token.type != ',')
4799                         break;
4800                 eat(',');
4801         }
4802
4803         return result;
4804 }
4805
4806 /**
4807  * Parse a asm statement clobber specification.
4808  */
4809 static asm_clobber_t *parse_asm_clobbers(void)
4810 {
4811         asm_clobber_t *result = NULL;
4812         asm_clobber_t *last   = NULL;
4813
4814         while(token.type == T_STRING_LITERAL) {
4815                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4816                 clobber->clobber       = parse_string_literals();
4817
4818                 if(last != NULL) {
4819                         last->next = clobber;
4820                 } else {
4821                         result = clobber;
4822                 }
4823                 last = clobber;
4824
4825                 if(token.type != ',')
4826                         break;
4827                 eat(',');
4828         }
4829
4830         return result;
4831 }
4832
4833 /**
4834  * Parse an asm statement.
4835  */
4836 static statement_t *parse_asm_statement(void)
4837 {
4838         eat(T_asm);
4839
4840         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4841         statement->base.source_position = token.source_position;
4842
4843         asm_statement_t *asm_statement = &statement->asms;
4844
4845         if(token.type == T_volatile) {
4846                 next_token();
4847                 asm_statement->is_volatile = true;
4848         }
4849
4850         expect('(');
4851         asm_statement->asm_text = parse_string_literals();
4852
4853         if(token.type != ':')
4854                 goto end_of_asm;
4855         eat(':');
4856
4857         asm_statement->inputs = parse_asm_constraints();
4858         if(token.type != ':')
4859                 goto end_of_asm;
4860         eat(':');
4861
4862         asm_statement->outputs = parse_asm_constraints();
4863         if(token.type != ':')
4864                 goto end_of_asm;
4865         eat(':');
4866
4867         asm_statement->clobbers = parse_asm_clobbers();
4868
4869 end_of_asm:
4870         expect(')');
4871         expect(';');
4872         return statement;
4873 }
4874
4875 /**
4876  * Parse a case statement.
4877  */
4878 static statement_t *parse_case_statement(void)
4879 {
4880         eat(T_case);
4881
4882         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4883
4884         statement->base.source_position  = token.source_position;
4885         statement->case_label.expression = parse_expression();
4886
4887         expect(':');
4888
4889         if (! is_constant_expression(statement->case_label.expression)) {
4890                 errorf(statement->base.source_position,
4891                         "case label does not reduce to an integer constant");
4892         } else {
4893                 /* TODO: check if the case label is already known */
4894                 if (current_switch != NULL) {
4895                         /* link all cases into the switch statement */
4896                         if (current_switch->last_case == NULL) {
4897                                 current_switch->first_case =
4898                                 current_switch->last_case  = &statement->case_label;
4899                         } else {
4900                                 current_switch->last_case->next = &statement->case_label;
4901                         }
4902                 } else {
4903                         errorf(statement->base.source_position,
4904                                 "case label not within a switch statement");
4905                 }
4906         }
4907         statement->case_label.label_statement = parse_statement();
4908
4909         return statement;
4910 }
4911
4912 /**
4913  * Finds an existing default label of a switch statement.
4914  */
4915 static case_label_statement_t *
4916 find_default_label(const switch_statement_t *statement)
4917 {
4918         for (case_label_statement_t *label = statement->first_case;
4919              label != NULL;
4920                  label = label->next) {
4921                 if (label->expression == NULL)
4922                         return label;
4923         }
4924         return NULL;
4925 }
4926
4927 /**
4928  * Parse a default statement.
4929  */
4930 static statement_t *parse_default_statement(void)
4931 {
4932         eat(T_default);
4933
4934         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4935
4936         statement->base.source_position = token.source_position;
4937
4938         expect(':');
4939         if (current_switch != NULL) {
4940                 const case_label_statement_t *def_label = find_default_label(current_switch);
4941                 if (def_label != NULL) {
4942                         errorf(HERE, "multiple default labels in one switch");
4943                         errorf(def_label->statement.source_position,
4944                                 "this is the first default label");
4945                 } else {
4946                         /* link all cases into the switch statement */
4947                         if (current_switch->last_case == NULL) {
4948                                 current_switch->first_case =
4949                                         current_switch->last_case  = &statement->case_label;
4950                         } else {
4951                                 current_switch->last_case->next = &statement->case_label;
4952                         }
4953                 }
4954         } else {
4955                 errorf(statement->base.source_position,
4956                         "'default' label not within a switch statement");
4957         }
4958         statement->label.label_statement = parse_statement();
4959
4960         return statement;
4961 }
4962
4963 /**
4964  * Return the declaration for a given label symbol or create a new one.
4965  */
4966 static declaration_t *get_label(symbol_t *symbol)
4967 {
4968         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4969         assert(current_function != NULL);
4970         /* if we found a label in the same function, then we already created the
4971          * declaration */
4972         if(candidate != NULL
4973                         && candidate->parent_context == &current_function->context) {
4974                 return candidate;
4975         }
4976
4977         /* otherwise we need to create a new one */
4978         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4979         declaration->namespc       = NAMESPACE_LABEL;
4980         declaration->symbol        = symbol;
4981
4982         label_push(declaration);
4983
4984         return declaration;
4985 }
4986
4987 /**
4988  * Parse a label statement.
4989  */
4990 static statement_t *parse_label_statement(void)
4991 {
4992         assert(token.type == T_IDENTIFIER);
4993         symbol_t *symbol = token.v.symbol;
4994         next_token();
4995
4996         declaration_t *label = get_label(symbol);
4997
4998         /* if source position is already set then the label is defined twice,
4999          * otherwise it was just mentioned in a goto so far */
5000         if(label->source_position.input_name != NULL) {
5001                 errorf(HERE, "duplicate label '%Y'", symbol);
5002                 errorf(label->source_position, "previous definition of '%Y' was here",
5003                        symbol);
5004         } else {
5005                 label->source_position = token.source_position;
5006         }
5007
5008         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
5009
5010         label_statement->statement.kind            = STATEMENT_LABEL;
5011         label_statement->statement.source_position = token.source_position;
5012         label_statement->label                     = label;
5013
5014         eat(':');
5015
5016         if(token.type == '}') {
5017                 /* TODO only warn? */
5018                 errorf(HERE, "label at end of compound statement");
5019                 return (statement_t*) label_statement;
5020         } else {
5021                 label_statement->label_statement = parse_statement();
5022         }
5023
5024         return (statement_t*) label_statement;
5025 }
5026
5027 /**
5028  * Parse an if statement.
5029  */
5030 static statement_t *parse_if(void)
5031 {
5032         eat(T_if);
5033
5034         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5035         statement->statement.kind            = STATEMENT_IF;
5036         statement->statement.source_position = token.source_position;
5037
5038         expect('(');
5039         statement->condition = parse_expression();
5040         expect(')');
5041
5042         statement->true_statement = parse_statement();
5043         if(token.type == T_else) {
5044                 next_token();
5045                 statement->false_statement = parse_statement();
5046         }
5047
5048         return (statement_t*) statement;
5049 }
5050
5051 /**
5052  * Parse a switch statement.
5053  */
5054 static statement_t *parse_switch(void)
5055 {
5056         eat(T_switch);
5057
5058         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5059         statement->statement.kind            = STATEMENT_SWITCH;
5060         statement->statement.source_position = token.source_position;
5061
5062         expect('(');
5063         expression_t *const expr = parse_expression();
5064         type_t       *const type = promote_integer(skip_typeref(expr->base.datatype));
5065         statement->expression = create_implicit_cast(expr, type);
5066         expect(')');
5067
5068         switch_statement_t *rem = current_switch;
5069         current_switch  = statement;
5070         statement->body = parse_statement();
5071         current_switch  = rem;
5072
5073         return (statement_t*) statement;
5074 }
5075
5076 /**
5077  * Parse a while statement.
5078  */
5079 static statement_t *parse_while(void)
5080 {
5081         eat(T_while);
5082
5083         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5084         statement->statement.kind            = STATEMENT_WHILE;
5085         statement->statement.source_position = token.source_position;
5086
5087         statement_t *rem = current_loop;
5088         expect_fail('(');
5089         statement->condition = parse_expression();
5090         expect_fail(')');
5091
5092         statement->body = parse_statement();
5093         current_loop = rem;
5094
5095         return (statement_t*) statement;
5096 fail:
5097         current_loop = rem;
5098         return NULL;
5099 }
5100
5101 /**
5102  * Parse a do statement.
5103  */
5104 static statement_t *parse_do(void)
5105 {
5106         eat(T_do);
5107
5108         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5109         statement->statement.kind            = STATEMENT_DO_WHILE;
5110         statement->statement.source_position = token.source_position;
5111
5112         statement_t *rem = current_loop;
5113         statement->body = parse_statement();
5114         expect_fail(T_while);
5115         expect_fail('(');
5116         statement->condition = parse_expression();
5117         expect_fail(')');
5118         current_loop = rem;
5119         expect(';');
5120
5121         return (statement_t*) statement;
5122 fail:
5123         current_loop = rem;
5124         return NULL;
5125 }
5126
5127 /**
5128  * Parse a for statement.
5129  */
5130 static statement_t *parse_for(void)
5131 {
5132         eat(T_for);
5133
5134         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5135         statement->statement.kind            = STATEMENT_FOR;
5136         statement->statement.source_position = token.source_position;
5137
5138         expect('(');
5139
5140         statement_t *rem = current_loop;
5141         int         top          = environment_top();
5142         context_t  *last_context = context;
5143         set_context(&statement->context);
5144
5145         if(token.type != ';') {
5146                 if(is_declaration_specifier(&token, false)) {
5147                         parse_declaration(record_declaration);
5148                 } else {
5149                         statement->initialisation = parse_expression();
5150                         expect_fail(';');
5151                 }
5152         } else {
5153                 expect_fail(';');
5154         }
5155
5156         if(token.type != ';') {
5157                 statement->condition = parse_expression();
5158         }
5159         expect_fail(';');
5160         if(token.type != ')') {
5161                 statement->step = parse_expression();
5162         }
5163         expect_fail(')');
5164         statement->body = parse_statement();
5165
5166         assert(context == &statement->context);
5167         set_context(last_context);
5168         environment_pop_to(top);
5169         current_loop = rem;
5170
5171         return (statement_t*) statement;
5172 fail:
5173         current_loop = rem;
5174         return NULL;
5175 }
5176
5177 /**
5178  * Parse a goto statement.
5179  */
5180 static statement_t *parse_goto(void)
5181 {
5182         eat(T_goto);
5183
5184         if(token.type != T_IDENTIFIER) {
5185                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5186                 eat_statement();
5187                 return NULL;
5188         }
5189         symbol_t *symbol = token.v.symbol;
5190         next_token();
5191
5192         declaration_t *label = get_label(symbol);
5193
5194         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5195
5196         statement->statement.kind            = STATEMENT_GOTO;
5197         statement->statement.source_position = token.source_position;
5198
5199         statement->label = label;
5200
5201         /* remember the goto's in a list for later checking */
5202         if (goto_last == NULL) {
5203                 goto_first = goto_last = statement;
5204         } else {
5205                 goto_last->next = statement;
5206         }
5207
5208         expect(';');
5209
5210         return (statement_t*) statement;
5211 }
5212
5213 /**
5214  * Parse a continue statement.
5215  */
5216 static statement_t *parse_continue(void)
5217 {
5218         eat(T_continue);
5219         expect(';');
5220
5221         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
5222         statement->kind                 = STATEMENT_CONTINUE;
5223         statement->base.source_position = token.source_position;
5224
5225         if (current_loop == NULL) {
5226                 errorf(HERE, "continue statement not within loop");
5227                 return NULL;
5228         }
5229
5230         return statement;
5231 }
5232
5233 /**
5234  * Parse a break statement.
5235  */
5236 static statement_t *parse_break(void)
5237 {
5238         eat(T_break);
5239         expect(';');
5240
5241         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
5242         statement->kind                 = STATEMENT_BREAK;
5243         statement->base.source_position = token.source_position;
5244
5245         if (current_switch == NULL && current_loop == NULL) {
5246                 errorf(HERE, "break statement not within loop or switch");
5247                 return NULL;
5248         }
5249         return statement;
5250 }
5251
5252 /**
5253  * Check if a given declaration represents a local variable.
5254  */
5255 static bool is_local_var_declaration(const declaration_t *declaration) {
5256         switch ((storage_class_tag_t) declaration->storage_class) {
5257         case STORAGE_CLASS_NONE:
5258         case STORAGE_CLASS_AUTO:
5259         case STORAGE_CLASS_REGISTER: {
5260                 const type_t *type = skip_typeref(declaration->type);
5261                 if(is_type_function(type)) {
5262                         return false;
5263                 } else {
5264                         return true;
5265                 }
5266         }
5267         default:
5268                 return false;
5269         }
5270 }
5271
5272 /**
5273  * Check if a given expression represents a local variable.
5274  */
5275 static bool is_local_variable(const expression_t *expression)
5276 {
5277         if (expression->base.kind != EXPR_REFERENCE) {
5278                 return false;
5279         }
5280         const declaration_t *declaration = expression->reference.declaration;
5281         return is_local_var_declaration(declaration);
5282 }
5283
5284 /**
5285  * Parse a return statement.
5286  */
5287 static statement_t *parse_return(void)
5288 {
5289         eat(T_return);
5290
5291         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5292
5293         statement->statement.kind            = STATEMENT_RETURN;
5294         statement->statement.source_position = token.source_position;
5295
5296         assert(is_type_function(current_function->type));
5297         function_type_t *function_type = &current_function->type->function;
5298         type_t          *return_type   = function_type->return_type;
5299
5300         expression_t *return_value = NULL;
5301         if(token.type != ';') {
5302                 return_value = parse_expression();
5303         }
5304         expect(';');
5305
5306         if(return_type == NULL)
5307                 return (statement_t*) statement;
5308         if(return_value != NULL && return_value->base.datatype == NULL)
5309                 return (statement_t*) statement;
5310
5311         return_type = skip_typeref(return_type);
5312
5313         if(return_value != NULL) {
5314                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
5315
5316                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5317                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5318                         warningf(statement->statement.source_position,
5319                                 "'return' with a value, in function returning void");
5320                         return_value = NULL;
5321                 } else {
5322                         if(return_type != NULL) {
5323                                 semantic_assign(return_type, &return_value, "'return'");
5324                         }
5325                 }
5326                 /* check for returning address of a local var */
5327                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
5328                         const expression_t *expression = return_value->unary.value;
5329                         if (is_local_variable(expression)) {
5330                                 warningf(statement->statement.source_position,
5331                                         "function returns address of local variable");
5332                         }
5333                 }
5334         } else {
5335                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5336                         warningf(statement->statement.source_position,
5337                                 "'return' without value, in function returning non-void");
5338                 }
5339         }
5340         statement->return_value = return_value;
5341
5342         return (statement_t*) statement;
5343 }
5344
5345 /**
5346  * Parse a declaration statement.
5347  */
5348 static statement_t *parse_declaration_statement(void)
5349 {
5350         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
5351
5352         statement->base.source_position = token.source_position;
5353
5354         declaration_t *before = last_declaration;
5355         parse_declaration(record_declaration);
5356
5357         if(before == NULL) {
5358                 statement->declaration.declarations_begin = context->declarations;
5359         } else {
5360                 statement->declaration.declarations_begin = before->next;
5361         }
5362         statement->declaration.declarations_end = last_declaration;
5363
5364         return statement;
5365 }
5366
5367 /**
5368  * Parse an expression statement, ie. expr ';'.
5369  */
5370 static statement_t *parse_expression_statement(void)
5371 {
5372         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
5373
5374         statement->base.source_position  = token.source_position;
5375         statement->expression.expression = parse_expression();
5376
5377         expect(';');
5378
5379         return statement;
5380 }
5381
5382 /**
5383  * Parse a statement.
5384  */
5385 static statement_t *parse_statement(void)
5386 {
5387         statement_t   *statement = NULL;
5388
5389         /* declaration or statement */
5390         switch(token.type) {
5391         case T_asm:
5392                 statement = parse_asm_statement();
5393                 break;
5394
5395         case T_case:
5396                 statement = parse_case_statement();
5397                 break;
5398
5399         case T_default:
5400                 statement = parse_default_statement();
5401                 break;
5402
5403         case '{':
5404                 statement = parse_compound_statement();
5405                 break;
5406
5407         case T_if:
5408                 statement = parse_if();
5409                 break;
5410
5411         case T_switch:
5412                 statement = parse_switch();
5413                 break;
5414
5415         case T_while:
5416                 statement = parse_while();
5417                 break;
5418
5419         case T_do:
5420                 statement = parse_do();
5421                 break;
5422
5423         case T_for:
5424                 statement = parse_for();
5425                 break;
5426
5427         case T_goto:
5428                 statement = parse_goto();
5429                 break;
5430
5431         case T_continue:
5432                 statement = parse_continue();
5433                 break;
5434
5435         case T_break:
5436                 statement = parse_break();
5437                 break;
5438
5439         case T_return:
5440                 statement = parse_return();
5441                 break;
5442
5443         case ';':
5444                 next_token();
5445                 statement = NULL;
5446                 break;
5447
5448         case T_IDENTIFIER:
5449                 if(look_ahead(1)->type == ':') {
5450                         statement = parse_label_statement();
5451                         break;
5452                 }
5453
5454                 if(is_typedef_symbol(token.v.symbol)) {
5455                         statement = parse_declaration_statement();
5456                         break;
5457                 }
5458
5459                 statement = parse_expression_statement();
5460                 break;
5461
5462         case T___extension__:
5463                 /* this can be a prefix to a declaration or an expression statement */
5464                 /* we simply eat it now and parse the rest with tail recursion */
5465                 do {
5466                         next_token();
5467                 } while(token.type == T___extension__);
5468                 statement = parse_statement();
5469                 break;
5470
5471         DECLARATION_START
5472                 statement = parse_declaration_statement();
5473                 break;
5474
5475         default:
5476                 statement = parse_expression_statement();
5477                 break;
5478         }
5479
5480         assert(statement == NULL
5481                         || statement->base.source_position.input_name != NULL);
5482
5483         return statement;
5484 }
5485
5486 /**
5487  * Parse a compound statement.
5488  */
5489 static statement_t *parse_compound_statement(void)
5490 {
5491         compound_statement_t *compound_statement
5492                 = allocate_ast_zero(sizeof(compound_statement[0]));
5493         compound_statement->statement.kind            = STATEMENT_COMPOUND;
5494         compound_statement->statement.source_position = token.source_position;
5495
5496         eat('{');
5497
5498         int        top          = environment_top();
5499         context_t *last_context = context;
5500         set_context(&compound_statement->context);
5501
5502         statement_t *last_statement = NULL;
5503
5504         while(token.type != '}' && token.type != T_EOF) {
5505                 statement_t *statement = parse_statement();
5506                 if(statement == NULL)
5507                         continue;
5508
5509                 if(last_statement != NULL) {
5510                         last_statement->base.next = statement;
5511                 } else {
5512                         compound_statement->statements = statement;
5513                 }
5514
5515                 while(statement->base.next != NULL)
5516                         statement = statement->base.next;
5517
5518                 last_statement = statement;
5519         }
5520
5521         if(token.type == '}') {
5522                 next_token();
5523         } else {
5524                 errorf(compound_statement->statement.source_position, "end of file while looking for closing '}'");
5525         }
5526
5527         assert(context == &compound_statement->context);
5528         set_context(last_context);
5529         environment_pop_to(top);
5530
5531         return (statement_t*) compound_statement;
5532 }
5533
5534 /**
5535  * Initialize builtin types.
5536  */
5537 static void initialize_builtin_types(void)
5538 {
5539         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
5540         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
5541         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
5542         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
5543         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
5544         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
5545         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
5546         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
5547
5548         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
5549         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
5550         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
5551         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
5552 }
5553
5554 /**
5555  * Parse a translation unit.
5556  */
5557 static translation_unit_t *parse_translation_unit(void)
5558 {
5559         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
5560
5561         assert(global_context == NULL);
5562         global_context = &unit->context;
5563
5564         assert(context == NULL);
5565         set_context(&unit->context);
5566
5567         initialize_builtin_types();
5568
5569         while(token.type != T_EOF) {
5570                 if (token.type == ';') {
5571                         /* TODO error in strict mode */
5572                         warningf(HERE, "stray ';' outside of function");
5573                         next_token();
5574                 } else {
5575                         parse_external_declaration();
5576                 }
5577         }
5578
5579         assert(context == &unit->context);
5580         context          = NULL;
5581         last_declaration = NULL;
5582
5583         assert(global_context == &unit->context);
5584         global_context = NULL;
5585
5586         return unit;
5587 }
5588
5589 /**
5590  * Parse the input.
5591  *
5592  * @return  the translation unit or NULL if errors occurred.
5593  */
5594 translation_unit_t *parse(void)
5595 {
5596         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5597         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5598         diagnostic_count  = 0;
5599         error_count       = 0;
5600         warning_count     = 0;
5601
5602         type_set_output(stderr);
5603         ast_set_output(stderr);
5604
5605         lookahead_bufpos = 0;
5606         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5607                 next_token();
5608         }
5609         translation_unit_t *unit = parse_translation_unit();
5610
5611         DEL_ARR_F(environment_stack);
5612         DEL_ARR_F(label_stack);
5613
5614         if(error_count > 0)
5615                 return NULL;
5616
5617         return unit;
5618 }
5619
5620 /**
5621  * Initialize the parser.
5622  */
5623 void init_parser(void)
5624 {
5625         init_expression_parsers();
5626         obstack_init(&temp_obst);
5627
5628         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
5629         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
5630 }
5631
5632 /**
5633  * Terminate the parser.
5634  */
5635 void exit_parser(void)
5636 {
5637         obstack_free(&temp_obst, NULL);
5638 }