2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
46 declaration_t *old_declaration;
48 unsigned short namespc;
51 typedef struct declaration_specifiers_t declaration_specifiers_t;
52 struct declaration_specifiers_t {
53 source_position_t source_position;
54 unsigned char declared_storage_class;
55 unsigned char alignment; /**< Alignment, 0 if not set. */
57 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
58 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
59 symbol_t *get_property_sym; /**< the name of the get property if set. */
60 symbol_t *put_property_sym; /**< the name of the put property if set. */
65 * An environment for parsing initializers (and compound literals).
67 typedef struct parse_initializer_env_t {
68 type_t *type; /**< the type of the initializer. In case of an
69 array type with unspecified size this gets
70 adjusted to the actual size. */
71 declaration_t *declaration; /**< the declaration that is initialized if any */
72 bool must_be_constant;
73 } parse_initializer_env_t;
75 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
78 static token_t lookahead_buffer[MAX_LOOKAHEAD];
79 static int lookahead_bufpos;
80 static stack_entry_t *environment_stack = NULL;
81 static stack_entry_t *label_stack = NULL;
82 static scope_t *global_scope = NULL;
83 static scope_t *scope = NULL;
84 static declaration_t *last_declaration = NULL;
85 static declaration_t *current_function = NULL;
86 static switch_statement_t *current_switch = NULL;
87 static statement_t *current_loop = NULL;
88 static goto_statement_t *goto_first = NULL;
89 static goto_statement_t *goto_last = NULL;
90 static label_statement_t *label_first = NULL;
91 static label_statement_t *label_last = NULL;
92 static struct obstack temp_obst;
94 /* symbols for Microsoft extended-decl-modifier */
95 static const symbol_t *sym_align = NULL;
96 static const symbol_t *sym_allocate = NULL;
97 static const symbol_t *sym_dllimport = NULL;
98 static const symbol_t *sym_dllexport = NULL;
99 static const symbol_t *sym_naked = NULL;
100 static const symbol_t *sym_noinline = NULL;
101 static const symbol_t *sym_noreturn = NULL;
102 static const symbol_t *sym_nothrow = NULL;
103 static const symbol_t *sym_novtable = NULL;
104 static const symbol_t *sym_property = NULL;
105 static const symbol_t *sym_get = NULL;
106 static const symbol_t *sym_put = NULL;
107 static const symbol_t *sym_selectany = NULL;
108 static const symbol_t *sym_thread = NULL;
109 static const symbol_t *sym_uuid = NULL;
110 static const symbol_t *sym_deprecated = NULL;
112 /** The token anchor set */
113 static unsigned char token_anchor_set[T_LAST_TOKEN];
115 /** The current source position. */
116 #define HERE token.source_position
118 static type_t *type_valist;
120 static statement_t *parse_compound_statement(void);
121 static statement_t *parse_statement(void);
123 static expression_t *parse_sub_expression(unsigned precedence);
124 static expression_t *parse_expression(void);
125 static type_t *parse_typename(void);
127 static void parse_compound_type_entries(declaration_t *compound_declaration);
128 static declaration_t *parse_declarator(
129 const declaration_specifiers_t *specifiers, bool may_be_abstract);
130 static declaration_t *record_declaration(declaration_t *declaration);
132 static void semantic_comparison(binary_expression_t *expression);
134 #define STORAGE_CLASSES \
141 #define TYPE_QUALIFIERS \
148 #ifdef PROVIDE_COMPLEX
149 #define COMPLEX_SPECIFIERS \
151 #define IMAGINARY_SPECIFIERS \
154 #define COMPLEX_SPECIFIERS
155 #define IMAGINARY_SPECIFIERS
158 #define TYPE_SPECIFIERS \
173 case T___builtin_va_list: \
177 #define DECLARATION_START \
182 #define TYPENAME_START \
187 * Allocate an AST node with given size and
188 * initialize all fields with zero.
190 static void *allocate_ast_zero(size_t size)
192 void *res = allocate_ast(size);
193 memset(res, 0, size);
197 static declaration_t *allocate_declaration_zero(void)
199 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
200 declaration->type = type_error_type;
201 declaration->alignment = 0;
206 * Returns the size of a statement node.
208 * @param kind the statement kind
210 static size_t get_statement_struct_size(statement_kind_t kind)
212 static const size_t sizes[] = {
213 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
214 [STATEMENT_RETURN] = sizeof(return_statement_t),
215 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
216 [STATEMENT_IF] = sizeof(if_statement_t),
217 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
218 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
219 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
220 [STATEMENT_BREAK] = sizeof(statement_base_t),
221 [STATEMENT_GOTO] = sizeof(goto_statement_t),
222 [STATEMENT_LABEL] = sizeof(label_statement_t),
223 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
224 [STATEMENT_WHILE] = sizeof(while_statement_t),
225 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
226 [STATEMENT_FOR] = sizeof(for_statement_t),
227 [STATEMENT_ASM] = sizeof(asm_statement_t)
229 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
230 assert(sizes[kind] != 0);
235 * Allocate a statement node of given kind and initialize all
238 static statement_t *allocate_statement_zero(statement_kind_t kind)
240 size_t size = get_statement_struct_size(kind);
241 statement_t *res = allocate_ast_zero(size);
243 res->base.kind = kind;
248 * Returns the size of an expression node.
250 * @param kind the expression kind
252 static size_t get_expression_struct_size(expression_kind_t kind)
254 static const size_t sizes[] = {
255 [EXPR_INVALID] = sizeof(expression_base_t),
256 [EXPR_REFERENCE] = sizeof(reference_expression_t),
257 [EXPR_CONST] = sizeof(const_expression_t),
258 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
259 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
260 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
261 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
262 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
263 [EXPR_CALL] = sizeof(call_expression_t),
264 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
265 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
266 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
267 [EXPR_SELECT] = sizeof(select_expression_t),
268 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
269 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
270 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
271 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
272 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
273 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
274 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
275 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
276 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
277 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
278 [EXPR_VA_START] = sizeof(va_start_expression_t),
279 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
280 [EXPR_STATEMENT] = sizeof(statement_expression_t),
282 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
283 return sizes[EXPR_UNARY_FIRST];
285 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
286 return sizes[EXPR_BINARY_FIRST];
288 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
289 assert(sizes[kind] != 0);
294 * Allocate an expression node of given kind and initialize all
297 static expression_t *allocate_expression_zero(expression_kind_t kind)
299 size_t size = get_expression_struct_size(kind);
300 expression_t *res = allocate_ast_zero(size);
302 res->base.kind = kind;
303 res->base.type = type_error_type;
308 * Returns the size of a type node.
310 * @param kind the type kind
312 static size_t get_type_struct_size(type_kind_t kind)
314 static const size_t sizes[] = {
315 [TYPE_ATOMIC] = sizeof(atomic_type_t),
316 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
317 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
318 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
319 [TYPE_ENUM] = sizeof(enum_type_t),
320 [TYPE_FUNCTION] = sizeof(function_type_t),
321 [TYPE_POINTER] = sizeof(pointer_type_t),
322 [TYPE_ARRAY] = sizeof(array_type_t),
323 [TYPE_BUILTIN] = sizeof(builtin_type_t),
324 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
325 [TYPE_TYPEOF] = sizeof(typeof_type_t),
327 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
328 assert(kind <= TYPE_TYPEOF);
329 assert(sizes[kind] != 0);
334 * Allocate a type node of given kind and initialize all
337 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
339 size_t size = get_type_struct_size(kind);
340 type_t *res = obstack_alloc(type_obst, size);
341 memset(res, 0, size);
343 res->base.kind = kind;
344 res->base.source_position = source_position;
349 * Returns the size of an initializer node.
351 * @param kind the initializer kind
353 static size_t get_initializer_size(initializer_kind_t kind)
355 static const size_t sizes[] = {
356 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
357 [INITIALIZER_STRING] = sizeof(initializer_string_t),
358 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
359 [INITIALIZER_LIST] = sizeof(initializer_list_t),
360 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
362 assert(kind < sizeof(sizes) / sizeof(*sizes));
363 assert(sizes[kind] != 0);
368 * Allocate an initializer node of given kind and initialize all
371 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
373 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
380 * Free a type from the type obstack.
382 static void free_type(void *type)
384 obstack_free(type_obst, type);
388 * Returns the index of the top element of the environment stack.
390 static size_t environment_top(void)
392 return ARR_LEN(environment_stack);
396 * Returns the index of the top element of the label stack.
398 static size_t label_top(void)
400 return ARR_LEN(label_stack);
404 * Return the next token.
406 static inline void next_token(void)
408 token = lookahead_buffer[lookahead_bufpos];
409 lookahead_buffer[lookahead_bufpos] = lexer_token;
412 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
415 print_token(stderr, &token);
416 fprintf(stderr, "\n");
421 * Return the next token with a given lookahead.
423 static inline const token_t *look_ahead(int num)
425 assert(num > 0 && num <= MAX_LOOKAHEAD);
426 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
427 return &lookahead_buffer[pos];
431 * Adds a token to the token anchor set (a multi-set).
433 static void add_anchor_token(int token_type) {
434 assert(0 <= token_type && token_type < T_LAST_TOKEN);
435 ++token_anchor_set[token_type];
439 * Remove a token from the token anchor set (a multi-set).
441 static void rem_anchor_token(int token_type) {
442 assert(0 <= token_type && token_type < T_LAST_TOKEN);
443 --token_anchor_set[token_type];
446 static bool at_anchor(void) {
449 return token_anchor_set[token.type];
453 * Eat tokens until a matching token is found.
455 static void eat_until_matching_token(int type) {
456 unsigned parenthesis_count = 0;
457 unsigned brace_count = 0;
458 unsigned bracket_count = 0;
459 int end_token = type;
468 while(token.type != end_token ||
469 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
473 case '(': ++parenthesis_count; break;
474 case '{': ++brace_count; break;
475 case '[': ++bracket_count; break;
477 if(parenthesis_count > 0)
485 if(bracket_count > 0)
496 * Eat input tokens until an anchor is found.
498 static void eat_until_anchor(void) {
499 if(token.type == T_EOF)
501 while(token_anchor_set[token.type] == 0) {
502 if(token.type == '(' || token.type == '{' || token.type == '[')
503 eat_until_matching_token(token.type);
504 if(token.type == T_EOF)
510 static void eat_block(void) {
511 eat_until_matching_token('{');
512 if(token.type == '}')
516 static void eat_statement(void) {
517 eat_until_matching_token(';');
518 if(token.type == ';')
522 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
525 * Report a parse error because an expected token was not found.
527 static void parse_error_expected(const char *message, ...)
529 if(message != NULL) {
530 errorf(HERE, "%s", message);
533 va_start(ap, message);
534 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
539 * Report a type error.
541 static void type_error(const char *msg, const source_position_t source_position,
544 errorf(source_position, "%s, but found type '%T'", msg, type);
548 * Report an incompatible type.
550 static void type_error_incompatible(const char *msg,
551 const source_position_t source_position, type_t *type1, type_t *type2)
553 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
557 * Expect the the current token is the expected token.
558 * If not, generate an error, eat the current statement,
559 * and goto the end_error label.
561 #define expect(expected) \
563 if(UNLIKELY(token.type != (expected))) { \
564 parse_error_expected(NULL, (expected), 0); \
565 add_anchor_token(expected); \
566 eat_until_anchor(); \
567 rem_anchor_token(expected); \
573 static void set_scope(scope_t *new_scope)
576 scope->last_declaration = last_declaration;
580 last_declaration = new_scope->last_declaration;
584 * Search a symbol in a given namespace and returns its declaration or
585 * NULL if this symbol was not found.
587 static declaration_t *get_declaration(const symbol_t *const symbol,
588 const namespace_t namespc)
590 declaration_t *declaration = symbol->declaration;
591 for( ; declaration != NULL; declaration = declaration->symbol_next) {
592 if(declaration->namespc == namespc)
600 * pushs an environment_entry on the environment stack and links the
601 * corresponding symbol to the new entry
603 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
605 symbol_t *symbol = declaration->symbol;
606 namespace_t namespc = (namespace_t) declaration->namespc;
608 /* replace/add declaration into declaration list of the symbol */
609 declaration_t *iter = symbol->declaration;
611 symbol->declaration = declaration;
613 declaration_t *iter_last = NULL;
614 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
615 /* replace an entry? */
616 if(iter->namespc == namespc) {
617 if(iter_last == NULL) {
618 symbol->declaration = declaration;
620 iter_last->symbol_next = declaration;
622 declaration->symbol_next = iter->symbol_next;
627 assert(iter_last->symbol_next == NULL);
628 iter_last->symbol_next = declaration;
632 /* remember old declaration */
634 entry.symbol = symbol;
635 entry.old_declaration = iter;
636 entry.namespc = (unsigned short) namespc;
637 ARR_APP1(stack_entry_t, *stack_ptr, entry);
640 static void environment_push(declaration_t *declaration)
642 assert(declaration->source_position.input_name != NULL);
643 assert(declaration->parent_scope != NULL);
644 stack_push(&environment_stack, declaration);
647 static void label_push(declaration_t *declaration)
649 declaration->parent_scope = ¤t_function->scope;
650 stack_push(&label_stack, declaration);
654 * pops symbols from the environment stack until @p new_top is the top element
656 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
658 stack_entry_t *stack = *stack_ptr;
659 size_t top = ARR_LEN(stack);
662 assert(new_top <= top);
666 for(i = top; i > new_top; --i) {
667 stack_entry_t *entry = &stack[i - 1];
669 declaration_t *old_declaration = entry->old_declaration;
670 symbol_t *symbol = entry->symbol;
671 namespace_t namespc = (namespace_t)entry->namespc;
673 /* replace/remove declaration */
674 declaration_t *declaration = symbol->declaration;
675 assert(declaration != NULL);
676 if(declaration->namespc == namespc) {
677 if(old_declaration == NULL) {
678 symbol->declaration = declaration->symbol_next;
680 symbol->declaration = old_declaration;
683 declaration_t *iter_last = declaration;
684 declaration_t *iter = declaration->symbol_next;
685 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
686 /* replace an entry? */
687 if(iter->namespc == namespc) {
688 assert(iter_last != NULL);
689 iter_last->symbol_next = old_declaration;
690 if(old_declaration != NULL) {
691 old_declaration->symbol_next = iter->symbol_next;
696 assert(iter != NULL);
700 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
703 static void environment_pop_to(size_t new_top)
705 stack_pop_to(&environment_stack, new_top);
708 static void label_pop_to(size_t new_top)
710 stack_pop_to(&label_stack, new_top);
714 static int get_rank(const type_t *type)
716 assert(!is_typeref(type));
717 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
718 * and esp. footnote 108). However we can't fold constants (yet), so we
719 * can't decide whether unsigned int is possible, while int always works.
720 * (unsigned int would be preferable when possible... for stuff like
721 * struct { enum { ... } bla : 4; } ) */
722 if(type->kind == TYPE_ENUM)
723 return ATOMIC_TYPE_INT;
725 assert(type->kind == TYPE_ATOMIC);
726 return type->atomic.akind;
729 static type_t *promote_integer(type_t *type)
731 if(type->kind == TYPE_BITFIELD)
732 type = type->bitfield.base;
734 if(get_rank(type) < ATOMIC_TYPE_INT)
741 * Create a cast expression.
743 * @param expression the expression to cast
744 * @param dest_type the destination type
746 static expression_t *create_cast_expression(expression_t *expression,
749 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
751 cast->unary.value = expression;
752 cast->base.type = dest_type;
758 * Check if a given expression represents the 0 pointer constant.
760 static bool is_null_pointer_constant(const expression_t *expression)
762 /* skip void* cast */
763 if(expression->kind == EXPR_UNARY_CAST
764 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
765 expression = expression->unary.value;
768 /* TODO: not correct yet, should be any constant integer expression
769 * which evaluates to 0 */
770 if (expression->kind != EXPR_CONST)
773 type_t *const type = skip_typeref(expression->base.type);
774 if (!is_type_integer(type))
777 return expression->conste.v.int_value == 0;
781 * Create an implicit cast expression.
783 * @param expression the expression to cast
784 * @param dest_type the destination type
786 static expression_t *create_implicit_cast(expression_t *expression,
789 type_t *const source_type = expression->base.type;
791 if (source_type == dest_type)
794 return create_cast_expression(expression, dest_type);
797 /** Implements the rules from § 6.5.16.1 */
798 static type_t *semantic_assign(type_t *orig_type_left,
799 const expression_t *const right,
802 type_t *const orig_type_right = right->base.type;
803 type_t *const type_left = skip_typeref(orig_type_left);
804 type_t *const type_right = skip_typeref(orig_type_right);
806 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
807 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
808 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
809 && is_type_pointer(type_right))) {
810 return orig_type_left;
813 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
814 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
815 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
817 /* the left type has all qualifiers from the right type */
818 unsigned missing_qualifiers
819 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
820 if(missing_qualifiers != 0) {
821 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
822 return orig_type_left;
825 points_to_left = get_unqualified_type(points_to_left);
826 points_to_right = get_unqualified_type(points_to_right);
828 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
829 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
830 return orig_type_left;
833 if (!types_compatible(points_to_left, points_to_right)) {
834 warningf(right->base.source_position,
835 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
836 orig_type_left, context, right, orig_type_right);
839 return orig_type_left;
842 if ((is_type_compound(type_left) && is_type_compound(type_right))
843 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
844 type_t *const unqual_type_left = get_unqualified_type(type_left);
845 type_t *const unqual_type_right = get_unqualified_type(type_right);
846 if (types_compatible(unqual_type_left, unqual_type_right)) {
847 return orig_type_left;
851 if (!is_type_valid(type_left))
854 if (!is_type_valid(type_right))
855 return orig_type_right;
860 static expression_t *parse_constant_expression(void)
862 /* start parsing at precedence 7 (conditional expression) */
863 expression_t *result = parse_sub_expression(7);
865 if(!is_constant_expression(result)) {
866 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
872 static expression_t *parse_assignment_expression(void)
874 /* start parsing at precedence 2 (assignment expression) */
875 return parse_sub_expression(2);
878 static type_t *make_global_typedef(const char *name, type_t *type)
880 symbol_t *const symbol = symbol_table_insert(name);
882 declaration_t *const declaration = allocate_declaration_zero();
883 declaration->namespc = NAMESPACE_NORMAL;
884 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
885 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
886 declaration->type = type;
887 declaration->symbol = symbol;
888 declaration->source_position = builtin_source_position;
890 record_declaration(declaration);
892 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
893 typedef_type->typedeft.declaration = declaration;
898 static string_t parse_string_literals(void)
900 assert(token.type == T_STRING_LITERAL);
901 string_t result = token.v.string;
905 while (token.type == T_STRING_LITERAL) {
906 result = concat_strings(&result, &token.v.string);
913 static void parse_attributes(void)
917 case T___attribute__: {
925 errorf(HERE, "EOF while parsing attribute");
944 if(token.type != T_STRING_LITERAL) {
945 parse_error_expected("while parsing assembler attribute",
947 eat_until_matching_token('(');
950 parse_string_literals();
955 goto attributes_finished;
964 static designator_t *parse_designation(void)
966 designator_t *result = NULL;
967 designator_t *last = NULL;
970 designator_t *designator;
973 designator = allocate_ast_zero(sizeof(designator[0]));
974 designator->source_position = token.source_position;
976 add_anchor_token(']');
977 designator->array_index = parse_constant_expression();
978 rem_anchor_token(']');
982 designator = allocate_ast_zero(sizeof(designator[0]));
983 designator->source_position = token.source_position;
985 if(token.type != T_IDENTIFIER) {
986 parse_error_expected("while parsing designator",
990 designator->symbol = token.v.symbol;
998 assert(designator != NULL);
1000 last->next = designator;
1002 result = designator;
1010 static initializer_t *initializer_from_string(array_type_t *type,
1011 const string_t *const string)
1013 /* TODO: check len vs. size of array type */
1016 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1017 initializer->string.string = *string;
1022 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1023 wide_string_t *const string)
1025 /* TODO: check len vs. size of array type */
1028 initializer_t *const initializer =
1029 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1030 initializer->wide_string.string = *string;
1036 * Build an initializer from a given expression.
1038 static initializer_t *initializer_from_expression(type_t *orig_type,
1039 expression_t *expression)
1041 /* TODO check that expression is a constant expression */
1043 /* § 6.7.8.14/15 char array may be initialized by string literals */
1044 type_t *type = skip_typeref(orig_type);
1045 type_t *expr_type_orig = expression->base.type;
1046 type_t *expr_type = skip_typeref(expr_type_orig);
1047 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1048 array_type_t *const array_type = &type->array;
1049 type_t *const element_type = skip_typeref(array_type->element_type);
1051 if (element_type->kind == TYPE_ATOMIC) {
1052 atomic_type_kind_t akind = element_type->atomic.akind;
1053 switch (expression->kind) {
1054 case EXPR_STRING_LITERAL:
1055 if (akind == ATOMIC_TYPE_CHAR
1056 || akind == ATOMIC_TYPE_SCHAR
1057 || akind == ATOMIC_TYPE_UCHAR) {
1058 return initializer_from_string(array_type,
1059 &expression->string.value);
1062 case EXPR_WIDE_STRING_LITERAL: {
1063 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1064 if (get_unqualified_type(element_type) == bare_wchar_type) {
1065 return initializer_from_wide_string(array_type,
1066 &expression->wide_string.value);
1076 type_t *const res_type = semantic_assign(type, expression, "initializer");
1077 if (res_type == NULL)
1080 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1081 result->value.value = create_implicit_cast(expression, res_type);
1087 * Checks if a given expression can be used as an constant initializer.
1089 static bool is_initializer_constant(const expression_t *expression)
1091 return is_constant_expression(expression)
1092 || is_address_constant(expression);
1096 * Parses an scalar initializer.
1098 * § 6.7.8.11; eat {} without warning
1100 static initializer_t *parse_scalar_initializer(type_t *type,
1101 bool must_be_constant)
1103 /* there might be extra {} hierarchies */
1105 while(token.type == '{') {
1108 warningf(HERE, "extra curly braces around scalar initializer");
1113 expression_t *expression = parse_assignment_expression();
1114 if(must_be_constant && !is_initializer_constant(expression)) {
1115 errorf(expression->base.source_position,
1116 "Initialisation expression '%E' is not constant\n",
1120 initializer_t *initializer = initializer_from_expression(type, expression);
1122 if(initializer == NULL) {
1123 errorf(expression->base.source_position,
1124 "expression '%E' doesn't match expected type '%T'",
1130 bool additional_warning_displayed = false;
1132 if(token.type == ',') {
1135 if(token.type != '}') {
1136 if(!additional_warning_displayed) {
1137 warningf(HERE, "additional elements in scalar initializer");
1138 additional_warning_displayed = true;
1149 * An entry in the type path.
1151 typedef struct type_path_entry_t type_path_entry_t;
1152 struct type_path_entry_t {
1153 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1155 size_t index; /**< For array types: the current index. */
1156 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1161 * A type path expression a position inside compound or array types.
1163 typedef struct type_path_t type_path_t;
1164 struct type_path_t {
1165 type_path_entry_t *path; /**< An flexible array containing the current path. */
1166 type_t *top_type; /**< type of the element the path points */
1167 size_t max_index; /**< largest index in outermost array */
1171 * Prints a type path for debugging.
1173 static __attribute__((unused)) void debug_print_type_path(
1174 const type_path_t *path)
1176 size_t len = ARR_LEN(path->path);
1178 for(size_t i = 0; i < len; ++i) {
1179 const type_path_entry_t *entry = & path->path[i];
1181 type_t *type = skip_typeref(entry->type);
1182 if(is_type_compound(type)) {
1183 /* in gcc mode structs can have no members */
1184 if(entry->v.compound_entry == NULL) {
1188 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1189 } else if(is_type_array(type)) {
1190 fprintf(stderr, "[%u]", entry->v.index);
1192 fprintf(stderr, "-INVALID-");
1195 if(path->top_type != NULL) {
1196 fprintf(stderr, " (");
1197 print_type(path->top_type);
1198 fprintf(stderr, ")");
1203 * Return the top type path entry, ie. in a path
1204 * (type).a.b returns the b.
1206 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1208 size_t len = ARR_LEN(path->path);
1210 return &path->path[len-1];
1214 * Enlarge the type path by an (empty) element.
1216 static type_path_entry_t *append_to_type_path(type_path_t *path)
1218 size_t len = ARR_LEN(path->path);
1219 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1221 type_path_entry_t *result = & path->path[len];
1222 memset(result, 0, sizeof(result[0]));
1227 * Descending into a sub-type. Enter the scope of the current
1230 static void descend_into_subtype(type_path_t *path)
1232 type_t *orig_top_type = path->top_type;
1233 type_t *top_type = skip_typeref(orig_top_type);
1235 assert(is_type_compound(top_type) || is_type_array(top_type));
1237 type_path_entry_t *top = append_to_type_path(path);
1238 top->type = top_type;
1240 if(is_type_compound(top_type)) {
1241 declaration_t *declaration = top_type->compound.declaration;
1242 declaration_t *entry = declaration->scope.declarations;
1243 top->v.compound_entry = entry;
1246 path->top_type = entry->type;
1248 path->top_type = NULL;
1251 assert(is_type_array(top_type));
1254 path->top_type = top_type->array.element_type;
1259 * Pop an entry from the given type path, ie. returning from
1260 * (type).a.b to (type).a
1262 static void ascend_from_subtype(type_path_t *path)
1264 type_path_entry_t *top = get_type_path_top(path);
1266 path->top_type = top->type;
1268 size_t len = ARR_LEN(path->path);
1269 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1273 * Pop entries from the given type path until the given
1274 * path level is reached.
1276 static void ascend_to(type_path_t *path, size_t top_path_level)
1278 size_t len = ARR_LEN(path->path);
1280 while(len > top_path_level) {
1281 ascend_from_subtype(path);
1282 len = ARR_LEN(path->path);
1286 static bool walk_designator(type_path_t *path, const designator_t *designator,
1287 bool used_in_offsetof)
1289 for( ; designator != NULL; designator = designator->next) {
1290 type_path_entry_t *top = get_type_path_top(path);
1291 type_t *orig_type = top->type;
1293 type_t *type = skip_typeref(orig_type);
1295 if(designator->symbol != NULL) {
1296 symbol_t *symbol = designator->symbol;
1297 if(!is_type_compound(type)) {
1298 if(is_type_valid(type)) {
1299 errorf(designator->source_position,
1300 "'.%Y' designator used for non-compound type '%T'",
1306 declaration_t *declaration = type->compound.declaration;
1307 declaration_t *iter = declaration->scope.declarations;
1308 for( ; iter != NULL; iter = iter->next) {
1309 if(iter->symbol == symbol) {
1314 errorf(designator->source_position,
1315 "'%T' has no member named '%Y'", orig_type, symbol);
1318 if(used_in_offsetof) {
1319 type_t *real_type = skip_typeref(iter->type);
1320 if(real_type->kind == TYPE_BITFIELD) {
1321 errorf(designator->source_position,
1322 "offsetof designator '%Y' may not specify bitfield",
1328 top->type = orig_type;
1329 top->v.compound_entry = iter;
1330 orig_type = iter->type;
1332 expression_t *array_index = designator->array_index;
1333 assert(designator->array_index != NULL);
1335 if(!is_type_array(type)) {
1336 if(is_type_valid(type)) {
1337 errorf(designator->source_position,
1338 "[%E] designator used for non-array type '%T'",
1339 array_index, orig_type);
1343 if(!is_type_valid(array_index->base.type)) {
1347 long index = fold_constant(array_index);
1348 if(!used_in_offsetof) {
1350 errorf(designator->source_position,
1351 "array index [%E] must be positive", array_index);
1354 if(type->array.size_constant == true) {
1355 long array_size = type->array.size;
1356 if(index >= array_size) {
1357 errorf(designator->source_position,
1358 "designator [%E] (%d) exceeds array size %d",
1359 array_index, index, array_size);
1365 top->type = orig_type;
1366 top->v.index = (size_t) index;
1367 orig_type = type->array.element_type;
1369 path->top_type = orig_type;
1371 if(designator->next != NULL) {
1372 descend_into_subtype(path);
1381 static void advance_current_object(type_path_t *path, size_t top_path_level)
1383 type_path_entry_t *top = get_type_path_top(path);
1385 type_t *type = skip_typeref(top->type);
1386 if(is_type_union(type)) {
1387 /* in unions only the first element is initialized */
1388 top->v.compound_entry = NULL;
1389 } else if(is_type_struct(type)) {
1390 declaration_t *entry = top->v.compound_entry;
1392 entry = entry->next;
1393 top->v.compound_entry = entry;
1395 path->top_type = entry->type;
1399 assert(is_type_array(type));
1403 if(!type->array.size_constant || top->v.index < type->array.size) {
1408 /* we're past the last member of the current sub-aggregate, try if we
1409 * can ascend in the type hierarchy and continue with another subobject */
1410 size_t len = ARR_LEN(path->path);
1412 if(len > top_path_level) {
1413 ascend_from_subtype(path);
1414 advance_current_object(path, top_path_level);
1416 path->top_type = NULL;
1421 * skip until token is found.
1423 static void skip_until(int type) {
1424 while(token.type != type) {
1425 if(token.type == T_EOF)
1432 * skip any {...} blocks until a closing braket is reached.
1434 static void skip_initializers(void)
1436 if(token.type == '{')
1439 while(token.type != '}') {
1440 if(token.type == T_EOF)
1442 if(token.type == '{') {
1451 * Parse a part of an initialiser for a struct or union,
1453 static initializer_t *parse_sub_initializer(type_path_t *path,
1454 type_t *outer_type, size_t top_path_level,
1455 parse_initializer_env_t *env)
1457 if(token.type == '}') {
1458 /* empty initializer */
1462 type_t *orig_type = path->top_type;
1463 type_t *type = NULL;
1465 if (orig_type == NULL) {
1466 /* We are initializing an empty compound. */
1468 type = skip_typeref(orig_type);
1470 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1471 * initializers in this case. */
1472 if(!is_type_valid(type)) {
1473 skip_initializers();
1478 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1481 designator_t *designator = NULL;
1482 if(token.type == '.' || token.type == '[') {
1483 designator = parse_designation();
1485 /* reset path to toplevel, evaluate designator from there */
1486 ascend_to(path, top_path_level);
1487 if(!walk_designator(path, designator, false)) {
1488 /* can't continue after designation error */
1492 initializer_t *designator_initializer
1493 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1494 designator_initializer->designator.designator = designator;
1495 ARR_APP1(initializer_t*, initializers, designator_initializer);
1500 if(token.type == '{') {
1501 if(type != NULL && is_type_scalar(type)) {
1502 sub = parse_scalar_initializer(type, env->must_be_constant);
1506 if (env->declaration != NULL)
1507 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1508 env->declaration->symbol);
1510 errorf(HERE, "extra brace group at end of initializer");
1512 descend_into_subtype(path);
1514 add_anchor_token('}');
1515 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1517 rem_anchor_token('}');
1520 ascend_from_subtype(path);
1524 goto error_parse_next;
1528 /* must be an expression */
1529 expression_t *expression = parse_assignment_expression();
1531 if(env->must_be_constant && !is_initializer_constant(expression)) {
1532 errorf(expression->base.source_position,
1533 "Initialisation expression '%E' is not constant\n",
1538 /* we are already outside, ... */
1542 /* handle { "string" } special case */
1543 if((expression->kind == EXPR_STRING_LITERAL
1544 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1545 && outer_type != NULL) {
1546 sub = initializer_from_expression(outer_type, expression);
1548 if(token.type == ',') {
1551 if(token.type != '}') {
1552 warningf(HERE, "excessive elements in initializer for type '%T'",
1555 /* TODO: eat , ... */
1560 /* descend into subtypes until expression matches type */
1562 orig_type = path->top_type;
1563 type = skip_typeref(orig_type);
1565 sub = initializer_from_expression(orig_type, expression);
1569 if(!is_type_valid(type)) {
1572 if(is_type_scalar(type)) {
1573 errorf(expression->base.source_position,
1574 "expression '%E' doesn't match expected type '%T'",
1575 expression, orig_type);
1579 descend_into_subtype(path);
1583 /* update largest index of top array */
1584 const type_path_entry_t *first = &path->path[0];
1585 type_t *first_type = first->type;
1586 first_type = skip_typeref(first_type);
1587 if(is_type_array(first_type)) {
1588 size_t index = first->v.index;
1589 if(index > path->max_index)
1590 path->max_index = index;
1594 /* append to initializers list */
1595 ARR_APP1(initializer_t*, initializers, sub);
1598 if(env->declaration != NULL)
1599 warningf(HERE, "excess elements in struct initializer for '%Y'",
1600 env->declaration->symbol);
1602 warningf(HERE, "excess elements in struct initializer");
1606 if(token.type == '}') {
1610 if(token.type == '}') {
1615 /* advance to the next declaration if we are not at the end */
1616 advance_current_object(path, top_path_level);
1617 orig_type = path->top_type;
1618 if(orig_type != NULL)
1619 type = skip_typeref(orig_type);
1625 size_t len = ARR_LEN(initializers);
1626 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1627 initializer_t *result = allocate_ast_zero(size);
1628 result->kind = INITIALIZER_LIST;
1629 result->list.len = len;
1630 memcpy(&result->list.initializers, initializers,
1631 len * sizeof(initializers[0]));
1633 DEL_ARR_F(initializers);
1634 ascend_to(path, top_path_level);
1639 skip_initializers();
1640 DEL_ARR_F(initializers);
1641 ascend_to(path, top_path_level);
1646 * Parses an initializer. Parsers either a compound literal
1647 * (env->declaration == NULL) or an initializer of a declaration.
1649 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1651 type_t *type = skip_typeref(env->type);
1652 initializer_t *result = NULL;
1655 if(is_type_scalar(type)) {
1656 result = parse_scalar_initializer(type, env->must_be_constant);
1657 } else if(token.type == '{') {
1661 memset(&path, 0, sizeof(path));
1662 path.top_type = env->type;
1663 path.path = NEW_ARR_F(type_path_entry_t, 0);
1665 descend_into_subtype(&path);
1667 add_anchor_token('}');
1668 result = parse_sub_initializer(&path, env->type, 1, env);
1669 rem_anchor_token('}');
1671 max_index = path.max_index;
1672 DEL_ARR_F(path.path);
1676 /* parse_scalar_initializer() also works in this case: we simply
1677 * have an expression without {} around it */
1678 result = parse_scalar_initializer(type, env->must_be_constant);
1681 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1682 * the array type size */
1683 if(is_type_array(type) && type->array.size_expression == NULL
1684 && result != NULL) {
1686 switch (result->kind) {
1687 case INITIALIZER_LIST:
1688 size = max_index + 1;
1691 case INITIALIZER_STRING:
1692 size = result->string.string.size;
1695 case INITIALIZER_WIDE_STRING:
1696 size = result->wide_string.string.size;
1700 panic("invalid initializer type");
1703 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1704 cnst->base.type = type_size_t;
1705 cnst->conste.v.int_value = size;
1707 type_t *new_type = duplicate_type(type);
1709 new_type->array.size_expression = cnst;
1710 new_type->array.size_constant = true;
1711 new_type->array.size = size;
1712 env->type = new_type;
1720 static declaration_t *append_declaration(declaration_t *declaration);
1722 static declaration_t *parse_compound_type_specifier(bool is_struct)
1730 symbol_t *symbol = NULL;
1731 declaration_t *declaration = NULL;
1733 if (token.type == T___attribute__) {
1738 if(token.type == T_IDENTIFIER) {
1739 symbol = token.v.symbol;
1743 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1745 declaration = get_declaration(symbol, NAMESPACE_UNION);
1747 } else if(token.type != '{') {
1749 parse_error_expected("while parsing struct type specifier",
1750 T_IDENTIFIER, '{', 0);
1752 parse_error_expected("while parsing union type specifier",
1753 T_IDENTIFIER, '{', 0);
1759 if(declaration == NULL) {
1760 declaration = allocate_declaration_zero();
1761 declaration->namespc =
1762 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1763 declaration->source_position = token.source_position;
1764 declaration->symbol = symbol;
1765 declaration->parent_scope = scope;
1766 if (symbol != NULL) {
1767 environment_push(declaration);
1769 append_declaration(declaration);
1772 if(token.type == '{') {
1773 if(declaration->init.is_defined) {
1774 assert(symbol != NULL);
1775 errorf(HERE, "multiple definitions of '%s %Y'",
1776 is_struct ? "struct" : "union", symbol);
1777 declaration->scope.declarations = NULL;
1779 declaration->init.is_defined = true;
1781 parse_compound_type_entries(declaration);
1788 static void parse_enum_entries(type_t *const enum_type)
1792 if(token.type == '}') {
1794 errorf(HERE, "empty enum not allowed");
1798 add_anchor_token('}');
1800 if(token.type != T_IDENTIFIER) {
1801 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1803 rem_anchor_token('}');
1807 declaration_t *const entry = allocate_declaration_zero();
1808 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1809 entry->type = enum_type;
1810 entry->symbol = token.v.symbol;
1811 entry->source_position = token.source_position;
1814 if(token.type == '=') {
1816 expression_t *value = parse_constant_expression();
1818 value = create_implicit_cast(value, enum_type);
1819 entry->init.enum_value = value;
1824 record_declaration(entry);
1826 if(token.type != ',')
1829 } while(token.type != '}');
1830 rem_anchor_token('}');
1838 static type_t *parse_enum_specifier(void)
1842 declaration_t *declaration;
1845 if(token.type == T_IDENTIFIER) {
1846 symbol = token.v.symbol;
1849 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1850 } else if(token.type != '{') {
1851 parse_error_expected("while parsing enum type specifier",
1852 T_IDENTIFIER, '{', 0);
1859 if(declaration == NULL) {
1860 declaration = allocate_declaration_zero();
1861 declaration->namespc = NAMESPACE_ENUM;
1862 declaration->source_position = token.source_position;
1863 declaration->symbol = symbol;
1864 declaration->parent_scope = scope;
1867 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1868 type->enumt.declaration = declaration;
1870 if(token.type == '{') {
1871 if(declaration->init.is_defined) {
1872 errorf(HERE, "multiple definitions of enum %Y", symbol);
1874 if (symbol != NULL) {
1875 environment_push(declaration);
1877 append_declaration(declaration);
1878 declaration->init.is_defined = 1;
1880 parse_enum_entries(type);
1888 * if a symbol is a typedef to another type, return true
1890 static bool is_typedef_symbol(symbol_t *symbol)
1892 const declaration_t *const declaration =
1893 get_declaration(symbol, NAMESPACE_NORMAL);
1895 declaration != NULL &&
1896 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1899 static type_t *parse_typeof(void)
1906 add_anchor_token(')');
1908 expression_t *expression = NULL;
1911 switch(token.type) {
1912 case T___extension__:
1913 /* this can be a prefix to a typename or an expression */
1914 /* we simply eat it now. */
1917 } while(token.type == T___extension__);
1921 if(is_typedef_symbol(token.v.symbol)) {
1922 type = parse_typename();
1924 expression = parse_expression();
1925 type = expression->base.type;
1930 type = parse_typename();
1934 expression = parse_expression();
1935 type = expression->base.type;
1939 rem_anchor_token(')');
1942 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1943 typeof_type->typeoft.expression = expression;
1944 typeof_type->typeoft.typeof_type = type;
1952 SPECIFIER_SIGNED = 1 << 0,
1953 SPECIFIER_UNSIGNED = 1 << 1,
1954 SPECIFIER_LONG = 1 << 2,
1955 SPECIFIER_INT = 1 << 3,
1956 SPECIFIER_DOUBLE = 1 << 4,
1957 SPECIFIER_CHAR = 1 << 5,
1958 SPECIFIER_SHORT = 1 << 6,
1959 SPECIFIER_LONG_LONG = 1 << 7,
1960 SPECIFIER_FLOAT = 1 << 8,
1961 SPECIFIER_BOOL = 1 << 9,
1962 SPECIFIER_VOID = 1 << 10,
1963 #ifdef PROVIDE_COMPLEX
1964 SPECIFIER_COMPLEX = 1 << 11,
1965 SPECIFIER_IMAGINARY = 1 << 12,
1969 static type_t *create_builtin_type(symbol_t *const symbol,
1970 type_t *const real_type)
1972 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1973 type->builtin.symbol = symbol;
1974 type->builtin.real_type = real_type;
1976 type_t *result = typehash_insert(type);
1977 if (type != result) {
1984 static type_t *get_typedef_type(symbol_t *symbol)
1986 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1987 if(declaration == NULL
1988 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1991 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1992 type->typedeft.declaration = declaration;
1998 * check for the allowed MS alignment values.
2000 static bool check_elignment_value(long long intvalue) {
2001 if(intvalue < 1 || intvalue > 8192) {
2002 errorf(HERE, "illegal alignment value");
2005 unsigned v = (unsigned)intvalue;
2006 for(unsigned i = 1; i <= 8192; i += i) {
2010 errorf(HERE, "alignment must be power of two");
2014 #define DET_MOD(name, tag) do { \
2015 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2016 *modifiers |= tag; \
2019 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2022 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2024 while(token.type == T_IDENTIFIER) {
2025 symbol = token.v.symbol;
2026 if(symbol == sym_align) {
2029 if(token.type != T_INTEGER)
2031 if(check_elignment_value(token.v.intvalue)) {
2032 if(specifiers->alignment != 0)
2033 warningf(HERE, "align used more than once");
2034 specifiers->alignment = (unsigned char)token.v.intvalue;
2038 } else if(symbol == sym_allocate) {
2041 if(token.type != T_IDENTIFIER)
2043 (void)token.v.symbol;
2045 } else if(symbol == sym_dllimport) {
2047 DET_MOD(dllimport, DM_DLLIMPORT);
2048 } else if(symbol == sym_dllexport) {
2050 DET_MOD(dllexport, DM_DLLEXPORT);
2051 } else if(symbol == sym_thread) {
2053 DET_MOD(thread, DM_THREAD);
2054 } else if(symbol == sym_naked) {
2056 DET_MOD(naked, DM_NAKED);
2057 } else if(symbol == sym_noinline) {
2059 DET_MOD(noinline, DM_NOINLINE);
2060 } else if(symbol == sym_noreturn) {
2062 DET_MOD(noreturn, DM_NORETURN);
2063 } else if(symbol == sym_nothrow) {
2065 DET_MOD(nothrow, DM_NOTHROW);
2066 } else if(symbol == sym_novtable) {
2068 DET_MOD(novtable, DM_NOVTABLE);
2069 } else if(symbol == sym_property) {
2073 bool is_get = false;
2074 if(token.type != T_IDENTIFIER)
2076 if(token.v.symbol == sym_get) {
2078 } else if(token.v.symbol == sym_put) {
2080 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2085 if(token.type != T_IDENTIFIER)
2088 if(specifiers->get_property_sym != NULL) {
2089 errorf(HERE, "get property name already specified");
2091 specifiers->get_property_sym = token.v.symbol;
2094 if(specifiers->put_property_sym != NULL) {
2095 errorf(HERE, "put property name already specified");
2097 specifiers->put_property_sym = token.v.symbol;
2101 if(token.type == ',') {
2108 } else if(symbol == sym_selectany) {
2110 DET_MOD(selectany, DM_SELECTANY);
2111 } else if(symbol == sym_uuid) {
2114 if(token.type != T_STRING_LITERAL)
2118 } else if(symbol == sym_deprecated) {
2120 DET_MOD(deprecated, DM_DEPRECATED);
2121 if(token.type == '(') {
2123 if(token.type == T_STRING_LITERAL) {
2124 specifiers->deprecated_string = token.v.string.begin;
2127 errorf(HERE, "string literal expected");
2132 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2134 if(token.type == '(')
2137 if (token.type == ',')
2144 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2146 type_t *type = NULL;
2147 unsigned type_qualifiers = 0;
2148 unsigned type_specifiers = 0;
2151 specifiers->source_position = token.source_position;
2154 switch(token.type) {
2157 #define MATCH_STORAGE_CLASS(token, class) \
2159 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2160 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2162 specifiers->declared_storage_class = class; \
2166 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2167 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2168 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2169 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2170 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2175 add_anchor_token(')');
2176 parse_microsoft_extended_decl_modifier(specifiers);
2177 rem_anchor_token(')');
2182 switch (specifiers->declared_storage_class) {
2183 case STORAGE_CLASS_NONE:
2184 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2187 case STORAGE_CLASS_EXTERN:
2188 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2191 case STORAGE_CLASS_STATIC:
2192 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2196 errorf(HERE, "multiple storage classes in declaration specifiers");
2202 /* type qualifiers */
2203 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2205 type_qualifiers |= qualifier; \
2209 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2210 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2211 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2213 case T___extension__:
2218 /* type specifiers */
2219 #define MATCH_SPECIFIER(token, specifier, name) \
2222 if(type_specifiers & specifier) { \
2223 errorf(HERE, "multiple " name " type specifiers given"); \
2225 type_specifiers |= specifier; \
2229 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2230 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2231 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2232 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2233 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2234 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2235 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2236 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2237 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2238 #ifdef PROVIDE_COMPLEX
2239 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2240 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2243 /* only in microsoft mode */
2244 specifiers->decl_modifiers |= DM_FORCEINLINE;
2248 specifiers->is_inline = true;
2253 if(type_specifiers & SPECIFIER_LONG_LONG) {
2254 errorf(HERE, "multiple type specifiers given");
2255 } else if(type_specifiers & SPECIFIER_LONG) {
2256 type_specifiers |= SPECIFIER_LONG_LONG;
2258 type_specifiers |= SPECIFIER_LONG;
2263 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2265 type->compound.declaration = parse_compound_type_specifier(true);
2269 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2271 type->compound.declaration = parse_compound_type_specifier(false);
2275 type = parse_enum_specifier();
2278 type = parse_typeof();
2280 case T___builtin_va_list:
2281 type = duplicate_type(type_valist);
2285 case T___attribute__:
2289 case T_IDENTIFIER: {
2290 /* only parse identifier if we haven't found a type yet */
2291 if(type != NULL || type_specifiers != 0)
2292 goto finish_specifiers;
2294 type_t *typedef_type = get_typedef_type(token.v.symbol);
2296 if(typedef_type == NULL)
2297 goto finish_specifiers;
2300 type = typedef_type;
2304 /* function specifier */
2306 goto finish_specifiers;
2313 atomic_type_kind_t atomic_type;
2315 /* match valid basic types */
2316 switch(type_specifiers) {
2317 case SPECIFIER_VOID:
2318 atomic_type = ATOMIC_TYPE_VOID;
2320 case SPECIFIER_CHAR:
2321 atomic_type = ATOMIC_TYPE_CHAR;
2323 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2324 atomic_type = ATOMIC_TYPE_SCHAR;
2326 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2327 atomic_type = ATOMIC_TYPE_UCHAR;
2329 case SPECIFIER_SHORT:
2330 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2331 case SPECIFIER_SHORT | SPECIFIER_INT:
2332 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2333 atomic_type = ATOMIC_TYPE_SHORT;
2335 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2336 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2337 atomic_type = ATOMIC_TYPE_USHORT;
2340 case SPECIFIER_SIGNED:
2341 case SPECIFIER_SIGNED | SPECIFIER_INT:
2342 atomic_type = ATOMIC_TYPE_INT;
2344 case SPECIFIER_UNSIGNED:
2345 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2346 atomic_type = ATOMIC_TYPE_UINT;
2348 case SPECIFIER_LONG:
2349 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2350 case SPECIFIER_LONG | SPECIFIER_INT:
2351 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2352 atomic_type = ATOMIC_TYPE_LONG;
2354 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2355 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2356 atomic_type = ATOMIC_TYPE_ULONG;
2358 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2359 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2360 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2361 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2363 atomic_type = ATOMIC_TYPE_LONGLONG;
2365 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2366 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2368 atomic_type = ATOMIC_TYPE_ULONGLONG;
2370 case SPECIFIER_FLOAT:
2371 atomic_type = ATOMIC_TYPE_FLOAT;
2373 case SPECIFIER_DOUBLE:
2374 atomic_type = ATOMIC_TYPE_DOUBLE;
2376 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2377 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2379 case SPECIFIER_BOOL:
2380 atomic_type = ATOMIC_TYPE_BOOL;
2382 #ifdef PROVIDE_COMPLEX
2383 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2384 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2386 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2387 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2389 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2390 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2392 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2393 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2395 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2396 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2398 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2399 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2403 /* invalid specifier combination, give an error message */
2404 if(type_specifiers == 0) {
2405 if (! strict_mode) {
2406 if (warning.implicit_int) {
2407 warningf(HERE, "no type specifiers in declaration, using 'int'");
2409 atomic_type = ATOMIC_TYPE_INT;
2412 errorf(HERE, "no type specifiers given in declaration");
2414 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2415 (type_specifiers & SPECIFIER_UNSIGNED)) {
2416 errorf(HERE, "signed and unsigned specifiers gives");
2417 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2418 errorf(HERE, "only integer types can be signed or unsigned");
2420 errorf(HERE, "multiple datatypes in declaration");
2422 atomic_type = ATOMIC_TYPE_INVALID;
2425 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2426 type->atomic.akind = atomic_type;
2429 if(type_specifiers != 0) {
2430 errorf(HERE, "multiple datatypes in declaration");
2434 type->base.qualifiers = type_qualifiers;
2436 type_t *result = typehash_insert(type);
2437 if(newtype && result != type) {
2441 specifiers->type = result;
2446 static type_qualifiers_t parse_type_qualifiers(void)
2448 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2451 switch(token.type) {
2452 /* type qualifiers */
2453 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2454 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2455 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2458 return type_qualifiers;
2463 static declaration_t *parse_identifier_list(void)
2465 declaration_t *declarations = NULL;
2466 declaration_t *last_declaration = NULL;
2468 declaration_t *const declaration = allocate_declaration_zero();
2469 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2470 declaration->source_position = token.source_position;
2471 declaration->symbol = token.v.symbol;
2474 if(last_declaration != NULL) {
2475 last_declaration->next = declaration;
2477 declarations = declaration;
2479 last_declaration = declaration;
2481 if(token.type != ',')
2484 } while(token.type == T_IDENTIFIER);
2486 return declarations;
2489 static void semantic_parameter(declaration_t *declaration)
2491 /* TODO: improve error messages */
2493 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2494 errorf(HERE, "typedef not allowed in parameter list");
2495 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2496 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2497 errorf(HERE, "parameter may only have none or register storage class");
2500 type_t *const orig_type = declaration->type;
2501 type_t * type = skip_typeref(orig_type);
2503 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2504 * into a pointer. § 6.7.5.3 (7) */
2505 if (is_type_array(type)) {
2506 type_t *const element_type = type->array.element_type;
2508 type = make_pointer_type(element_type, type->base.qualifiers);
2510 declaration->type = type;
2513 if(is_type_incomplete(type)) {
2514 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2515 orig_type, declaration->symbol);
2519 static declaration_t *parse_parameter(void)
2521 declaration_specifiers_t specifiers;
2522 memset(&specifiers, 0, sizeof(specifiers));
2524 parse_declaration_specifiers(&specifiers);
2526 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2528 semantic_parameter(declaration);
2533 static declaration_t *parse_parameters(function_type_t *type)
2535 if(token.type == T_IDENTIFIER) {
2536 symbol_t *symbol = token.v.symbol;
2537 if(!is_typedef_symbol(symbol)) {
2538 type->kr_style_parameters = true;
2539 return parse_identifier_list();
2543 if(token.type == ')') {
2544 type->unspecified_parameters = 1;
2547 if(token.type == T_void && look_ahead(1)->type == ')') {
2552 declaration_t *declarations = NULL;
2553 declaration_t *declaration;
2554 declaration_t *last_declaration = NULL;
2555 function_parameter_t *parameter;
2556 function_parameter_t *last_parameter = NULL;
2559 switch(token.type) {
2563 return declarations;
2566 case T___extension__:
2568 declaration = parse_parameter();
2570 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2571 memset(parameter, 0, sizeof(parameter[0]));
2572 parameter->type = declaration->type;
2574 if(last_parameter != NULL) {
2575 last_declaration->next = declaration;
2576 last_parameter->next = parameter;
2578 type->parameters = parameter;
2579 declarations = declaration;
2581 last_parameter = parameter;
2582 last_declaration = declaration;
2586 return declarations;
2588 if(token.type != ',')
2589 return declarations;
2599 } construct_type_kind_t;
2601 typedef struct construct_type_t construct_type_t;
2602 struct construct_type_t {
2603 construct_type_kind_t kind;
2604 construct_type_t *next;
2607 typedef struct parsed_pointer_t parsed_pointer_t;
2608 struct parsed_pointer_t {
2609 construct_type_t construct_type;
2610 type_qualifiers_t type_qualifiers;
2613 typedef struct construct_function_type_t construct_function_type_t;
2614 struct construct_function_type_t {
2615 construct_type_t construct_type;
2616 type_t *function_type;
2619 typedef struct parsed_array_t parsed_array_t;
2620 struct parsed_array_t {
2621 construct_type_t construct_type;
2622 type_qualifiers_t type_qualifiers;
2628 typedef struct construct_base_type_t construct_base_type_t;
2629 struct construct_base_type_t {
2630 construct_type_t construct_type;
2634 static construct_type_t *parse_pointer_declarator(void)
2638 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2639 memset(pointer, 0, sizeof(pointer[0]));
2640 pointer->construct_type.kind = CONSTRUCT_POINTER;
2641 pointer->type_qualifiers = parse_type_qualifiers();
2643 return (construct_type_t*) pointer;
2646 static construct_type_t *parse_array_declarator(void)
2649 add_anchor_token(']');
2651 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2652 memset(array, 0, sizeof(array[0]));
2653 array->construct_type.kind = CONSTRUCT_ARRAY;
2655 if(token.type == T_static) {
2656 array->is_static = true;
2660 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2661 if(type_qualifiers != 0) {
2662 if(token.type == T_static) {
2663 array->is_static = true;
2667 array->type_qualifiers = type_qualifiers;
2669 if(token.type == '*' && look_ahead(1)->type == ']') {
2670 array->is_variable = true;
2672 } else if(token.type != ']') {
2673 array->size = parse_assignment_expression();
2676 rem_anchor_token(']');
2679 return (construct_type_t*) array;
2684 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2687 add_anchor_token(')');
2690 if(declaration != NULL) {
2691 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2693 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2696 declaration_t *parameters = parse_parameters(&type->function);
2697 if(declaration != NULL) {
2698 declaration->scope.declarations = parameters;
2701 construct_function_type_t *construct_function_type =
2702 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2703 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2704 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2705 construct_function_type->function_type = type;
2707 rem_anchor_token(')');
2711 return (construct_type_t*) construct_function_type;
2714 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2715 bool may_be_abstract)
2717 /* construct a single linked list of construct_type_t's which describe
2718 * how to construct the final declarator type */
2719 construct_type_t *first = NULL;
2720 construct_type_t *last = NULL;
2723 while(token.type == '*') {
2724 construct_type_t *type = parse_pointer_declarator();
2735 /* TODO: find out if this is correct */
2738 construct_type_t *inner_types = NULL;
2740 switch(token.type) {
2742 if(declaration == NULL) {
2743 errorf(HERE, "no identifier expected in typename");
2745 declaration->symbol = token.v.symbol;
2746 declaration->source_position = token.source_position;
2752 add_anchor_token(')');
2753 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2754 rem_anchor_token(')');
2760 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2761 /* avoid a loop in the outermost scope, because eat_statement doesn't
2763 if(token.type == '}' && current_function == NULL) {
2771 construct_type_t *p = last;
2774 construct_type_t *type;
2775 switch(token.type) {
2777 type = parse_function_declarator(declaration);
2780 type = parse_array_declarator();
2783 goto declarator_finished;
2786 /* insert in the middle of the list (behind p) */
2788 type->next = p->next;
2799 declarator_finished:
2802 /* append inner_types at the end of the list, we don't to set last anymore
2803 * as it's not needed anymore */
2805 assert(first == NULL);
2806 first = inner_types;
2808 last->next = inner_types;
2816 static type_t *construct_declarator_type(construct_type_t *construct_list,
2819 construct_type_t *iter = construct_list;
2820 for( ; iter != NULL; iter = iter->next) {
2821 switch(iter->kind) {
2822 case CONSTRUCT_INVALID:
2823 panic("invalid type construction found");
2824 case CONSTRUCT_FUNCTION: {
2825 construct_function_type_t *construct_function_type
2826 = (construct_function_type_t*) iter;
2828 type_t *function_type = construct_function_type->function_type;
2830 function_type->function.return_type = type;
2832 type_t *skipped_return_type = skip_typeref(type);
2833 if (is_type_function(skipped_return_type)) {
2834 errorf(HERE, "function returning function is not allowed");
2835 type = type_error_type;
2836 } else if (is_type_array(skipped_return_type)) {
2837 errorf(HERE, "function returning array is not allowed");
2838 type = type_error_type;
2840 type = function_type;
2845 case CONSTRUCT_POINTER: {
2846 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2847 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2848 pointer_type->pointer.points_to = type;
2849 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2851 type = pointer_type;
2855 case CONSTRUCT_ARRAY: {
2856 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2857 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2859 expression_t *size_expression = parsed_array->size;
2860 if(size_expression != NULL) {
2862 = create_implicit_cast(size_expression, type_size_t);
2865 array_type->base.qualifiers = parsed_array->type_qualifiers;
2866 array_type->array.element_type = type;
2867 array_type->array.is_static = parsed_array->is_static;
2868 array_type->array.is_variable = parsed_array->is_variable;
2869 array_type->array.size_expression = size_expression;
2871 if(size_expression != NULL) {
2872 if(is_constant_expression(size_expression)) {
2873 array_type->array.size_constant = true;
2874 array_type->array.size
2875 = fold_constant(size_expression);
2877 array_type->array.is_vla = true;
2881 type_t *skipped_type = skip_typeref(type);
2882 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2883 errorf(HERE, "array of void is not allowed");
2884 type = type_error_type;
2892 type_t *hashed_type = typehash_insert(type);
2893 if(hashed_type != type) {
2894 /* the function type was constructed earlier freeing it here will
2895 * destroy other types... */
2896 if(iter->kind != CONSTRUCT_FUNCTION) {
2906 static declaration_t *parse_declarator(
2907 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2909 declaration_t *const declaration = allocate_declaration_zero();
2910 declaration->declared_storage_class = specifiers->declared_storage_class;
2911 declaration->modifiers = specifiers->decl_modifiers;
2912 declaration->deprecated_string = specifiers->deprecated_string;
2913 declaration->get_property_sym = specifiers->get_property_sym;
2914 declaration->put_property_sym = specifiers->put_property_sym;
2915 declaration->is_inline = specifiers->is_inline;
2917 declaration->storage_class = specifiers->declared_storage_class;
2918 if(declaration->storage_class == STORAGE_CLASS_NONE
2919 && scope != global_scope) {
2920 declaration->storage_class = STORAGE_CLASS_AUTO;
2923 if(specifiers->alignment != 0) {
2924 /* TODO: add checks here */
2925 declaration->alignment = specifiers->alignment;
2928 construct_type_t *construct_type
2929 = parse_inner_declarator(declaration, may_be_abstract);
2930 type_t *const type = specifiers->type;
2931 declaration->type = construct_declarator_type(construct_type, type);
2933 if(construct_type != NULL) {
2934 obstack_free(&temp_obst, construct_type);
2940 static type_t *parse_abstract_declarator(type_t *base_type)
2942 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2944 type_t *result = construct_declarator_type(construct_type, base_type);
2945 if(construct_type != NULL) {
2946 obstack_free(&temp_obst, construct_type);
2952 static declaration_t *append_declaration(declaration_t* const declaration)
2954 if (last_declaration != NULL) {
2955 last_declaration->next = declaration;
2957 scope->declarations = declaration;
2959 last_declaration = declaration;
2964 * Check if the declaration of main is suspicious. main should be a
2965 * function with external linkage, returning int, taking either zero
2966 * arguments, two, or three arguments of appropriate types, ie.
2968 * int main([ int argc, char **argv [, char **env ] ]).
2970 * @param decl the declaration to check
2971 * @param type the function type of the declaration
2973 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2975 if (decl->storage_class == STORAGE_CLASS_STATIC) {
2976 warningf(decl->source_position, "'main' is normally a non-static function");
2978 if (skip_typeref(func_type->return_type) != type_int) {
2979 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2981 const function_parameter_t *parm = func_type->parameters;
2983 type_t *const first_type = parm->type;
2984 if (!types_compatible(skip_typeref(first_type), type_int)) {
2985 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2989 type_t *const second_type = parm->type;
2990 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2991 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2995 type_t *const third_type = parm->type;
2996 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2997 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3001 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3005 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3011 * Check if a symbol is the equal to "main".
3013 static bool is_sym_main(const symbol_t *const sym)
3015 return strcmp(sym->string, "main") == 0;
3018 static declaration_t *internal_record_declaration(
3019 declaration_t *const declaration,
3020 const bool is_function_definition)
3022 const symbol_t *const symbol = declaration->symbol;
3023 const namespace_t namespc = (namespace_t)declaration->namespc;
3025 type_t *const orig_type = declaration->type;
3026 type_t *const type = skip_typeref(orig_type);
3027 if (is_type_function(type) &&
3028 type->function.unspecified_parameters &&
3029 warning.strict_prototypes) {
3030 warningf(declaration->source_position,
3031 "function declaration '%#T' is not a prototype",
3032 orig_type, declaration->symbol);
3035 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3036 check_type_of_main(declaration, &type->function);
3039 assert(declaration->symbol != NULL);
3040 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3042 assert(declaration != previous_declaration);
3043 if (previous_declaration != NULL) {
3044 if (previous_declaration->parent_scope == scope) {
3045 /* can happen for K&R style declarations */
3046 if(previous_declaration->type == NULL) {
3047 previous_declaration->type = declaration->type;
3050 const type_t *prev_type = skip_typeref(previous_declaration->type);
3051 if (!types_compatible(type, prev_type)) {
3052 errorf(declaration->source_position,
3053 "declaration '%#T' is incompatible with "
3054 "previous declaration '%#T'",
3055 orig_type, symbol, previous_declaration->type, symbol);
3056 errorf(previous_declaration->source_position,
3057 "previous declaration of '%Y' was here", symbol);
3059 unsigned old_storage_class = previous_declaration->storage_class;
3060 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3061 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3062 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3063 return previous_declaration;
3066 unsigned new_storage_class = declaration->storage_class;
3068 if(is_type_incomplete(prev_type)) {
3069 previous_declaration->type = type;
3073 /* pretend no storage class means extern for function
3074 * declarations (except if the previous declaration is neither
3075 * none nor extern) */
3076 if (is_type_function(type)) {
3077 switch (old_storage_class) {
3078 case STORAGE_CLASS_NONE:
3079 old_storage_class = STORAGE_CLASS_EXTERN;
3081 case STORAGE_CLASS_EXTERN:
3082 if (is_function_definition) {
3083 if (warning.missing_prototypes &&
3084 prev_type->function.unspecified_parameters &&
3085 !is_sym_main(symbol)) {
3086 warningf(declaration->source_position,
3087 "no previous prototype for '%#T'",
3090 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3091 new_storage_class = STORAGE_CLASS_EXTERN;
3099 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3100 new_storage_class == STORAGE_CLASS_EXTERN) {
3101 warn_redundant_declaration:
3102 if (warning.redundant_decls) {
3103 warningf(declaration->source_position,
3104 "redundant declaration for '%Y'", symbol);
3105 warningf(previous_declaration->source_position,
3106 "previous declaration of '%Y' was here",
3109 } else if (current_function == NULL) {
3110 if (old_storage_class != STORAGE_CLASS_STATIC &&
3111 new_storage_class == STORAGE_CLASS_STATIC) {
3112 errorf(declaration->source_position,
3113 "static declaration of '%Y' follows non-static declaration",
3115 errorf(previous_declaration->source_position,
3116 "previous declaration of '%Y' was here", symbol);
3118 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3119 goto warn_redundant_declaration;
3121 if (new_storage_class == STORAGE_CLASS_NONE) {
3122 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3123 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3127 if (old_storage_class == new_storage_class) {
3128 errorf(declaration->source_position,
3129 "redeclaration of '%Y'", symbol);
3131 errorf(declaration->source_position,
3132 "redeclaration of '%Y' with different linkage",
3135 errorf(previous_declaration->source_position,
3136 "previous declaration of '%Y' was here", symbol);
3139 return previous_declaration;
3141 } else if (is_function_definition) {
3142 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3143 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3144 warningf(declaration->source_position,
3145 "no previous prototype for '%#T'", orig_type, symbol);
3146 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3147 warningf(declaration->source_position,
3148 "no previous declaration for '%#T'", orig_type,
3152 } else if (warning.missing_declarations &&
3153 scope == global_scope &&
3154 !is_type_function(type) && (
3155 declaration->storage_class == STORAGE_CLASS_NONE ||
3156 declaration->storage_class == STORAGE_CLASS_THREAD
3158 warningf(declaration->source_position,
3159 "no previous declaration for '%#T'", orig_type, symbol);
3162 assert(declaration->parent_scope == NULL);
3163 assert(scope != NULL);
3165 declaration->parent_scope = scope;
3167 environment_push(declaration);
3168 return append_declaration(declaration);
3171 static declaration_t *record_declaration(declaration_t *declaration)
3173 return internal_record_declaration(declaration, false);
3176 static declaration_t *record_function_definition(declaration_t *declaration)
3178 return internal_record_declaration(declaration, true);
3181 static void parser_error_multiple_definition(declaration_t *declaration,
3182 const source_position_t source_position)
3184 errorf(source_position, "multiple definition of symbol '%Y'",
3185 declaration->symbol);
3186 errorf(declaration->source_position,
3187 "this is the location of the previous definition.");
3190 static bool is_declaration_specifier(const token_t *token,
3191 bool only_type_specifiers)
3193 switch(token->type) {
3197 return is_typedef_symbol(token->v.symbol);
3199 case T___extension__:
3202 return !only_type_specifiers;
3209 static void parse_init_declarator_rest(declaration_t *declaration)
3213 type_t *orig_type = declaration->type;
3214 type_t *type = skip_typeref(orig_type);
3216 if(declaration->init.initializer != NULL) {
3217 parser_error_multiple_definition(declaration, token.source_position);
3220 bool must_be_constant = false;
3221 if(declaration->storage_class == STORAGE_CLASS_STATIC
3222 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3223 || declaration->parent_scope == global_scope) {
3224 must_be_constant = true;
3227 parse_initializer_env_t env;
3228 env.type = orig_type;
3229 env.must_be_constant = must_be_constant;
3230 env.declaration = declaration;
3232 initializer_t *initializer = parse_initializer(&env);
3234 if(env.type != orig_type) {
3235 orig_type = env.type;
3236 type = skip_typeref(orig_type);
3237 declaration->type = env.type;
3240 if(is_type_function(type)) {
3241 errorf(declaration->source_position,
3242 "initializers not allowed for function types at declator '%Y' (type '%T')",
3243 declaration->symbol, orig_type);
3245 declaration->init.initializer = initializer;
3249 /* parse rest of a declaration without any declarator */
3250 static void parse_anonymous_declaration_rest(
3251 const declaration_specifiers_t *specifiers,
3252 parsed_declaration_func finished_declaration)
3256 declaration_t *const declaration = allocate_declaration_zero();
3257 declaration->type = specifiers->type;
3258 declaration->declared_storage_class = specifiers->declared_storage_class;
3259 declaration->source_position = specifiers->source_position;
3260 declaration->modifiers = specifiers->decl_modifiers;
3262 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3263 warningf(declaration->source_position, "useless storage class in empty declaration");
3265 declaration->storage_class = STORAGE_CLASS_NONE;
3267 type_t *type = declaration->type;
3268 switch (type->kind) {
3269 case TYPE_COMPOUND_STRUCT:
3270 case TYPE_COMPOUND_UNION: {
3271 if (type->compound.declaration->symbol == NULL) {
3272 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3281 warningf(declaration->source_position, "empty declaration");
3285 finished_declaration(declaration);
3288 static void parse_declaration_rest(declaration_t *ndeclaration,
3289 const declaration_specifiers_t *specifiers,
3290 parsed_declaration_func finished_declaration)
3292 add_anchor_token(';');
3293 add_anchor_token('=');
3294 add_anchor_token(',');
3296 declaration_t *declaration = finished_declaration(ndeclaration);
3298 type_t *orig_type = declaration->type;
3299 type_t *type = skip_typeref(orig_type);
3301 if (type->kind != TYPE_FUNCTION &&
3302 declaration->is_inline &&
3303 is_type_valid(type)) {
3304 warningf(declaration->source_position,
3305 "variable '%Y' declared 'inline'\n", declaration->symbol);
3308 if(token.type == '=') {
3309 parse_init_declarator_rest(declaration);
3312 if(token.type != ',')
3316 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3321 rem_anchor_token(';');
3322 rem_anchor_token('=');
3323 rem_anchor_token(',');
3326 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3328 symbol_t *symbol = declaration->symbol;
3329 if(symbol == NULL) {
3330 errorf(HERE, "anonymous declaration not valid as function parameter");
3333 namespace_t namespc = (namespace_t) declaration->namespc;
3334 if(namespc != NAMESPACE_NORMAL) {
3335 return record_declaration(declaration);
3338 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3339 if(previous_declaration == NULL ||
3340 previous_declaration->parent_scope != scope) {
3341 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3346 if(previous_declaration->type == NULL) {
3347 previous_declaration->type = declaration->type;
3348 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3349 previous_declaration->storage_class = declaration->storage_class;
3350 previous_declaration->parent_scope = scope;
3351 return previous_declaration;
3353 return record_declaration(declaration);
3357 static void parse_declaration(parsed_declaration_func finished_declaration)
3359 declaration_specifiers_t specifiers;
3360 memset(&specifiers, 0, sizeof(specifiers));
3361 parse_declaration_specifiers(&specifiers);
3363 if(token.type == ';') {
3364 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3366 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3367 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3371 static void parse_kr_declaration_list(declaration_t *declaration)
3373 type_t *type = skip_typeref(declaration->type);
3374 if(!is_type_function(type))
3377 if(!type->function.kr_style_parameters)
3380 /* push function parameters */
3381 int top = environment_top();
3382 scope_t *last_scope = scope;
3383 set_scope(&declaration->scope);
3385 declaration_t *parameter = declaration->scope.declarations;
3386 for( ; parameter != NULL; parameter = parameter->next) {
3387 assert(parameter->parent_scope == NULL);
3388 parameter->parent_scope = scope;
3389 environment_push(parameter);
3392 /* parse declaration list */
3393 while(is_declaration_specifier(&token, false)) {
3394 parse_declaration(finished_kr_declaration);
3397 /* pop function parameters */
3398 assert(scope == &declaration->scope);
3399 set_scope(last_scope);
3400 environment_pop_to(top);
3402 /* update function type */
3403 type_t *new_type = duplicate_type(type);
3404 new_type->function.kr_style_parameters = false;
3406 function_parameter_t *parameters = NULL;
3407 function_parameter_t *last_parameter = NULL;
3409 declaration_t *parameter_declaration = declaration->scope.declarations;
3410 for( ; parameter_declaration != NULL;
3411 parameter_declaration = parameter_declaration->next) {
3412 type_t *parameter_type = parameter_declaration->type;
3413 if(parameter_type == NULL) {
3415 errorf(HERE, "no type specified for function parameter '%Y'",
3416 parameter_declaration->symbol);
3418 if (warning.implicit_int) {
3419 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3420 parameter_declaration->symbol);
3422 parameter_type = type_int;
3423 parameter_declaration->type = parameter_type;
3427 semantic_parameter(parameter_declaration);
3428 parameter_type = parameter_declaration->type;
3430 function_parameter_t *function_parameter
3431 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3432 memset(function_parameter, 0, sizeof(function_parameter[0]));
3434 function_parameter->type = parameter_type;
3435 if(last_parameter != NULL) {
3436 last_parameter->next = function_parameter;
3438 parameters = function_parameter;
3440 last_parameter = function_parameter;
3442 new_type->function.parameters = parameters;
3444 type = typehash_insert(new_type);
3445 if(type != new_type) {
3446 obstack_free(type_obst, new_type);
3449 declaration->type = type;
3452 static bool first_err = true;
3455 * When called with first_err set, prints the name of the current function,
3458 static void print_in_function(void) {
3461 diagnosticf("%s: In function '%Y':\n",
3462 current_function->source_position.input_name,
3463 current_function->symbol);
3468 * Check if all labels are defined in the current function.
3469 * Check if all labels are used in the current function.
3471 static void check_labels(void)
3473 for (const goto_statement_t *goto_statement = goto_first;
3474 goto_statement != NULL;
3475 goto_statement = goto_statement->next) {
3476 declaration_t *label = goto_statement->label;
3479 if (label->source_position.input_name == NULL) {
3480 print_in_function();
3481 errorf(goto_statement->base.source_position,
3482 "label '%Y' used but not defined", label->symbol);
3485 goto_first = goto_last = NULL;
3487 if (warning.unused_label) {
3488 for (const label_statement_t *label_statement = label_first;
3489 label_statement != NULL;
3490 label_statement = label_statement->next) {
3491 const declaration_t *label = label_statement->label;
3493 if (! label->used) {
3494 print_in_function();
3495 warningf(label_statement->base.source_position,
3496 "label '%Y' defined but not used", label->symbol);
3500 label_first = label_last = NULL;
3504 * Check declarations of current_function for unused entities.
3506 static void check_declarations(void)
3508 if (warning.unused_parameter) {
3509 const scope_t *scope = ¤t_function->scope;
3511 const declaration_t *parameter = scope->declarations;
3512 for (; parameter != NULL; parameter = parameter->next) {
3513 if (! parameter->used) {
3514 print_in_function();
3515 warningf(parameter->source_position,
3516 "unused parameter '%Y'", parameter->symbol);
3520 if (warning.unused_variable) {
3524 static void parse_external_declaration(void)
3526 /* function-definitions and declarations both start with declaration
3528 declaration_specifiers_t specifiers;
3529 memset(&specifiers, 0, sizeof(specifiers));
3531 add_anchor_token(';');
3532 parse_declaration_specifiers(&specifiers);
3533 rem_anchor_token(';');
3535 /* must be a declaration */
3536 if(token.type == ';') {
3537 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3541 add_anchor_token(',');
3542 add_anchor_token('=');
3543 rem_anchor_token(';');
3545 /* declarator is common to both function-definitions and declarations */
3546 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3548 rem_anchor_token(',');
3549 rem_anchor_token('=');
3550 rem_anchor_token(';');
3552 /* must be a declaration */
3553 if(token.type == ',' || token.type == '=' || token.type == ';') {
3554 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3558 /* must be a function definition */
3559 parse_kr_declaration_list(ndeclaration);
3561 if(token.type != '{') {
3562 parse_error_expected("while parsing function definition", '{', 0);
3563 eat_until_matching_token(';');
3567 type_t *type = ndeclaration->type;
3569 /* note that we don't skip typerefs: the standard doesn't allow them here
3570 * (so we can't use is_type_function here) */
3571 if(type->kind != TYPE_FUNCTION) {
3572 if (is_type_valid(type)) {
3573 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3574 type, ndeclaration->symbol);
3580 /* § 6.7.5.3 (14) a function definition with () means no
3581 * parameters (and not unspecified parameters) */
3582 if(type->function.unspecified_parameters) {
3583 type_t *duplicate = duplicate_type(type);
3584 duplicate->function.unspecified_parameters = false;
3586 type = typehash_insert(duplicate);
3587 if(type != duplicate) {
3588 obstack_free(type_obst, duplicate);
3590 ndeclaration->type = type;
3593 declaration_t *const declaration = record_function_definition(ndeclaration);
3594 if(ndeclaration != declaration) {
3595 declaration->scope = ndeclaration->scope;
3597 type = skip_typeref(declaration->type);
3599 /* push function parameters and switch scope */
3600 int top = environment_top();
3601 scope_t *last_scope = scope;
3602 set_scope(&declaration->scope);
3604 declaration_t *parameter = declaration->scope.declarations;
3605 for( ; parameter != NULL; parameter = parameter->next) {
3606 if(parameter->parent_scope == &ndeclaration->scope) {
3607 parameter->parent_scope = scope;
3609 assert(parameter->parent_scope == NULL
3610 || parameter->parent_scope == scope);
3611 parameter->parent_scope = scope;
3612 environment_push(parameter);
3615 if(declaration->init.statement != NULL) {
3616 parser_error_multiple_definition(declaration, token.source_position);
3618 goto end_of_parse_external_declaration;
3620 /* parse function body */
3621 int label_stack_top = label_top();
3622 declaration_t *old_current_function = current_function;
3623 current_function = declaration;
3625 declaration->init.statement = parse_compound_statement();
3628 check_declarations();
3630 assert(current_function == declaration);
3631 current_function = old_current_function;
3632 label_pop_to(label_stack_top);
3635 end_of_parse_external_declaration:
3636 assert(scope == &declaration->scope);
3637 set_scope(last_scope);
3638 environment_pop_to(top);
3641 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3642 source_position_t source_position)
3644 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3645 type->bitfield.base = base;
3646 type->bitfield.size = size;
3651 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3654 declaration_t *iter = compound_declaration->scope.declarations;
3655 for( ; iter != NULL; iter = iter->next) {
3656 if(iter->namespc != NAMESPACE_NORMAL)
3659 if(iter->symbol == NULL) {
3660 type_t *type = skip_typeref(iter->type);
3661 if(is_type_compound(type)) {
3662 declaration_t *result
3663 = find_compound_entry(type->compound.declaration, symbol);
3670 if(iter->symbol == symbol) {
3678 static void parse_compound_declarators(declaration_t *struct_declaration,
3679 const declaration_specifiers_t *specifiers)
3681 declaration_t *last_declaration = struct_declaration->scope.declarations;
3682 if(last_declaration != NULL) {
3683 while(last_declaration->next != NULL) {
3684 last_declaration = last_declaration->next;
3689 declaration_t *declaration;
3691 if(token.type == ':') {
3692 source_position_t source_position = HERE;
3695 type_t *base_type = specifiers->type;
3696 expression_t *size = parse_constant_expression();
3698 if(!is_type_integer(skip_typeref(base_type))) {
3699 errorf(HERE, "bitfield base type '%T' is not an integer type",
3703 type_t *type = make_bitfield_type(base_type, size, source_position);
3705 declaration = allocate_declaration_zero();
3706 declaration->namespc = NAMESPACE_NORMAL;
3707 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3708 declaration->storage_class = STORAGE_CLASS_NONE;
3709 declaration->source_position = source_position;
3710 declaration->modifiers = specifiers->decl_modifiers;
3711 declaration->type = type;
3713 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3715 type_t *orig_type = declaration->type;
3716 type_t *type = skip_typeref(orig_type);
3718 if(token.type == ':') {
3719 source_position_t source_position = HERE;
3721 expression_t *size = parse_constant_expression();
3723 if(!is_type_integer(type)) {
3724 errorf(HERE, "bitfield base type '%T' is not an "
3725 "integer type", orig_type);
3728 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3729 declaration->type = bitfield_type;
3731 /* TODO we ignore arrays for now... what is missing is a check
3732 * that they're at the end of the struct */
3733 if(is_type_incomplete(type) && !is_type_array(type)) {
3735 "compound member '%Y' has incomplete type '%T'",
3736 declaration->symbol, orig_type);
3737 } else if(is_type_function(type)) {
3738 errorf(HERE, "compound member '%Y' must not have function "
3739 "type '%T'", declaration->symbol, orig_type);
3744 /* make sure we don't define a symbol multiple times */
3745 symbol_t *symbol = declaration->symbol;
3746 if(symbol != NULL) {
3747 declaration_t *prev_decl
3748 = find_compound_entry(struct_declaration, symbol);
3750 if(prev_decl != NULL) {
3751 assert(prev_decl->symbol == symbol);
3752 errorf(declaration->source_position,
3753 "multiple declarations of symbol '%Y'", symbol);
3754 errorf(prev_decl->source_position,
3755 "previous declaration of '%Y' was here", symbol);
3759 /* append declaration */
3760 if(last_declaration != NULL) {
3761 last_declaration->next = declaration;
3763 struct_declaration->scope.declarations = declaration;
3765 last_declaration = declaration;
3767 if(token.type != ',')
3777 static void parse_compound_type_entries(declaration_t *compound_declaration)
3780 add_anchor_token('}');
3782 while(token.type != '}' && token.type != T_EOF) {
3783 declaration_specifiers_t specifiers;
3784 memset(&specifiers, 0, sizeof(specifiers));
3785 parse_declaration_specifiers(&specifiers);
3787 parse_compound_declarators(compound_declaration, &specifiers);
3789 rem_anchor_token('}');
3791 if(token.type == T_EOF) {
3792 errorf(HERE, "EOF while parsing struct");
3797 static type_t *parse_typename(void)
3799 declaration_specifiers_t specifiers;
3800 memset(&specifiers, 0, sizeof(specifiers));
3801 parse_declaration_specifiers(&specifiers);
3802 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3803 /* TODO: improve error message, user does probably not know what a
3804 * storage class is...
3806 errorf(HERE, "typename may not have a storage class");
3809 type_t *result = parse_abstract_declarator(specifiers.type);
3817 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3818 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3819 expression_t *left);
3821 typedef struct expression_parser_function_t expression_parser_function_t;
3822 struct expression_parser_function_t {
3823 unsigned precedence;
3824 parse_expression_function parser;
3825 unsigned infix_precedence;
3826 parse_expression_infix_function infix_parser;
3829 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3832 * Creates a new invalid expression.
3834 static expression_t *create_invalid_expression(void)
3836 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3837 expression->base.source_position = token.source_position;
3842 * Prints an error message if an expression was expected but not read
3844 static expression_t *expected_expression_error(void)
3846 /* skip the error message if the error token was read */
3847 if (token.type != T_ERROR) {
3848 errorf(HERE, "expected expression, got token '%K'", &token);
3852 return create_invalid_expression();
3856 * Parse a string constant.
3858 static expression_t *parse_string_const(void)
3861 if (token.type == T_STRING_LITERAL) {
3862 string_t res = token.v.string;
3864 while (token.type == T_STRING_LITERAL) {
3865 res = concat_strings(&res, &token.v.string);
3868 if (token.type != T_WIDE_STRING_LITERAL) {
3869 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3870 /* note: that we use type_char_ptr here, which is already the
3871 * automatic converted type. revert_automatic_type_conversion
3872 * will construct the array type */
3873 cnst->base.type = type_char_ptr;
3874 cnst->string.value = res;
3878 wres = concat_string_wide_string(&res, &token.v.wide_string);
3880 wres = token.v.wide_string;
3885 switch (token.type) {
3886 case T_WIDE_STRING_LITERAL:
3887 wres = concat_wide_strings(&wres, &token.v.wide_string);
3890 case T_STRING_LITERAL:
3891 wres = concat_wide_string_string(&wres, &token.v.string);
3895 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3896 cnst->base.type = type_wchar_t_ptr;
3897 cnst->wide_string.value = wres;
3906 * Parse an integer constant.
3908 static expression_t *parse_int_const(void)
3910 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3911 cnst->base.source_position = HERE;
3912 cnst->base.type = token.datatype;
3913 cnst->conste.v.int_value = token.v.intvalue;
3921 * Parse a character constant.
3923 static expression_t *parse_character_constant(void)
3925 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3927 cnst->base.source_position = HERE;
3928 cnst->base.type = token.datatype;
3929 cnst->conste.v.character = token.v.string;
3931 if (cnst->conste.v.character.size != 1) {
3932 if (warning.multichar && (c_mode & _GNUC)) {
3934 warningf(HERE, "multi-character character constant");
3936 errorf(HERE, "more than 1 characters in character constant");
3945 * Parse a wide character constant.
3947 static expression_t *parse_wide_character_constant(void)
3949 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3951 cnst->base.source_position = HERE;
3952 cnst->base.type = token.datatype;
3953 cnst->conste.v.wide_character = token.v.wide_string;
3955 if (cnst->conste.v.wide_character.size != 1) {
3956 if (warning.multichar && (c_mode & _GNUC)) {
3958 warningf(HERE, "multi-character character constant");
3960 errorf(HERE, "more than 1 characters in character constant");
3969 * Parse a float constant.
3971 static expression_t *parse_float_const(void)
3973 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3974 cnst->base.type = token.datatype;
3975 cnst->conste.v.float_value = token.v.floatvalue;
3982 static declaration_t *create_implicit_function(symbol_t *symbol,
3983 const source_position_t source_position)
3985 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
3986 ntype->function.return_type = type_int;
3987 ntype->function.unspecified_parameters = true;
3989 type_t *type = typehash_insert(ntype);
3994 declaration_t *const declaration = allocate_declaration_zero();
3995 declaration->storage_class = STORAGE_CLASS_EXTERN;
3996 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
3997 declaration->type = type;
3998 declaration->symbol = symbol;
3999 declaration->source_position = source_position;
4000 declaration->parent_scope = global_scope;
4002 scope_t *old_scope = scope;
4003 set_scope(global_scope);
4005 environment_push(declaration);
4006 /* prepends the declaration to the global declarations list */
4007 declaration->next = scope->declarations;
4008 scope->declarations = declaration;
4010 assert(scope == global_scope);
4011 set_scope(old_scope);
4017 * Creates a return_type (func)(argument_type) function type if not
4020 * @param return_type the return type
4021 * @param argument_type the argument type
4023 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4025 function_parameter_t *parameter
4026 = obstack_alloc(type_obst, sizeof(parameter[0]));
4027 memset(parameter, 0, sizeof(parameter[0]));
4028 parameter->type = argument_type;
4030 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4031 type->function.return_type = return_type;
4032 type->function.parameters = parameter;
4034 type_t *result = typehash_insert(type);
4035 if(result != type) {
4043 * Creates a function type for some function like builtins.
4045 * @param symbol the symbol describing the builtin
4047 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4049 switch(symbol->ID) {
4050 case T___builtin_alloca:
4051 return make_function_1_type(type_void_ptr, type_size_t);
4052 case T___builtin_nan:
4053 return make_function_1_type(type_double, type_char_ptr);
4054 case T___builtin_nanf:
4055 return make_function_1_type(type_float, type_char_ptr);
4056 case T___builtin_nand:
4057 return make_function_1_type(type_long_double, type_char_ptr);
4058 case T___builtin_va_end:
4059 return make_function_1_type(type_void, type_valist);
4061 panic("not implemented builtin symbol found");
4066 * Performs automatic type cast as described in § 6.3.2.1.
4068 * @param orig_type the original type
4070 static type_t *automatic_type_conversion(type_t *orig_type)
4072 type_t *type = skip_typeref(orig_type);
4073 if(is_type_array(type)) {
4074 array_type_t *array_type = &type->array;
4075 type_t *element_type = array_type->element_type;
4076 unsigned qualifiers = array_type->type.qualifiers;
4078 return make_pointer_type(element_type, qualifiers);
4081 if(is_type_function(type)) {
4082 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4089 * reverts the automatic casts of array to pointer types and function
4090 * to function-pointer types as defined § 6.3.2.1
4092 type_t *revert_automatic_type_conversion(const expression_t *expression)
4094 switch (expression->kind) {
4095 case EXPR_REFERENCE: return expression->reference.declaration->type;
4096 case EXPR_SELECT: return expression->select.compound_entry->type;
4098 case EXPR_UNARY_DEREFERENCE: {
4099 const expression_t *const value = expression->unary.value;
4100 type_t *const type = skip_typeref(value->base.type);
4101 assert(is_type_pointer(type));
4102 return type->pointer.points_to;
4105 case EXPR_BUILTIN_SYMBOL:
4106 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4108 case EXPR_ARRAY_ACCESS: {
4109 const expression_t *array_ref = expression->array_access.array_ref;
4110 type_t *type_left = skip_typeref(array_ref->base.type);
4111 if (!is_type_valid(type_left))
4113 assert(is_type_pointer(type_left));
4114 return type_left->pointer.points_to;
4117 case EXPR_STRING_LITERAL: {
4118 size_t size = expression->string.value.size;
4119 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4122 case EXPR_WIDE_STRING_LITERAL: {
4123 size_t size = expression->wide_string.value.size;
4124 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4127 case EXPR_COMPOUND_LITERAL:
4128 return expression->compound_literal.type;
4133 return expression->base.type;
4136 static expression_t *parse_reference(void)
4138 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4140 reference_expression_t *ref = &expression->reference;
4141 ref->symbol = token.v.symbol;
4143 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4145 source_position_t source_position = token.source_position;
4148 if(declaration == NULL) {
4149 if (! strict_mode && token.type == '(') {
4150 /* an implicitly defined function */
4151 if (warning.implicit_function_declaration) {
4152 warningf(HERE, "implicit declaration of function '%Y'",
4156 declaration = create_implicit_function(ref->symbol,
4159 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4160 return create_invalid_expression();
4164 type_t *type = declaration->type;
4166 /* we always do the auto-type conversions; the & and sizeof parser contains
4167 * code to revert this! */
4168 type = automatic_type_conversion(type);
4170 ref->declaration = declaration;
4171 ref->base.type = type;
4173 /* this declaration is used */
4174 declaration->used = true;
4179 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4183 /* TODO check if explicit cast is allowed and issue warnings/errors */
4186 static expression_t *parse_compound_literal(type_t *type)
4188 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4190 parse_initializer_env_t env;
4192 env.declaration = NULL;
4193 env.must_be_constant = false;
4194 initializer_t *initializer = parse_initializer(&env);
4197 expression->compound_literal.initializer = initializer;
4198 expression->compound_literal.type = type;
4199 expression->base.type = automatic_type_conversion(type);
4205 * Parse a cast expression.
4207 static expression_t *parse_cast(void)
4209 source_position_t source_position = token.source_position;
4211 type_t *type = parse_typename();
4213 /* matching add_anchor_token() is at call site */
4214 rem_anchor_token(')');
4217 if(token.type == '{') {
4218 return parse_compound_literal(type);
4221 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4222 cast->base.source_position = source_position;
4224 expression_t *value = parse_sub_expression(20);
4226 check_cast_allowed(value, type);
4228 cast->base.type = type;
4229 cast->unary.value = value;
4233 return create_invalid_expression();
4237 * Parse a statement expression.
4239 static expression_t *parse_statement_expression(void)
4241 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4243 statement_t *statement = parse_compound_statement();
4244 expression->statement.statement = statement;
4245 expression->base.source_position = statement->base.source_position;
4247 /* find last statement and use its type */
4248 type_t *type = type_void;
4249 const statement_t *stmt = statement->compound.statements;
4251 while (stmt->base.next != NULL)
4252 stmt = stmt->base.next;
4254 if (stmt->kind == STATEMENT_EXPRESSION) {
4255 type = stmt->expression.expression->base.type;
4258 warningf(expression->base.source_position, "empty statement expression ({})");
4260 expression->base.type = type;
4266 return create_invalid_expression();
4270 * Parse a braced expression.
4272 static expression_t *parse_brace_expression(void)
4275 add_anchor_token(')');
4277 switch(token.type) {
4279 /* gcc extension: a statement expression */
4280 return parse_statement_expression();
4284 return parse_cast();
4286 if(is_typedef_symbol(token.v.symbol)) {
4287 return parse_cast();
4291 expression_t *result = parse_expression();
4292 rem_anchor_token(')');
4297 return create_invalid_expression();
4300 static expression_t *parse_function_keyword(void)
4305 if (current_function == NULL) {
4306 errorf(HERE, "'__func__' used outside of a function");
4309 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4310 expression->base.type = type_char_ptr;
4315 static expression_t *parse_pretty_function_keyword(void)
4317 eat(T___PRETTY_FUNCTION__);
4320 if (current_function == NULL) {
4321 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4324 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4325 expression->base.type = type_char_ptr;
4330 static designator_t *parse_designator(void)
4332 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4333 result->source_position = HERE;
4335 if(token.type != T_IDENTIFIER) {
4336 parse_error_expected("while parsing member designator",
4340 result->symbol = token.v.symbol;
4343 designator_t *last_designator = result;
4345 if(token.type == '.') {
4347 if(token.type != T_IDENTIFIER) {
4348 parse_error_expected("while parsing member designator",
4352 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4353 designator->source_position = HERE;
4354 designator->symbol = token.v.symbol;
4357 last_designator->next = designator;
4358 last_designator = designator;
4361 if(token.type == '[') {
4363 add_anchor_token(']');
4364 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4365 designator->source_position = HERE;
4366 designator->array_index = parse_expression();
4367 rem_anchor_token(']');
4369 if(designator->array_index == NULL) {
4373 last_designator->next = designator;
4374 last_designator = designator;
4386 * Parse the __builtin_offsetof() expression.
4388 static expression_t *parse_offsetof(void)
4390 eat(T___builtin_offsetof);
4392 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4393 expression->base.type = type_size_t;
4396 add_anchor_token(',');
4397 type_t *type = parse_typename();
4398 rem_anchor_token(',');
4400 add_anchor_token(')');
4401 designator_t *designator = parse_designator();
4402 rem_anchor_token(')');
4405 expression->offsetofe.type = type;
4406 expression->offsetofe.designator = designator;
4409 memset(&path, 0, sizeof(path));
4410 path.top_type = type;
4411 path.path = NEW_ARR_F(type_path_entry_t, 0);
4413 descend_into_subtype(&path);
4415 if(!walk_designator(&path, designator, true)) {
4416 return create_invalid_expression();
4419 DEL_ARR_F(path.path);
4423 return create_invalid_expression();
4427 * Parses a _builtin_va_start() expression.
4429 static expression_t *parse_va_start(void)
4431 eat(T___builtin_va_start);
4433 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4436 add_anchor_token(',');
4437 expression->va_starte.ap = parse_assignment_expression();
4438 rem_anchor_token(',');
4440 expression_t *const expr = parse_assignment_expression();
4441 if (expr->kind == EXPR_REFERENCE) {
4442 declaration_t *const decl = expr->reference.declaration;
4444 return create_invalid_expression();
4445 if (decl->parent_scope == ¤t_function->scope &&
4446 decl->next == NULL) {
4447 expression->va_starte.parameter = decl;
4452 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4454 return create_invalid_expression();
4458 * Parses a _builtin_va_arg() expression.
4460 static expression_t *parse_va_arg(void)
4462 eat(T___builtin_va_arg);
4464 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4467 expression->va_arge.ap = parse_assignment_expression();
4469 expression->base.type = parse_typename();
4474 return create_invalid_expression();
4477 static expression_t *parse_builtin_symbol(void)
4479 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4481 symbol_t *symbol = token.v.symbol;
4483 expression->builtin_symbol.symbol = symbol;
4486 type_t *type = get_builtin_symbol_type(symbol);
4487 type = automatic_type_conversion(type);
4489 expression->base.type = type;
4494 * Parses a __builtin_constant() expression.
4496 static expression_t *parse_builtin_constant(void)
4498 eat(T___builtin_constant_p);
4500 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4503 add_anchor_token(')');
4504 expression->builtin_constant.value = parse_assignment_expression();
4505 rem_anchor_token(')');
4507 expression->base.type = type_int;
4511 return create_invalid_expression();
4515 * Parses a __builtin_prefetch() expression.
4517 static expression_t *parse_builtin_prefetch(void)
4519 eat(T___builtin_prefetch);
4521 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4524 add_anchor_token(')');
4525 expression->builtin_prefetch.adr = parse_assignment_expression();
4526 if (token.type == ',') {
4528 expression->builtin_prefetch.rw = parse_assignment_expression();
4530 if (token.type == ',') {
4532 expression->builtin_prefetch.locality = parse_assignment_expression();
4534 rem_anchor_token(')');
4536 expression->base.type = type_void;
4540 return create_invalid_expression();
4544 * Parses a __builtin_is_*() compare expression.
4546 static expression_t *parse_compare_builtin(void)
4548 expression_t *expression;
4550 switch(token.type) {
4551 case T___builtin_isgreater:
4552 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4554 case T___builtin_isgreaterequal:
4555 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4557 case T___builtin_isless:
4558 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4560 case T___builtin_islessequal:
4561 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4563 case T___builtin_islessgreater:
4564 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4566 case T___builtin_isunordered:
4567 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4570 panic("invalid compare builtin found");
4573 expression->base.source_position = HERE;
4577 expression->binary.left = parse_assignment_expression();
4579 expression->binary.right = parse_assignment_expression();
4582 type_t *const orig_type_left = expression->binary.left->base.type;
4583 type_t *const orig_type_right = expression->binary.right->base.type;
4585 type_t *const type_left = skip_typeref(orig_type_left);
4586 type_t *const type_right = skip_typeref(orig_type_right);
4587 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4588 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4589 type_error_incompatible("invalid operands in comparison",
4590 expression->base.source_position, orig_type_left, orig_type_right);
4593 semantic_comparison(&expression->binary);
4598 return create_invalid_expression();
4602 * Parses a __builtin_expect() expression.
4604 static expression_t *parse_builtin_expect(void)
4606 eat(T___builtin_expect);
4608 expression_t *expression
4609 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4612 expression->binary.left = parse_assignment_expression();
4614 expression->binary.right = parse_constant_expression();
4617 expression->base.type = expression->binary.left->base.type;
4621 return create_invalid_expression();
4625 * Parses a MS assume() expression.
4627 static expression_t *parse_assume(void) {
4630 expression_t *expression
4631 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4634 add_anchor_token(')');
4635 expression->unary.value = parse_assignment_expression();
4636 rem_anchor_token(')');
4639 expression->base.type = type_void;
4642 return create_invalid_expression();
4646 * Parses a primary expression.
4648 static expression_t *parse_primary_expression(void)
4650 switch (token.type) {
4651 case T_INTEGER: return parse_int_const();
4652 case T_CHARACTER_CONSTANT: return parse_character_constant();
4653 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4654 case T_FLOATINGPOINT: return parse_float_const();
4655 case T_STRING_LITERAL:
4656 case T_WIDE_STRING_LITERAL: return parse_string_const();
4657 case T_IDENTIFIER: return parse_reference();
4658 case T___FUNCTION__:
4659 case T___func__: return parse_function_keyword();
4660 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4661 case T___builtin_offsetof: return parse_offsetof();
4662 case T___builtin_va_start: return parse_va_start();
4663 case T___builtin_va_arg: return parse_va_arg();
4664 case T___builtin_expect: return parse_builtin_expect();
4665 case T___builtin_alloca:
4666 case T___builtin_nan:
4667 case T___builtin_nand:
4668 case T___builtin_nanf:
4669 case T___builtin_va_end: return parse_builtin_symbol();
4670 case T___builtin_isgreater:
4671 case T___builtin_isgreaterequal:
4672 case T___builtin_isless:
4673 case T___builtin_islessequal:
4674 case T___builtin_islessgreater:
4675 case T___builtin_isunordered: return parse_compare_builtin();
4676 case T___builtin_constant_p: return parse_builtin_constant();
4677 case T___builtin_prefetch: return parse_builtin_prefetch();
4678 case T_assume: return parse_assume();
4680 case '(': return parse_brace_expression();
4683 errorf(HERE, "unexpected token %K, expected an expression", &token);
4684 return create_invalid_expression();
4688 * Check if the expression has the character type and issue a warning then.
4690 static void check_for_char_index_type(const expression_t *expression) {
4691 type_t *const type = expression->base.type;
4692 const type_t *const base_type = skip_typeref(type);
4694 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4695 warning.char_subscripts) {
4696 warningf(expression->base.source_position,
4697 "array subscript has type '%T'", type);
4701 static expression_t *parse_array_expression(unsigned precedence,
4707 add_anchor_token(']');
4709 expression_t *inside = parse_expression();
4711 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4713 array_access_expression_t *array_access = &expression->array_access;
4715 type_t *const orig_type_left = left->base.type;
4716 type_t *const orig_type_inside = inside->base.type;
4718 type_t *const type_left = skip_typeref(orig_type_left);
4719 type_t *const type_inside = skip_typeref(orig_type_inside);
4721 type_t *return_type;
4722 if (is_type_pointer(type_left)) {
4723 return_type = type_left->pointer.points_to;
4724 array_access->array_ref = left;
4725 array_access->index = inside;
4726 check_for_char_index_type(inside);
4727 } else if (is_type_pointer(type_inside)) {
4728 return_type = type_inside->pointer.points_to;
4729 array_access->array_ref = inside;
4730 array_access->index = left;
4731 array_access->flipped = true;
4732 check_for_char_index_type(left);
4734 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4736 "array access on object with non-pointer types '%T', '%T'",
4737 orig_type_left, orig_type_inside);
4739 return_type = type_error_type;
4740 array_access->array_ref = create_invalid_expression();
4743 rem_anchor_token(']');
4744 if(token.type != ']') {
4745 parse_error_expected("Problem while parsing array access", ']', 0);
4750 return_type = automatic_type_conversion(return_type);
4751 expression->base.type = return_type;
4756 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4758 expression_t *tp_expression = allocate_expression_zero(kind);
4759 tp_expression->base.type = type_size_t;
4761 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4763 add_anchor_token(')');
4764 tp_expression->typeprop.type = parse_typename();
4765 rem_anchor_token(')');
4768 expression_t *expression = parse_sub_expression(precedence);
4769 expression->base.type = revert_automatic_type_conversion(expression);
4771 tp_expression->typeprop.type = expression->base.type;
4772 tp_expression->typeprop.tp_expression = expression;
4775 return tp_expression;
4777 return create_invalid_expression();
4780 static expression_t *parse_sizeof(unsigned precedence)
4783 return parse_typeprop(EXPR_SIZEOF, precedence);
4786 static expression_t *parse_alignof(unsigned precedence)
4789 return parse_typeprop(EXPR_SIZEOF, precedence);
4792 static expression_t *parse_select_expression(unsigned precedence,
4793 expression_t *compound)
4796 assert(token.type == '.' || token.type == T_MINUSGREATER);
4798 bool is_pointer = (token.type == T_MINUSGREATER);
4801 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4802 select->select.compound = compound;
4804 if(token.type != T_IDENTIFIER) {
4805 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4808 symbol_t *symbol = token.v.symbol;
4809 select->select.symbol = symbol;
4812 type_t *const orig_type = compound->base.type;
4813 type_t *const type = skip_typeref(orig_type);
4815 type_t *type_left = type;
4817 if (!is_type_pointer(type)) {
4818 if (is_type_valid(type)) {
4819 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4821 return create_invalid_expression();
4823 type_left = type->pointer.points_to;
4825 type_left = skip_typeref(type_left);
4827 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4828 type_left->kind != TYPE_COMPOUND_UNION) {
4829 if (is_type_valid(type_left)) {
4830 errorf(HERE, "request for member '%Y' in something not a struct or "
4831 "union, but '%T'", symbol, type_left);
4833 return create_invalid_expression();
4836 declaration_t *const declaration = type_left->compound.declaration;
4838 if(!declaration->init.is_defined) {
4839 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4841 return create_invalid_expression();
4844 declaration_t *iter = find_compound_entry(declaration, symbol);
4846 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4847 return create_invalid_expression();
4850 /* we always do the auto-type conversions; the & and sizeof parser contains
4851 * code to revert this! */
4852 type_t *expression_type = automatic_type_conversion(iter->type);
4854 select->select.compound_entry = iter;
4855 select->base.type = expression_type;
4857 if(expression_type->kind == TYPE_BITFIELD) {
4858 expression_t *extract
4859 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4860 extract->unary.value = select;
4861 extract->base.type = expression_type->bitfield.base;
4870 * Parse a call expression, ie. expression '( ... )'.
4872 * @param expression the function address
4874 static expression_t *parse_call_expression(unsigned precedence,
4875 expression_t *expression)
4878 expression_t *result = allocate_expression_zero(EXPR_CALL);
4880 call_expression_t *call = &result->call;
4881 call->function = expression;
4883 type_t *const orig_type = expression->base.type;
4884 type_t *const type = skip_typeref(orig_type);
4886 function_type_t *function_type = NULL;
4887 if (is_type_pointer(type)) {
4888 type_t *const to_type = skip_typeref(type->pointer.points_to);
4890 if (is_type_function(to_type)) {
4891 function_type = &to_type->function;
4892 call->base.type = function_type->return_type;
4896 if (function_type == NULL && is_type_valid(type)) {
4897 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4900 /* parse arguments */
4902 add_anchor_token(')');
4903 add_anchor_token(',');
4905 if(token.type != ')') {
4906 call_argument_t *last_argument = NULL;
4909 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4911 argument->expression = parse_assignment_expression();
4912 if(last_argument == NULL) {
4913 call->arguments = argument;
4915 last_argument->next = argument;
4917 last_argument = argument;
4919 if(token.type != ',')
4924 rem_anchor_token(',');
4925 rem_anchor_token(')');
4928 if(function_type != NULL) {
4929 function_parameter_t *parameter = function_type->parameters;
4930 call_argument_t *argument = call->arguments;
4931 for( ; parameter != NULL && argument != NULL;
4932 parameter = parameter->next, argument = argument->next) {
4933 type_t *expected_type = parameter->type;
4934 /* TODO report scope in error messages */
4935 expression_t *const arg_expr = argument->expression;
4936 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4937 if (res_type == NULL) {
4938 /* TODO improve error message */
4939 errorf(arg_expr->base.source_position,
4940 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4941 arg_expr, arg_expr->base.type, expected_type);
4943 argument->expression = create_implicit_cast(argument->expression, expected_type);
4946 /* too few parameters */
4947 if(parameter != NULL) {
4948 errorf(HERE, "too few arguments to function '%E'", expression);
4949 } else if(argument != NULL) {
4950 /* too many parameters */
4951 if(!function_type->variadic
4952 && !function_type->unspecified_parameters) {
4953 errorf(HERE, "too many arguments to function '%E'", expression);
4955 /* do default promotion */
4956 for( ; argument != NULL; argument = argument->next) {
4957 type_t *type = argument->expression->base.type;
4959 type = skip_typeref(type);
4960 if(is_type_integer(type)) {
4961 type = promote_integer(type);
4962 } else if(type == type_float) {
4966 argument->expression
4967 = create_implicit_cast(argument->expression, type);
4970 check_format(&result->call);
4973 check_format(&result->call);
4979 return create_invalid_expression();
4982 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4984 static bool same_compound_type(const type_t *type1, const type_t *type2)
4987 is_type_compound(type1) &&
4988 type1->kind == type2->kind &&
4989 type1->compound.declaration == type2->compound.declaration;
4993 * Parse a conditional expression, ie. 'expression ? ... : ...'.
4995 * @param expression the conditional expression
4997 static expression_t *parse_conditional_expression(unsigned precedence,
4998 expression_t *expression)
5001 add_anchor_token(':');
5003 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5005 conditional_expression_t *conditional = &result->conditional;
5006 conditional->condition = expression;
5009 type_t *const condition_type_orig = expression->base.type;
5010 type_t *const condition_type = skip_typeref(condition_type_orig);
5011 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5012 type_error("expected a scalar type in conditional condition",
5013 expression->base.source_position, condition_type_orig);
5016 expression_t *true_expression = parse_expression();
5017 rem_anchor_token(':');
5019 expression_t *false_expression = parse_sub_expression(precedence);
5021 type_t *const orig_true_type = true_expression->base.type;
5022 type_t *const orig_false_type = false_expression->base.type;
5023 type_t *const true_type = skip_typeref(orig_true_type);
5024 type_t *const false_type = skip_typeref(orig_false_type);
5027 type_t *result_type;
5028 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
5029 result_type = semantic_arithmetic(true_type, false_type);
5031 true_expression = create_implicit_cast(true_expression, result_type);
5032 false_expression = create_implicit_cast(false_expression, result_type);
5034 conditional->true_expression = true_expression;
5035 conditional->false_expression = false_expression;
5036 conditional->base.type = result_type;
5037 } else if (same_compound_type(true_type, false_type) || (
5038 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
5039 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
5041 /* just take 1 of the 2 types */
5042 result_type = true_type;
5043 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
5044 && pointers_compatible(true_type, false_type)) {
5046 result_type = true_type;
5047 } else if (is_type_pointer(true_type)
5048 && is_null_pointer_constant(false_expression)) {
5049 result_type = true_type;
5050 } else if (is_type_pointer(false_type)
5051 && is_null_pointer_constant(true_expression)) {
5052 result_type = false_type;
5054 /* TODO: one pointer to void*, other some pointer */
5056 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5057 type_error_incompatible("while parsing conditional",
5058 expression->base.source_position, true_type,
5061 result_type = type_error_type;
5064 conditional->true_expression
5065 = create_implicit_cast(true_expression, result_type);
5066 conditional->false_expression
5067 = create_implicit_cast(false_expression, result_type);
5068 conditional->base.type = result_type;
5071 return create_invalid_expression();
5075 * Parse an extension expression.
5077 static expression_t *parse_extension(unsigned precedence)
5079 eat(T___extension__);
5081 /* TODO enable extensions */
5082 expression_t *expression = parse_sub_expression(precedence);
5083 /* TODO disable extensions */
5088 * Parse a __builtin_classify_type() expression.
5090 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5092 eat(T___builtin_classify_type);
5094 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5095 result->base.type = type_int;
5098 add_anchor_token(')');
5099 expression_t *expression = parse_sub_expression(precedence);
5100 rem_anchor_token(')');
5102 result->classify_type.type_expression = expression;
5106 return create_invalid_expression();
5109 static void semantic_incdec(unary_expression_t *expression)
5111 type_t *const orig_type = expression->value->base.type;
5112 type_t *const type = skip_typeref(orig_type);
5113 /* TODO !is_type_real && !is_type_pointer */
5114 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5115 if (is_type_valid(type)) {
5116 /* TODO: improve error message */
5117 errorf(HERE, "operation needs an arithmetic or pointer type");
5122 expression->base.type = orig_type;
5125 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5127 type_t *const orig_type = expression->value->base.type;
5128 type_t *const type = skip_typeref(orig_type);
5129 if(!is_type_arithmetic(type)) {
5130 if (is_type_valid(type)) {
5131 /* TODO: improve error message */
5132 errorf(HERE, "operation needs an arithmetic type");
5137 expression->base.type = orig_type;
5140 static void semantic_unexpr_scalar(unary_expression_t *expression)
5142 type_t *const orig_type = expression->value->base.type;
5143 type_t *const type = skip_typeref(orig_type);
5144 if (!is_type_scalar(type)) {
5145 if (is_type_valid(type)) {
5146 errorf(HERE, "operand of ! must be of scalar type");
5151 expression->base.type = orig_type;
5154 static void semantic_unexpr_integer(unary_expression_t *expression)
5156 type_t *const orig_type = expression->value->base.type;
5157 type_t *const type = skip_typeref(orig_type);
5158 if (!is_type_integer(type)) {
5159 if (is_type_valid(type)) {
5160 errorf(HERE, "operand of ~ must be of integer type");
5165 expression->base.type = orig_type;
5168 static void semantic_dereference(unary_expression_t *expression)
5170 type_t *const orig_type = expression->value->base.type;
5171 type_t *const type = skip_typeref(orig_type);
5172 if(!is_type_pointer(type)) {
5173 if (is_type_valid(type)) {
5174 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5179 type_t *result_type = type->pointer.points_to;
5180 result_type = automatic_type_conversion(result_type);
5181 expression->base.type = result_type;
5185 * Check the semantic of the address taken expression.
5187 static void semantic_take_addr(unary_expression_t *expression)
5189 expression_t *value = expression->value;
5190 value->base.type = revert_automatic_type_conversion(value);
5192 type_t *orig_type = value->base.type;
5193 if(!is_type_valid(orig_type))
5196 if(value->kind == EXPR_REFERENCE) {
5197 declaration_t *const declaration = value->reference.declaration;
5198 if(declaration != NULL) {
5199 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5200 errorf(expression->base.source_position,
5201 "address of register variable '%Y' requested",
5202 declaration->symbol);
5204 declaration->address_taken = 1;
5208 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5211 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5212 static expression_t *parse_##unexpression_type(unsigned precedence) \
5216 expression_t *unary_expression \
5217 = allocate_expression_zero(unexpression_type); \
5218 unary_expression->base.source_position = HERE; \
5219 unary_expression->unary.value = parse_sub_expression(precedence); \
5221 sfunc(&unary_expression->unary); \
5223 return unary_expression; \
5226 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5227 semantic_unexpr_arithmetic)
5228 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5229 semantic_unexpr_arithmetic)
5230 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5231 semantic_unexpr_scalar)
5232 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5233 semantic_dereference)
5234 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5236 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5237 semantic_unexpr_integer)
5238 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5240 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5243 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5245 static expression_t *parse_##unexpression_type(unsigned precedence, \
5246 expression_t *left) \
5248 (void) precedence; \
5251 expression_t *unary_expression \
5252 = allocate_expression_zero(unexpression_type); \
5253 unary_expression->unary.value = left; \
5255 sfunc(&unary_expression->unary); \
5257 return unary_expression; \
5260 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5261 EXPR_UNARY_POSTFIX_INCREMENT,
5263 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5264 EXPR_UNARY_POSTFIX_DECREMENT,
5267 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5269 /* TODO: handle complex + imaginary types */
5271 /* § 6.3.1.8 Usual arithmetic conversions */
5272 if(type_left == type_long_double || type_right == type_long_double) {
5273 return type_long_double;
5274 } else if(type_left == type_double || type_right == type_double) {
5276 } else if(type_left == type_float || type_right == type_float) {
5280 type_right = promote_integer(type_right);
5281 type_left = promote_integer(type_left);
5283 if(type_left == type_right)
5286 bool signed_left = is_type_signed(type_left);
5287 bool signed_right = is_type_signed(type_right);
5288 int rank_left = get_rank(type_left);
5289 int rank_right = get_rank(type_right);
5290 if(rank_left < rank_right) {
5291 if(signed_left == signed_right || !signed_right) {
5297 if(signed_left == signed_right || !signed_left) {
5306 * Check the semantic restrictions for a binary expression.
5308 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5310 expression_t *const left = expression->left;
5311 expression_t *const right = expression->right;
5312 type_t *const orig_type_left = left->base.type;
5313 type_t *const orig_type_right = right->base.type;
5314 type_t *const type_left = skip_typeref(orig_type_left);
5315 type_t *const type_right = skip_typeref(orig_type_right);
5317 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5318 /* TODO: improve error message */
5319 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5320 errorf(HERE, "operation needs arithmetic types");
5325 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5326 expression->left = create_implicit_cast(left, arithmetic_type);
5327 expression->right = create_implicit_cast(right, arithmetic_type);
5328 expression->base.type = arithmetic_type;
5331 static void semantic_shift_op(binary_expression_t *expression)
5333 expression_t *const left = expression->left;
5334 expression_t *const right = expression->right;
5335 type_t *const orig_type_left = left->base.type;
5336 type_t *const orig_type_right = right->base.type;
5337 type_t * type_left = skip_typeref(orig_type_left);
5338 type_t * type_right = skip_typeref(orig_type_right);
5340 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5341 /* TODO: improve error message */
5342 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5343 errorf(HERE, "operation needs integer types");
5348 type_left = promote_integer(type_left);
5349 type_right = promote_integer(type_right);
5351 expression->left = create_implicit_cast(left, type_left);
5352 expression->right = create_implicit_cast(right, type_right);
5353 expression->base.type = type_left;
5356 static void semantic_add(binary_expression_t *expression)
5358 expression_t *const left = expression->left;
5359 expression_t *const right = expression->right;
5360 type_t *const orig_type_left = left->base.type;
5361 type_t *const orig_type_right = right->base.type;
5362 type_t *const type_left = skip_typeref(orig_type_left);
5363 type_t *const type_right = skip_typeref(orig_type_right);
5366 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5367 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5368 expression->left = create_implicit_cast(left, arithmetic_type);
5369 expression->right = create_implicit_cast(right, arithmetic_type);
5370 expression->base.type = arithmetic_type;
5372 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5373 expression->base.type = type_left;
5374 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5375 expression->base.type = type_right;
5376 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5377 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5381 static void semantic_sub(binary_expression_t *expression)
5383 expression_t *const left = expression->left;
5384 expression_t *const right = expression->right;
5385 type_t *const orig_type_left = left->base.type;
5386 type_t *const orig_type_right = right->base.type;
5387 type_t *const type_left = skip_typeref(orig_type_left);
5388 type_t *const type_right = skip_typeref(orig_type_right);
5391 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5392 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5393 expression->left = create_implicit_cast(left, arithmetic_type);
5394 expression->right = create_implicit_cast(right, arithmetic_type);
5395 expression->base.type = arithmetic_type;
5397 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5398 expression->base.type = type_left;
5399 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5400 if(!pointers_compatible(type_left, type_right)) {
5402 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5403 orig_type_left, orig_type_right);
5405 expression->base.type = type_ptrdiff_t;
5407 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5408 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5409 orig_type_left, orig_type_right);
5414 * Check the semantics of comparison expressions.
5416 * @param expression The expression to check.
5418 static void semantic_comparison(binary_expression_t *expression)
5420 expression_t *left = expression->left;
5421 expression_t *right = expression->right;
5422 type_t *orig_type_left = left->base.type;
5423 type_t *orig_type_right = right->base.type;
5425 type_t *type_left = skip_typeref(orig_type_left);
5426 type_t *type_right = skip_typeref(orig_type_right);
5428 /* TODO non-arithmetic types */
5429 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5430 if (warning.sign_compare &&
5431 (expression->base.kind != EXPR_BINARY_EQUAL &&
5432 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5433 (is_type_signed(type_left) != is_type_signed(type_right))) {
5434 warningf(expression->base.source_position,
5435 "comparison between signed and unsigned");
5437 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5438 expression->left = create_implicit_cast(left, arithmetic_type);
5439 expression->right = create_implicit_cast(right, arithmetic_type);
5440 expression->base.type = arithmetic_type;
5441 if (warning.float_equal &&
5442 (expression->base.kind == EXPR_BINARY_EQUAL ||
5443 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5444 is_type_float(arithmetic_type)) {
5445 warningf(expression->base.source_position,
5446 "comparing floating point with == or != is unsafe");
5448 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5449 /* TODO check compatibility */
5450 } else if (is_type_pointer(type_left)) {
5451 expression->right = create_implicit_cast(right, type_left);
5452 } else if (is_type_pointer(type_right)) {
5453 expression->left = create_implicit_cast(left, type_right);
5454 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5455 type_error_incompatible("invalid operands in comparison",
5456 expression->base.source_position,
5457 type_left, type_right);
5459 expression->base.type = type_int;
5462 static void semantic_arithmetic_assign(binary_expression_t *expression)
5464 expression_t *left = expression->left;
5465 expression_t *right = expression->right;
5466 type_t *orig_type_left = left->base.type;
5467 type_t *orig_type_right = right->base.type;
5469 type_t *type_left = skip_typeref(orig_type_left);
5470 type_t *type_right = skip_typeref(orig_type_right);
5472 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5473 /* TODO: improve error message */
5474 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5475 errorf(HERE, "operation needs arithmetic types");
5480 /* combined instructions are tricky. We can't create an implicit cast on
5481 * the left side, because we need the uncasted form for the store.
5482 * The ast2firm pass has to know that left_type must be right_type
5483 * for the arithmetic operation and create a cast by itself */
5484 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5485 expression->right = create_implicit_cast(right, arithmetic_type);
5486 expression->base.type = type_left;
5489 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5491 expression_t *const left = expression->left;
5492 expression_t *const right = expression->right;
5493 type_t *const orig_type_left = left->base.type;
5494 type_t *const orig_type_right = right->base.type;
5495 type_t *const type_left = skip_typeref(orig_type_left);
5496 type_t *const type_right = skip_typeref(orig_type_right);
5498 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5499 /* combined instructions are tricky. We can't create an implicit cast on
5500 * the left side, because we need the uncasted form for the store.
5501 * The ast2firm pass has to know that left_type must be right_type
5502 * for the arithmetic operation and create a cast by itself */
5503 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5504 expression->right = create_implicit_cast(right, arithmetic_type);
5505 expression->base.type = type_left;
5506 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5507 expression->base.type = type_left;
5508 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5509 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5514 * Check the semantic restrictions of a logical expression.
5516 static void semantic_logical_op(binary_expression_t *expression)
5518 expression_t *const left = expression->left;
5519 expression_t *const right = expression->right;
5520 type_t *const orig_type_left = left->base.type;
5521 type_t *const orig_type_right = right->base.type;
5522 type_t *const type_left = skip_typeref(orig_type_left);
5523 type_t *const type_right = skip_typeref(orig_type_right);
5525 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5526 /* TODO: improve error message */
5527 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5528 errorf(HERE, "operation needs scalar types");
5533 expression->base.type = type_int;
5537 * Checks if a compound type has constant fields.
5539 static bool has_const_fields(const compound_type_t *type)
5541 const scope_t *scope = &type->declaration->scope;
5542 const declaration_t *declaration = scope->declarations;
5544 for (; declaration != NULL; declaration = declaration->next) {
5545 if (declaration->namespc != NAMESPACE_NORMAL)
5548 const type_t *decl_type = skip_typeref(declaration->type);
5549 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5557 * Check the semantic restrictions of a binary assign expression.
5559 static void semantic_binexpr_assign(binary_expression_t *expression)
5561 expression_t *left = expression->left;
5562 type_t *orig_type_left = left->base.type;
5564 type_t *type_left = revert_automatic_type_conversion(left);
5565 type_left = skip_typeref(orig_type_left);
5567 /* must be a modifiable lvalue */
5568 if (is_type_array(type_left)) {
5569 errorf(HERE, "cannot assign to arrays ('%E')", left);
5572 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5573 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5577 if(is_type_incomplete(type_left)) {
5579 "left-hand side of assignment '%E' has incomplete type '%T'",
5580 left, orig_type_left);
5583 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5584 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5585 left, orig_type_left);
5589 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5591 if (res_type == NULL) {
5592 errorf(expression->base.source_position,
5593 "cannot assign to '%T' from '%T'",
5594 orig_type_left, expression->right->base.type);
5596 expression->right = create_implicit_cast(expression->right, res_type);
5599 expression->base.type = orig_type_left;
5603 * Determine if the outermost operation (or parts thereof) of the given
5604 * expression has no effect in order to generate a warning about this fact.
5605 * Therefore in some cases this only examines some of the operands of the
5606 * expression (see comments in the function and examples below).
5608 * f() + 23; // warning, because + has no effect
5609 * x || f(); // no warning, because x controls execution of f()
5610 * x ? y : f(); // warning, because y has no effect
5611 * (void)x; // no warning to be able to suppress the warning
5612 * This function can NOT be used for an "expression has definitely no effect"-
5614 static bool expression_has_effect(const expression_t *const expr)
5616 switch (expr->kind) {
5617 case EXPR_UNKNOWN: break;
5618 case EXPR_INVALID: return true; /* do NOT warn */
5619 case EXPR_REFERENCE: return false;
5620 case EXPR_CONST: return false;
5621 case EXPR_CHARACTER_CONSTANT: return false;
5622 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5623 case EXPR_STRING_LITERAL: return false;
5624 case EXPR_WIDE_STRING_LITERAL: return false;
5627 const call_expression_t *const call = &expr->call;
5628 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5631 switch (call->function->builtin_symbol.symbol->ID) {
5632 case T___builtin_va_end: return true;
5633 default: return false;
5637 /* Generate the warning if either the left or right hand side of a
5638 * conditional expression has no effect */
5639 case EXPR_CONDITIONAL: {
5640 const conditional_expression_t *const cond = &expr->conditional;
5642 expression_has_effect(cond->true_expression) &&
5643 expression_has_effect(cond->false_expression);
5646 case EXPR_SELECT: return false;
5647 case EXPR_ARRAY_ACCESS: return false;
5648 case EXPR_SIZEOF: return false;
5649 case EXPR_CLASSIFY_TYPE: return false;
5650 case EXPR_ALIGNOF: return false;
5652 case EXPR_FUNCTION: return false;
5653 case EXPR_PRETTY_FUNCTION: return false;
5654 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5655 case EXPR_BUILTIN_CONSTANT_P: return false;
5656 case EXPR_BUILTIN_PREFETCH: return true;
5657 case EXPR_OFFSETOF: return false;
5658 case EXPR_VA_START: return true;
5659 case EXPR_VA_ARG: return true;
5660 case EXPR_STATEMENT: return true; // TODO
5661 case EXPR_COMPOUND_LITERAL: return false;
5663 case EXPR_UNARY_NEGATE: return false;
5664 case EXPR_UNARY_PLUS: return false;
5665 case EXPR_UNARY_BITWISE_NEGATE: return false;
5666 case EXPR_UNARY_NOT: return false;
5667 case EXPR_UNARY_DEREFERENCE: return false;
5668 case EXPR_UNARY_TAKE_ADDRESS: return false;
5669 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5670 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5671 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5672 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5674 /* Treat void casts as if they have an effect in order to being able to
5675 * suppress the warning */
5676 case EXPR_UNARY_CAST: {
5677 type_t *const type = skip_typeref(expr->base.type);
5678 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5681 case EXPR_UNARY_CAST_IMPLICIT: return true;
5682 case EXPR_UNARY_ASSUME: return true;
5683 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5685 case EXPR_BINARY_ADD: return false;
5686 case EXPR_BINARY_SUB: return false;
5687 case EXPR_BINARY_MUL: return false;
5688 case EXPR_BINARY_DIV: return false;
5689 case EXPR_BINARY_MOD: return false;
5690 case EXPR_BINARY_EQUAL: return false;
5691 case EXPR_BINARY_NOTEQUAL: return false;
5692 case EXPR_BINARY_LESS: return false;
5693 case EXPR_BINARY_LESSEQUAL: return false;
5694 case EXPR_BINARY_GREATER: return false;
5695 case EXPR_BINARY_GREATEREQUAL: return false;
5696 case EXPR_BINARY_BITWISE_AND: return false;
5697 case EXPR_BINARY_BITWISE_OR: return false;
5698 case EXPR_BINARY_BITWISE_XOR: return false;
5699 case EXPR_BINARY_SHIFTLEFT: return false;
5700 case EXPR_BINARY_SHIFTRIGHT: return false;
5701 case EXPR_BINARY_ASSIGN: return true;
5702 case EXPR_BINARY_MUL_ASSIGN: return true;
5703 case EXPR_BINARY_DIV_ASSIGN: return true;
5704 case EXPR_BINARY_MOD_ASSIGN: return true;
5705 case EXPR_BINARY_ADD_ASSIGN: return true;
5706 case EXPR_BINARY_SUB_ASSIGN: return true;
5707 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5708 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5709 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5710 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5711 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5713 /* Only examine the right hand side of && and ||, because the left hand
5714 * side already has the effect of controlling the execution of the right
5716 case EXPR_BINARY_LOGICAL_AND:
5717 case EXPR_BINARY_LOGICAL_OR:
5718 /* Only examine the right hand side of a comma expression, because the left
5719 * hand side has a separate warning */
5720 case EXPR_BINARY_COMMA:
5721 return expression_has_effect(expr->binary.right);
5723 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5724 case EXPR_BINARY_ISGREATER: return false;
5725 case EXPR_BINARY_ISGREATEREQUAL: return false;
5726 case EXPR_BINARY_ISLESS: return false;
5727 case EXPR_BINARY_ISLESSEQUAL: return false;
5728 case EXPR_BINARY_ISLESSGREATER: return false;
5729 case EXPR_BINARY_ISUNORDERED: return false;
5732 panic("unexpected expression");
5735 static void semantic_comma(binary_expression_t *expression)
5737 if (warning.unused_value) {
5738 const expression_t *const left = expression->left;
5739 if (!expression_has_effect(left)) {
5740 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5743 expression->base.type = expression->right->base.type;
5746 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5747 static expression_t *parse_##binexpression_type(unsigned precedence, \
5748 expression_t *left) \
5751 source_position_t pos = HERE; \
5753 expression_t *right = parse_sub_expression(precedence + lr); \
5755 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5756 binexpr->base.source_position = pos; \
5757 binexpr->binary.left = left; \
5758 binexpr->binary.right = right; \
5759 sfunc(&binexpr->binary); \
5764 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5765 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5766 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5767 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5768 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5769 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5770 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5771 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5772 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5774 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5775 semantic_comparison, 1)
5776 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5777 semantic_comparison, 1)
5778 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5779 semantic_comparison, 1)
5780 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5781 semantic_comparison, 1)
5783 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5784 semantic_binexpr_arithmetic, 1)
5785 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5786 semantic_binexpr_arithmetic, 1)
5787 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5788 semantic_binexpr_arithmetic, 1)
5789 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5790 semantic_logical_op, 1)
5791 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5792 semantic_logical_op, 1)
5793 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5794 semantic_shift_op, 1)
5795 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5796 semantic_shift_op, 1)
5797 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5798 semantic_arithmetic_addsubb_assign, 0)
5799 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5800 semantic_arithmetic_addsubb_assign, 0)
5801 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5802 semantic_arithmetic_assign, 0)
5803 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5804 semantic_arithmetic_assign, 0)
5805 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5806 semantic_arithmetic_assign, 0)
5807 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5808 semantic_arithmetic_assign, 0)
5809 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5810 semantic_arithmetic_assign, 0)
5811 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5812 semantic_arithmetic_assign, 0)
5813 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5814 semantic_arithmetic_assign, 0)
5815 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5816 semantic_arithmetic_assign, 0)
5818 static expression_t *parse_sub_expression(unsigned precedence)
5820 if(token.type < 0) {
5821 return expected_expression_error();
5824 expression_parser_function_t *parser
5825 = &expression_parsers[token.type];
5826 source_position_t source_position = token.source_position;
5829 if(parser->parser != NULL) {
5830 left = parser->parser(parser->precedence);
5832 left = parse_primary_expression();
5834 assert(left != NULL);
5835 left->base.source_position = source_position;
5838 if(token.type < 0) {
5839 return expected_expression_error();
5842 parser = &expression_parsers[token.type];
5843 if(parser->infix_parser == NULL)
5845 if(parser->infix_precedence < precedence)
5848 left = parser->infix_parser(parser->infix_precedence, left);
5850 assert(left != NULL);
5851 assert(left->kind != EXPR_UNKNOWN);
5852 left->base.source_position = source_position;
5859 * Parse an expression.
5861 static expression_t *parse_expression(void)
5863 return parse_sub_expression(1);
5867 * Register a parser for a prefix-like operator with given precedence.
5869 * @param parser the parser function
5870 * @param token_type the token type of the prefix token
5871 * @param precedence the precedence of the operator
5873 static void register_expression_parser(parse_expression_function parser,
5874 int token_type, unsigned precedence)
5876 expression_parser_function_t *entry = &expression_parsers[token_type];
5878 if(entry->parser != NULL) {
5879 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5880 panic("trying to register multiple expression parsers for a token");
5882 entry->parser = parser;
5883 entry->precedence = precedence;
5887 * Register a parser for an infix operator with given precedence.
5889 * @param parser the parser function
5890 * @param token_type the token type of the infix operator
5891 * @param precedence the precedence of the operator
5893 static void register_infix_parser(parse_expression_infix_function parser,
5894 int token_type, unsigned precedence)
5896 expression_parser_function_t *entry = &expression_parsers[token_type];
5898 if(entry->infix_parser != NULL) {
5899 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5900 panic("trying to register multiple infix expression parsers for a "
5903 entry->infix_parser = parser;
5904 entry->infix_precedence = precedence;
5908 * Initialize the expression parsers.
5910 static void init_expression_parsers(void)
5912 memset(&expression_parsers, 0, sizeof(expression_parsers));
5914 register_infix_parser(parse_array_expression, '[', 30);
5915 register_infix_parser(parse_call_expression, '(', 30);
5916 register_infix_parser(parse_select_expression, '.', 30);
5917 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5918 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5920 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5923 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5924 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5925 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5926 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5927 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5928 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5929 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5930 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5931 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5932 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5933 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5934 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5935 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5936 T_EXCLAMATIONMARKEQUAL, 13);
5937 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5938 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5939 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5940 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5941 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5942 register_infix_parser(parse_conditional_expression, '?', 7);
5943 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5944 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5945 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5946 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5947 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5948 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5949 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5950 T_LESSLESSEQUAL, 2);
5951 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5952 T_GREATERGREATEREQUAL, 2);
5953 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5955 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5957 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5960 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
5962 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
5963 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
5964 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
5965 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
5966 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
5967 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
5968 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5970 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5972 register_expression_parser(parse_sizeof, T_sizeof, 25);
5973 register_expression_parser(parse_alignof, T___alignof__, 25);
5974 register_expression_parser(parse_extension, T___extension__, 25);
5975 register_expression_parser(parse_builtin_classify_type,
5976 T___builtin_classify_type, 25);
5980 * Parse a asm statement constraints specification.
5982 static asm_constraint_t *parse_asm_constraints(void)
5984 asm_constraint_t *result = NULL;
5985 asm_constraint_t *last = NULL;
5987 while(token.type == T_STRING_LITERAL || token.type == '[') {
5988 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5989 memset(constraint, 0, sizeof(constraint[0]));
5991 if(token.type == '[') {
5993 if(token.type != T_IDENTIFIER) {
5994 parse_error_expected("while parsing asm constraint",
5998 constraint->symbol = token.v.symbol;
6003 constraint->constraints = parse_string_literals();
6005 constraint->expression = parse_expression();
6009 last->next = constraint;
6011 result = constraint;
6015 if(token.type != ',')
6026 * Parse a asm statement clobber specification.
6028 static asm_clobber_t *parse_asm_clobbers(void)
6030 asm_clobber_t *result = NULL;
6031 asm_clobber_t *last = NULL;
6033 while(token.type == T_STRING_LITERAL) {
6034 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6035 clobber->clobber = parse_string_literals();
6038 last->next = clobber;
6044 if(token.type != ',')
6053 * Parse an asm statement.
6055 static statement_t *parse_asm_statement(void)
6059 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6060 statement->base.source_position = token.source_position;
6062 asm_statement_t *asm_statement = &statement->asms;
6064 if(token.type == T_volatile) {
6066 asm_statement->is_volatile = true;
6070 add_anchor_token(')');
6071 add_anchor_token(':');
6072 asm_statement->asm_text = parse_string_literals();
6074 if(token.type != ':') {
6075 rem_anchor_token(':');
6080 asm_statement->inputs = parse_asm_constraints();
6081 if(token.type != ':') {
6082 rem_anchor_token(':');
6087 asm_statement->outputs = parse_asm_constraints();
6088 if(token.type != ':') {
6089 rem_anchor_token(':');
6092 rem_anchor_token(':');
6095 asm_statement->clobbers = parse_asm_clobbers();
6098 rem_anchor_token(')');
6107 * Parse a case statement.
6109 static statement_t *parse_case_statement(void)
6113 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6115 statement->base.source_position = token.source_position;
6116 statement->case_label.expression = parse_expression();
6118 if (c_mode & _GNUC) {
6119 if (token.type == T_DOTDOTDOT) {
6121 statement->case_label.end_range = parse_expression();
6127 if (! is_constant_expression(statement->case_label.expression)) {
6128 errorf(statement->base.source_position,
6129 "case label does not reduce to an integer constant");
6131 /* TODO: check if the case label is already known */
6132 if (current_switch != NULL) {
6133 /* link all cases into the switch statement */
6134 if (current_switch->last_case == NULL) {
6135 current_switch->first_case =
6136 current_switch->last_case = &statement->case_label;
6138 current_switch->last_case->next = &statement->case_label;
6141 errorf(statement->base.source_position,
6142 "case label not within a switch statement");
6145 statement->case_label.statement = parse_statement();
6153 * Finds an existing default label of a switch statement.
6155 static case_label_statement_t *
6156 find_default_label(const switch_statement_t *statement)
6158 case_label_statement_t *label = statement->first_case;
6159 for ( ; label != NULL; label = label->next) {
6160 if (label->expression == NULL)
6167 * Parse a default statement.
6169 static statement_t *parse_default_statement(void)
6173 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6175 statement->base.source_position = token.source_position;
6178 if (current_switch != NULL) {
6179 const case_label_statement_t *def_label = find_default_label(current_switch);
6180 if (def_label != NULL) {
6181 errorf(HERE, "multiple default labels in one switch");
6182 errorf(def_label->base.source_position,
6183 "this is the first default label");
6185 /* link all cases into the switch statement */
6186 if (current_switch->last_case == NULL) {
6187 current_switch->first_case =
6188 current_switch->last_case = &statement->case_label;
6190 current_switch->last_case->next = &statement->case_label;
6194 errorf(statement->base.source_position,
6195 "'default' label not within a switch statement");
6197 statement->case_label.statement = parse_statement();
6205 * Return the declaration for a given label symbol or create a new one.
6207 static declaration_t *get_label(symbol_t *symbol)
6209 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6210 assert(current_function != NULL);
6211 /* if we found a label in the same function, then we already created the
6213 if(candidate != NULL
6214 && candidate->parent_scope == ¤t_function->scope) {
6218 /* otherwise we need to create a new one */
6219 declaration_t *const declaration = allocate_declaration_zero();
6220 declaration->namespc = NAMESPACE_LABEL;
6221 declaration->symbol = symbol;
6223 label_push(declaration);
6229 * Parse a label statement.
6231 static statement_t *parse_label_statement(void)
6233 assert(token.type == T_IDENTIFIER);
6234 symbol_t *symbol = token.v.symbol;
6237 declaration_t *label = get_label(symbol);
6239 /* if source position is already set then the label is defined twice,
6240 * otherwise it was just mentioned in a goto so far */
6241 if(label->source_position.input_name != NULL) {
6242 errorf(HERE, "duplicate label '%Y'", symbol);
6243 errorf(label->source_position, "previous definition of '%Y' was here",
6246 label->source_position = token.source_position;
6249 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6251 statement->base.source_position = token.source_position;
6252 statement->label.label = label;
6256 if(token.type == '}') {
6257 /* TODO only warn? */
6258 errorf(HERE, "label at end of compound statement");
6261 if (token.type == ';') {
6262 /* eat an empty statement here, to avoid the warning about an empty
6263 * after a label. label:; is commonly used to have a label before
6267 statement->label.statement = parse_statement();
6271 /* remember the labels's in a list for later checking */
6272 if (label_last == NULL) {
6273 label_first = &statement->label;
6275 label_last->next = &statement->label;
6277 label_last = &statement->label;
6283 * Parse an if statement.
6285 static statement_t *parse_if(void)
6289 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6290 statement->base.source_position = token.source_position;
6293 add_anchor_token(')');
6294 statement->ifs.condition = parse_expression();
6295 rem_anchor_token(')');
6298 add_anchor_token(T_else);
6299 statement->ifs.true_statement = parse_statement();
6300 rem_anchor_token(T_else);
6302 if(token.type == T_else) {
6304 statement->ifs.false_statement = parse_statement();
6313 * Parse a switch statement.
6315 static statement_t *parse_switch(void)
6319 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6320 statement->base.source_position = token.source_position;
6323 expression_t *const expr = parse_expression();
6324 type_t * type = skip_typeref(expr->base.type);
6325 if (is_type_integer(type)) {
6326 type = promote_integer(type);
6327 } else if (is_type_valid(type)) {
6328 errorf(expr->base.source_position,
6329 "switch quantity is not an integer, but '%T'", type);
6330 type = type_error_type;
6332 statement->switchs.expression = create_implicit_cast(expr, type);
6335 switch_statement_t *rem = current_switch;
6336 current_switch = &statement->switchs;
6337 statement->switchs.body = parse_statement();
6338 current_switch = rem;
6340 if (warning.switch_default
6341 && find_default_label(&statement->switchs) == NULL) {
6342 warningf(statement->base.source_position, "switch has no default case");
6350 static statement_t *parse_loop_body(statement_t *const loop)
6352 statement_t *const rem = current_loop;
6353 current_loop = loop;
6355 statement_t *const body = parse_statement();
6362 * Parse a while statement.
6364 static statement_t *parse_while(void)
6368 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6369 statement->base.source_position = token.source_position;
6372 add_anchor_token(')');
6373 statement->whiles.condition = parse_expression();
6374 rem_anchor_token(')');
6377 statement->whiles.body = parse_loop_body(statement);
6385 * Parse a do statement.
6387 static statement_t *parse_do(void)
6391 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6393 statement->base.source_position = token.source_position;
6395 add_anchor_token(T_while);
6396 statement->do_while.body = parse_loop_body(statement);
6397 rem_anchor_token(T_while);
6401 add_anchor_token(')');
6402 statement->do_while.condition = parse_expression();
6403 rem_anchor_token(')');
6413 * Parse a for statement.
6415 static statement_t *parse_for(void)
6419 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6420 statement->base.source_position = token.source_position;
6422 int top = environment_top();
6423 scope_t *last_scope = scope;
6424 set_scope(&statement->fors.scope);
6427 add_anchor_token(')');
6429 if(token.type != ';') {
6430 if(is_declaration_specifier(&token, false)) {
6431 parse_declaration(record_declaration);
6433 expression_t *const init = parse_expression();
6434 statement->fors.initialisation = init;
6435 if (warning.unused_value && !expression_has_effect(init)) {
6436 warningf(init->base.source_position,
6437 "initialisation of 'for'-statement has no effect");
6445 if(token.type != ';') {
6446 statement->fors.condition = parse_expression();
6449 if(token.type != ')') {
6450 expression_t *const step = parse_expression();
6451 statement->fors.step = step;
6452 if (warning.unused_value && !expression_has_effect(step)) {
6453 warningf(step->base.source_position,
6454 "step of 'for'-statement has no effect");
6457 rem_anchor_token(')');
6459 statement->fors.body = parse_loop_body(statement);
6461 assert(scope == &statement->fors.scope);
6462 set_scope(last_scope);
6463 environment_pop_to(top);
6468 rem_anchor_token(')');
6469 assert(scope == &statement->fors.scope);
6470 set_scope(last_scope);
6471 environment_pop_to(top);
6477 * Parse a goto statement.
6479 static statement_t *parse_goto(void)
6483 if(token.type != T_IDENTIFIER) {
6484 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6488 symbol_t *symbol = token.v.symbol;
6491 declaration_t *label = get_label(symbol);
6493 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6494 statement->base.source_position = token.source_position;
6496 statement->gotos.label = label;
6498 /* remember the goto's in a list for later checking */
6499 if (goto_last == NULL) {
6500 goto_first = &statement->gotos;
6502 goto_last->next = &statement->gotos;
6504 goto_last = &statement->gotos;
6514 * Parse a continue statement.
6516 static statement_t *parse_continue(void)
6518 statement_t *statement;
6519 if (current_loop == NULL) {
6520 errorf(HERE, "continue statement not within loop");
6523 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6525 statement->base.source_position = token.source_position;
6537 * Parse a break statement.
6539 static statement_t *parse_break(void)
6541 statement_t *statement;
6542 if (current_switch == NULL && current_loop == NULL) {
6543 errorf(HERE, "break statement not within loop or switch");
6546 statement = allocate_statement_zero(STATEMENT_BREAK);
6548 statement->base.source_position = token.source_position;
6560 * Check if a given declaration represents a local variable.
6562 static bool is_local_var_declaration(const declaration_t *declaration) {
6563 switch ((storage_class_tag_t) declaration->storage_class) {
6564 case STORAGE_CLASS_AUTO:
6565 case STORAGE_CLASS_REGISTER: {
6566 const type_t *type = skip_typeref(declaration->type);
6567 if(is_type_function(type)) {
6579 * Check if a given declaration represents a variable.
6581 static bool is_var_declaration(const declaration_t *declaration) {
6582 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6585 const type_t *type = skip_typeref(declaration->type);
6586 return !is_type_function(type);
6590 * Check if a given expression represents a local variable.
6592 static bool is_local_variable(const expression_t *expression)
6594 if (expression->base.kind != EXPR_REFERENCE) {
6597 const declaration_t *declaration = expression->reference.declaration;
6598 return is_local_var_declaration(declaration);
6602 * Check if a given expression represents a local variable and
6603 * return its declaration then, else return NULL.
6605 declaration_t *expr_is_variable(const expression_t *expression)
6607 if (expression->base.kind != EXPR_REFERENCE) {
6610 declaration_t *declaration = expression->reference.declaration;
6611 if (is_var_declaration(declaration))
6617 * Parse a return statement.
6619 static statement_t *parse_return(void)
6623 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6624 statement->base.source_position = token.source_position;
6626 expression_t *return_value = NULL;
6627 if(token.type != ';') {
6628 return_value = parse_expression();
6632 const type_t *const func_type = current_function->type;
6633 assert(is_type_function(func_type));
6634 type_t *const return_type = skip_typeref(func_type->function.return_type);
6636 if(return_value != NULL) {
6637 type_t *return_value_type = skip_typeref(return_value->base.type);
6639 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6640 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6641 warningf(statement->base.source_position,
6642 "'return' with a value, in function returning void");
6643 return_value = NULL;
6645 type_t *const res_type = semantic_assign(return_type,
6646 return_value, "'return'");
6647 if (res_type == NULL) {
6648 errorf(statement->base.source_position,
6649 "cannot return something of type '%T' in function returning '%T'",
6650 return_value->base.type, return_type);
6652 return_value = create_implicit_cast(return_value, res_type);
6655 /* check for returning address of a local var */
6656 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6657 const expression_t *expression = return_value->unary.value;
6658 if (is_local_variable(expression)) {
6659 warningf(statement->base.source_position,
6660 "function returns address of local variable");
6664 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6665 warningf(statement->base.source_position,
6666 "'return' without value, in function returning non-void");
6669 statement->returns.value = return_value;
6677 * Parse a declaration statement.
6679 static statement_t *parse_declaration_statement(void)
6681 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6683 statement->base.source_position = token.source_position;
6685 declaration_t *before = last_declaration;
6686 parse_declaration(record_declaration);
6688 if(before == NULL) {
6689 statement->declaration.declarations_begin = scope->declarations;
6691 statement->declaration.declarations_begin = before->next;
6693 statement->declaration.declarations_end = last_declaration;
6699 * Parse an expression statement, ie. expr ';'.
6701 static statement_t *parse_expression_statement(void)
6703 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6705 statement->base.source_position = token.source_position;
6706 expression_t *const expr = parse_expression();
6707 statement->expression.expression = expr;
6709 if (warning.unused_value && !expression_has_effect(expr)) {
6710 warningf(expr->base.source_position, "statement has no effect");
6721 * Parse a statement.
6723 static statement_t *parse_statement(void)
6725 statement_t *statement = NULL;
6727 /* declaration or statement */
6728 add_anchor_token(';');
6729 switch(token.type) {
6731 statement = parse_asm_statement();
6735 statement = parse_case_statement();
6739 statement = parse_default_statement();
6743 statement = parse_compound_statement();
6747 statement = parse_if();
6751 statement = parse_switch();
6755 statement = parse_while();
6759 statement = parse_do();
6763 statement = parse_for();
6767 statement = parse_goto();
6771 statement = parse_continue();
6775 statement = parse_break();
6779 statement = parse_return();
6783 if (warning.empty_statement) {
6784 warningf(HERE, "statement is empty");
6791 if(look_ahead(1)->type == ':') {
6792 statement = parse_label_statement();
6796 if(is_typedef_symbol(token.v.symbol)) {
6797 statement = parse_declaration_statement();
6801 statement = parse_expression_statement();
6804 case T___extension__:
6805 /* this can be a prefix to a declaration or an expression statement */
6806 /* we simply eat it now and parse the rest with tail recursion */
6809 } while(token.type == T___extension__);
6810 statement = parse_statement();
6814 statement = parse_declaration_statement();
6818 statement = parse_expression_statement();
6821 rem_anchor_token(';');
6823 assert(statement == NULL
6824 || statement->base.source_position.input_name != NULL);
6830 * Parse a compound statement.
6832 static statement_t *parse_compound_statement(void)
6834 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6836 statement->base.source_position = token.source_position;
6839 add_anchor_token('}');
6841 int top = environment_top();
6842 scope_t *last_scope = scope;
6843 set_scope(&statement->compound.scope);
6845 statement_t *last_statement = NULL;
6847 while(token.type != '}' && token.type != T_EOF) {
6848 statement_t *sub_statement = parse_statement();
6849 if(sub_statement == NULL) {
6850 /* an error occurred. if we are at an anchor, return */
6856 if(last_statement != NULL) {
6857 last_statement->base.next = sub_statement;
6859 statement->compound.statements = sub_statement;
6862 while(sub_statement->base.next != NULL)
6863 sub_statement = sub_statement->base.next;
6865 last_statement = sub_statement;
6868 if(token.type == '}') {
6871 errorf(statement->base.source_position,
6872 "end of file while looking for closing '}'");
6876 rem_anchor_token('}');
6877 assert(scope == &statement->compound.scope);
6878 set_scope(last_scope);
6879 environment_pop_to(top);
6885 * Initialize builtin types.
6887 static void initialize_builtin_types(void)
6889 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6890 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6891 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6892 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6893 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6894 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6895 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6896 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6898 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6899 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6900 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6901 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6905 * Check for unused global static functions and variables
6907 static void check_unused_globals(void)
6909 if (!warning.unused_function && !warning.unused_variable)
6912 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6913 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6916 type_t *const type = decl->type;
6918 if (is_type_function(skip_typeref(type))) {
6919 if (!warning.unused_function || decl->is_inline)
6922 s = (decl->init.statement != NULL ? "defined" : "declared");
6924 if (!warning.unused_variable)
6930 warningf(decl->source_position, "'%#T' %s but not used",
6931 type, decl->symbol, s);
6936 * Parse a translation unit.
6938 static translation_unit_t *parse_translation_unit(void)
6940 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6942 assert(global_scope == NULL);
6943 global_scope = &unit->scope;
6945 assert(scope == NULL);
6946 set_scope(&unit->scope);
6948 initialize_builtin_types();
6950 while(token.type != T_EOF) {
6951 if (token.type == ';') {
6952 /* TODO error in strict mode */
6953 warningf(HERE, "stray ';' outside of function");
6956 parse_external_declaration();
6960 assert(scope == &unit->scope);
6962 last_declaration = NULL;
6964 assert(global_scope == &unit->scope);
6965 check_unused_globals();
6966 global_scope = NULL;
6974 * @return the translation unit or NULL if errors occurred.
6976 translation_unit_t *parse(void)
6978 environment_stack = NEW_ARR_F(stack_entry_t, 0);
6979 label_stack = NEW_ARR_F(stack_entry_t, 0);
6980 diagnostic_count = 0;
6984 type_set_output(stderr);
6985 ast_set_output(stderr);
6987 lookahead_bufpos = 0;
6988 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6991 translation_unit_t *unit = parse_translation_unit();
6993 DEL_ARR_F(environment_stack);
6994 DEL_ARR_F(label_stack);
7003 * Initialize the parser.
7005 void init_parser(void)
7008 /* add predefined symbols for extended-decl-modifier */
7009 sym_align = symbol_table_insert("align");
7010 sym_allocate = symbol_table_insert("allocate");
7011 sym_dllimport = symbol_table_insert("dllimport");
7012 sym_dllexport = symbol_table_insert("dllexport");
7013 sym_naked = symbol_table_insert("naked");
7014 sym_noinline = symbol_table_insert("noinline");
7015 sym_noreturn = symbol_table_insert("noreturn");
7016 sym_nothrow = symbol_table_insert("nothrow");
7017 sym_novtable = symbol_table_insert("novtable");
7018 sym_property = symbol_table_insert("property");
7019 sym_get = symbol_table_insert("get");
7020 sym_put = symbol_table_insert("put");
7021 sym_selectany = symbol_table_insert("selectany");
7022 sym_thread = symbol_table_insert("thread");
7023 sym_uuid = symbol_table_insert("uuid");
7024 sym_deprecated = symbol_table_insert("deprecated");
7026 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7028 init_expression_parsers();
7029 obstack_init(&temp_obst);
7031 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7032 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7036 * Terminate the parser.
7038 void exit_parser(void)
7040 obstack_free(&temp_obst, NULL);