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