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 argument_list_t argument_list_t;
52 struct argument_list_t {
54 argument_list_t *next;
57 typedef struct gnu_attribute_t gnu_attribute_t;
58 struct gnu_attribute_t {
59 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
60 gnu_attribute_t *next;
61 bool invalid; /**< Set if this attribute had argument errors, */
62 bool have_arguments; /**< True, if this attribute has arguments. */
66 atomic_type_kind_t akind;
67 long argument; /**< Single argument. */
68 argument_list_t *arguments; /**< List of argument expressions. */
72 typedef struct declaration_specifiers_t declaration_specifiers_t;
73 struct declaration_specifiers_t {
74 source_position_t source_position;
75 unsigned char declared_storage_class;
76 unsigned char alignment; /**< Alignment, 0 if not set. */
77 unsigned int is_inline : 1;
78 unsigned int deprecated : 1;
79 decl_modifiers_t modifiers; /**< declaration modifiers */
80 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
81 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
82 symbol_t *get_property_sym; /**< the name of the get property if set. */
83 symbol_t *put_property_sym; /**< the name of the put property if set. */
88 * An environment for parsing initializers (and compound literals).
90 typedef struct parse_initializer_env_t {
91 type_t *type; /**< the type of the initializer. In case of an
92 array type with unspecified size this gets
93 adjusted to the actual size. */
94 declaration_t *declaration; /**< the declaration that is initialized if any */
95 bool must_be_constant;
96 } parse_initializer_env_t;
98 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
100 static token_t token;
101 static token_t lookahead_buffer[MAX_LOOKAHEAD];
102 static int lookahead_bufpos;
103 static stack_entry_t *environment_stack = NULL;
104 static stack_entry_t *label_stack = NULL;
105 static scope_t *global_scope = NULL;
106 static scope_t *scope = NULL;
107 static declaration_t *last_declaration = NULL;
108 static declaration_t *current_function = NULL;
109 static switch_statement_t *current_switch = NULL;
110 static statement_t *current_loop = NULL;
111 static statement_t *current_parent = NULL;
112 static ms_try_statement_t *current_try = NULL;
113 static goto_statement_t *goto_first = NULL;
114 static goto_statement_t *goto_last = NULL;
115 static label_statement_t *label_first = NULL;
116 static label_statement_t *label_last = NULL;
117 static translation_unit_t *unit = NULL;
118 static struct obstack temp_obst;
120 #define PUSH_PARENT(stmt) \
121 statement_t *const prev_parent = current_parent; \
122 current_parent = (stmt);
123 #define POP_PARENT ((void)(current_parent = prev_parent))
125 static source_position_t null_position = { NULL, 0 };
127 /* symbols for Microsoft extended-decl-modifier */
128 static const symbol_t *sym_align = NULL;
129 static const symbol_t *sym_allocate = NULL;
130 static const symbol_t *sym_dllimport = NULL;
131 static const symbol_t *sym_dllexport = NULL;
132 static const symbol_t *sym_naked = NULL;
133 static const symbol_t *sym_noinline = NULL;
134 static const symbol_t *sym_noreturn = NULL;
135 static const symbol_t *sym_nothrow = NULL;
136 static const symbol_t *sym_novtable = NULL;
137 static const symbol_t *sym_property = NULL;
138 static const symbol_t *sym_get = NULL;
139 static const symbol_t *sym_put = NULL;
140 static const symbol_t *sym_selectany = NULL;
141 static const symbol_t *sym_thread = NULL;
142 static const symbol_t *sym_uuid = NULL;
143 static const symbol_t *sym_deprecated = NULL;
144 static const symbol_t *sym_restrict = NULL;
145 static const symbol_t *sym_noalias = NULL;
147 /** The token anchor set */
148 static unsigned char token_anchor_set[T_LAST_TOKEN];
150 /** The current source position. */
151 #define HERE (&token.source_position)
153 static type_t *type_valist;
155 static statement_t *parse_compound_statement(bool inside_expression_statement);
156 static statement_t *parse_statement(void);
158 static expression_t *parse_sub_expression(unsigned precedence);
159 static expression_t *parse_expression(void);
160 static type_t *parse_typename(void);
162 static void parse_compound_type_entries(declaration_t *compound_declaration);
163 static declaration_t *parse_declarator(
164 const declaration_specifiers_t *specifiers, bool may_be_abstract);
165 static declaration_t *record_declaration(declaration_t *declaration);
167 static void semantic_comparison(binary_expression_t *expression);
169 #define STORAGE_CLASSES \
177 #define TYPE_QUALIFIERS \
182 case T__forceinline: \
183 case T___attribute__:
185 #ifdef PROVIDE_COMPLEX
186 #define COMPLEX_SPECIFIERS \
188 #define IMAGINARY_SPECIFIERS \
191 #define COMPLEX_SPECIFIERS
192 #define IMAGINARY_SPECIFIERS
195 #define TYPE_SPECIFIERS \
210 case T___builtin_va_list: \
215 #define DECLARATION_START \
220 #define TYPENAME_START \
225 * Allocate an AST node with given size and
226 * initialize all fields with zero.
228 static void *allocate_ast_zero(size_t size)
230 void *res = allocate_ast(size);
231 memset(res, 0, size);
235 static declaration_t *allocate_declaration_zero(void)
237 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
238 declaration->type = type_error_type;
239 declaration->alignment = 0;
244 * Returns the size of a statement node.
246 * @param kind the statement kind
248 static size_t get_statement_struct_size(statement_kind_t kind)
250 static const size_t sizes[] = {
251 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
252 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
253 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
254 [STATEMENT_RETURN] = sizeof(return_statement_t),
255 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
256 [STATEMENT_IF] = sizeof(if_statement_t),
257 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
258 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
259 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
260 [STATEMENT_BREAK] = sizeof(statement_base_t),
261 [STATEMENT_GOTO] = sizeof(goto_statement_t),
262 [STATEMENT_LABEL] = sizeof(label_statement_t),
263 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
264 [STATEMENT_WHILE] = sizeof(while_statement_t),
265 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
266 [STATEMENT_FOR] = sizeof(for_statement_t),
267 [STATEMENT_ASM] = sizeof(asm_statement_t),
268 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
269 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
271 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
272 assert(sizes[kind] != 0);
277 * Returns the size of an expression node.
279 * @param kind the expression kind
281 static size_t get_expression_struct_size(expression_kind_t kind)
283 static const size_t sizes[] = {
284 [EXPR_INVALID] = sizeof(expression_base_t),
285 [EXPR_REFERENCE] = sizeof(reference_expression_t),
286 [EXPR_CONST] = sizeof(const_expression_t),
287 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
288 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
289 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
290 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
291 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
292 [EXPR_CALL] = sizeof(call_expression_t),
293 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
294 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
295 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
296 [EXPR_SELECT] = sizeof(select_expression_t),
297 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
298 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
299 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
300 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
301 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
302 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
303 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
304 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
305 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
306 [EXPR_VA_START] = sizeof(va_start_expression_t),
307 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
308 [EXPR_STATEMENT] = sizeof(statement_expression_t),
310 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
311 return sizes[EXPR_UNARY_FIRST];
313 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
314 return sizes[EXPR_BINARY_FIRST];
316 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
317 assert(sizes[kind] != 0);
322 * Allocate a statement node of given kind and initialize all
325 static statement_t *allocate_statement_zero(statement_kind_t kind)
327 size_t size = get_statement_struct_size(kind);
328 statement_t *res = allocate_ast_zero(size);
330 res->base.kind = kind;
331 res->base.parent = current_parent;
336 * Allocate an expression node of given kind and initialize all
339 static expression_t *allocate_expression_zero(expression_kind_t kind)
341 size_t size = get_expression_struct_size(kind);
342 expression_t *res = allocate_ast_zero(size);
344 res->base.kind = kind;
345 res->base.type = type_error_type;
350 * Creates a new invalid expression.
352 static expression_t *create_invalid_expression(void)
354 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
355 expression->base.source_position = token.source_position;
360 * Creates a new invalid statement.
362 static statement_t *create_invalid_statement(void)
364 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
365 statement->base.source_position = token.source_position;
370 * Allocate a new empty statement.
372 static statement_t *create_empty_statement(void)
374 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
375 statement->base.source_position = token.source_position;
380 * Returns the size of a type node.
382 * @param kind the type kind
384 static size_t get_type_struct_size(type_kind_t kind)
386 static const size_t sizes[] = {
387 [TYPE_ATOMIC] = sizeof(atomic_type_t),
388 [TYPE_COMPLEX] = sizeof(complex_type_t),
389 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
390 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
391 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
392 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
393 [TYPE_ENUM] = sizeof(enum_type_t),
394 [TYPE_FUNCTION] = sizeof(function_type_t),
395 [TYPE_POINTER] = sizeof(pointer_type_t),
396 [TYPE_ARRAY] = sizeof(array_type_t),
397 [TYPE_BUILTIN] = sizeof(builtin_type_t),
398 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
399 [TYPE_TYPEOF] = sizeof(typeof_type_t),
401 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
402 assert(kind <= TYPE_TYPEOF);
403 assert(sizes[kind] != 0);
408 * Allocate a type node of given kind and initialize all
411 * @param kind type kind to allocate
412 * @param source_position the source position of the type definition
414 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
416 size_t size = get_type_struct_size(kind);
417 type_t *res = obstack_alloc(type_obst, size);
418 memset(res, 0, size);
420 res->base.kind = kind;
421 res->base.source_position = *source_position;
426 * Returns the size of an initializer node.
428 * @param kind the initializer kind
430 static size_t get_initializer_size(initializer_kind_t kind)
432 static const size_t sizes[] = {
433 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
434 [INITIALIZER_STRING] = sizeof(initializer_string_t),
435 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
436 [INITIALIZER_LIST] = sizeof(initializer_list_t),
437 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
439 assert(kind < sizeof(sizes) / sizeof(*sizes));
440 assert(sizes[kind] != 0);
445 * Allocate an initializer node of given kind and initialize all
448 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
450 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
457 * Free a type from the type obstack.
459 static void free_type(void *type)
461 obstack_free(type_obst, type);
465 * Returns the index of the top element of the environment stack.
467 static size_t environment_top(void)
469 return ARR_LEN(environment_stack);
473 * Returns the index of the top element of the label stack.
475 static size_t label_top(void)
477 return ARR_LEN(label_stack);
481 * Return the next token.
483 static inline void next_token(void)
485 token = lookahead_buffer[lookahead_bufpos];
486 lookahead_buffer[lookahead_bufpos] = lexer_token;
489 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
492 print_token(stderr, &token);
493 fprintf(stderr, "\n");
498 * Return the next token with a given lookahead.
500 static inline const token_t *look_ahead(int num)
502 assert(num > 0 && num <= MAX_LOOKAHEAD);
503 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
504 return &lookahead_buffer[pos];
508 * Adds a token to the token anchor set (a multi-set).
510 static void add_anchor_token(int token_type)
512 assert(0 <= token_type && token_type < T_LAST_TOKEN);
513 ++token_anchor_set[token_type];
516 static int save_and_reset_anchor_state(int token_type)
518 assert(0 <= token_type && token_type < T_LAST_TOKEN);
519 int count = token_anchor_set[token_type];
520 token_anchor_set[token_type] = 0;
524 static void restore_anchor_state(int token_type, int count)
526 assert(0 <= token_type && token_type < T_LAST_TOKEN);
527 token_anchor_set[token_type] = count;
531 * Remove a token from the token anchor set (a multi-set).
533 static void rem_anchor_token(int token_type)
535 assert(0 <= token_type && token_type < T_LAST_TOKEN);
536 --token_anchor_set[token_type];
539 static bool at_anchor(void)
543 return token_anchor_set[token.type];
547 * Eat tokens until a matching token is found.
549 static void eat_until_matching_token(int type)
553 case '(': end_token = ')'; break;
554 case '{': end_token = '}'; break;
555 case '[': end_token = ']'; break;
556 default: end_token = type; break;
559 unsigned parenthesis_count = 0;
560 unsigned brace_count = 0;
561 unsigned bracket_count = 0;
562 while (token.type != end_token ||
563 parenthesis_count != 0 ||
565 bracket_count != 0) {
566 switch (token.type) {
568 case '(': ++parenthesis_count; break;
569 case '{': ++brace_count; break;
570 case '[': ++bracket_count; break;
573 if (parenthesis_count > 0)
583 if (bracket_count > 0)
586 if (token.type == end_token &&
587 parenthesis_count == 0 &&
601 * Eat input tokens until an anchor is found.
603 static void eat_until_anchor(void)
605 if (token.type == T_EOF)
607 while (token_anchor_set[token.type] == 0) {
608 if (token.type == '(' || token.type == '{' || token.type == '[')
609 eat_until_matching_token(token.type);
610 if (token.type == T_EOF)
616 static void eat_block(void)
618 eat_until_matching_token('{');
619 if (token.type == '}')
624 * eat all token until a ';' is reached or a stop token is found.
626 static void eat_statement(void)
628 eat_until_matching_token(';');
629 if (token.type == ';')
633 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
636 * Report a parse error because an expected token was not found.
639 #if defined __GNUC__ && __GNUC__ >= 4
640 __attribute__((sentinel))
642 void parse_error_expected(const char *message, ...)
644 if (message != NULL) {
645 errorf(HERE, "%s", message);
648 va_start(ap, message);
649 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
654 * Report a type error.
656 static void type_error(const char *msg, const source_position_t *source_position,
659 errorf(source_position, "%s, but found type '%T'", msg, type);
663 * Report an incompatible type.
665 static void type_error_incompatible(const char *msg,
666 const source_position_t *source_position, type_t *type1, type_t *type2)
668 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
673 * Expect the the current token is the expected token.
674 * If not, generate an error, eat the current statement,
675 * and goto the end_error label.
677 #define expect(expected) \
679 if (UNLIKELY(token.type != (expected))) { \
680 parse_error_expected(NULL, (expected), NULL); \
681 add_anchor_token(expected); \
682 eat_until_anchor(); \
683 if (token.type == expected) \
685 rem_anchor_token(expected); \
691 static void set_scope(scope_t *new_scope)
694 scope->last_declaration = last_declaration;
698 last_declaration = new_scope->last_declaration;
702 * Search a symbol in a given namespace and returns its declaration or
703 * NULL if this symbol was not found.
705 static declaration_t *get_declaration(const symbol_t *const symbol,
706 const namespace_t namespc)
708 declaration_t *declaration = symbol->declaration;
709 for( ; declaration != NULL; declaration = declaration->symbol_next) {
710 if (declaration->namespc == namespc)
718 * pushs an environment_entry on the environment stack and links the
719 * corresponding symbol to the new entry
721 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
723 symbol_t *symbol = declaration->symbol;
724 namespace_t namespc = (namespace_t) declaration->namespc;
726 /* replace/add declaration into declaration list of the symbol */
727 declaration_t *iter = symbol->declaration;
729 symbol->declaration = declaration;
731 declaration_t *iter_last = NULL;
732 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
733 /* replace an entry? */
734 if (iter->namespc == namespc) {
735 if (iter_last == NULL) {
736 symbol->declaration = declaration;
738 iter_last->symbol_next = declaration;
740 declaration->symbol_next = iter->symbol_next;
745 assert(iter_last->symbol_next == NULL);
746 iter_last->symbol_next = declaration;
750 /* remember old declaration */
752 entry.symbol = symbol;
753 entry.old_declaration = iter;
754 entry.namespc = (unsigned short) namespc;
755 ARR_APP1(stack_entry_t, *stack_ptr, entry);
758 static void environment_push(declaration_t *declaration)
760 assert(declaration->source_position.input_name != NULL);
761 assert(declaration->parent_scope != NULL);
762 stack_push(&environment_stack, declaration);
766 * Push a declaration of the label stack.
768 * @param declaration the declaration
770 static void label_push(declaration_t *declaration)
772 declaration->parent_scope = ¤t_function->scope;
773 stack_push(&label_stack, declaration);
777 * pops symbols from the environment stack until @p new_top is the top element
779 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
781 stack_entry_t *stack = *stack_ptr;
782 size_t top = ARR_LEN(stack);
785 assert(new_top <= top);
789 for(i = top; i > new_top; --i) {
790 stack_entry_t *entry = &stack[i - 1];
792 declaration_t *old_declaration = entry->old_declaration;
793 symbol_t *symbol = entry->symbol;
794 namespace_t namespc = (namespace_t)entry->namespc;
796 /* replace/remove declaration */
797 declaration_t *declaration = symbol->declaration;
798 assert(declaration != NULL);
799 if (declaration->namespc == namespc) {
800 if (old_declaration == NULL) {
801 symbol->declaration = declaration->symbol_next;
803 symbol->declaration = old_declaration;
806 declaration_t *iter_last = declaration;
807 declaration_t *iter = declaration->symbol_next;
808 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
809 /* replace an entry? */
810 if (iter->namespc == namespc) {
811 assert(iter_last != NULL);
812 iter_last->symbol_next = old_declaration;
813 if (old_declaration != NULL) {
814 old_declaration->symbol_next = iter->symbol_next;
819 assert(iter != NULL);
823 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
826 static void environment_pop_to(size_t new_top)
828 stack_pop_to(&environment_stack, new_top);
832 * Pop all entries on the label stack until the new_top
835 * @param new_top the new stack top
837 static void label_pop_to(size_t new_top)
839 stack_pop_to(&label_stack, new_top);
843 static atomic_type_kind_t get_rank(const type_t *type)
845 assert(!is_typeref(type));
846 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
847 * and esp. footnote 108). However we can't fold constants (yet), so we
848 * can't decide whether unsigned int is possible, while int always works.
849 * (unsigned int would be preferable when possible... for stuff like
850 * struct { enum { ... } bla : 4; } ) */
851 if (type->kind == TYPE_ENUM)
852 return ATOMIC_TYPE_INT;
854 assert(type->kind == TYPE_ATOMIC);
855 return type->atomic.akind;
858 static type_t *promote_integer(type_t *type)
860 if (type->kind == TYPE_BITFIELD)
861 type = type->bitfield.base_type;
863 if (get_rank(type) < ATOMIC_TYPE_INT)
870 * Create a cast expression.
872 * @param expression the expression to cast
873 * @param dest_type the destination type
875 static expression_t *create_cast_expression(expression_t *expression,
878 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
880 cast->unary.value = expression;
881 cast->base.type = dest_type;
887 * Check if a given expression represents the 0 pointer constant.
889 static bool is_null_pointer_constant(const expression_t *expression)
891 /* skip void* cast */
892 if (expression->kind == EXPR_UNARY_CAST
893 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
894 expression = expression->unary.value;
897 /* TODO: not correct yet, should be any constant integer expression
898 * which evaluates to 0 */
899 if (expression->kind != EXPR_CONST)
902 type_t *const type = skip_typeref(expression->base.type);
903 if (!is_type_integer(type))
906 return expression->conste.v.int_value == 0;
910 * Create an implicit cast expression.
912 * @param expression the expression to cast
913 * @param dest_type the destination type
915 static expression_t *create_implicit_cast(expression_t *expression,
918 type_t *const source_type = expression->base.type;
920 if (source_type == dest_type)
923 return create_cast_expression(expression, dest_type);
926 typedef enum assign_error_t {
928 ASSIGN_ERROR_INCOMPATIBLE,
929 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
930 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
931 ASSIGN_WARNING_POINTER_FROM_INT,
932 ASSIGN_WARNING_INT_FROM_POINTER
935 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
936 const expression_t *const right,
938 const source_position_t *source_position)
940 type_t *const orig_type_right = right->base.type;
941 type_t *const type_left = skip_typeref(orig_type_left);
942 type_t *const type_right = skip_typeref(orig_type_right);
947 case ASSIGN_ERROR_INCOMPATIBLE:
948 errorf(source_position,
949 "destination type '%T' in %s is incompatible with type '%T'",
950 orig_type_left, context, orig_type_right);
953 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
954 type_t *points_to_left
955 = skip_typeref(type_left->pointer.points_to);
956 type_t *points_to_right
957 = skip_typeref(type_right->pointer.points_to);
959 /* the left type has all qualifiers from the right type */
960 unsigned missing_qualifiers
961 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
962 errorf(source_position,
963 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
964 orig_type_left, context, orig_type_right, missing_qualifiers);
968 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
969 warningf(source_position,
970 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
971 orig_type_left, context, right, orig_type_right);
974 case ASSIGN_WARNING_POINTER_FROM_INT:
975 warningf(source_position,
976 "%s makes integer '%T' from pointer '%T' without a cast",
977 context, orig_type_left, orig_type_right);
980 case ASSIGN_WARNING_INT_FROM_POINTER:
981 warningf(source_position,
982 "%s makes integer '%T' from pointer '%T' without a cast",
983 context, orig_type_left, orig_type_right);
987 panic("invalid error value");
991 /** Implements the rules from § 6.5.16.1 */
992 static assign_error_t semantic_assign(type_t *orig_type_left,
993 const expression_t *const right)
995 type_t *const orig_type_right = right->base.type;
996 type_t *const type_left = skip_typeref(orig_type_left);
997 type_t *const type_right = skip_typeref(orig_type_right);
999 if (is_type_pointer(type_left)) {
1000 if (is_null_pointer_constant(right)) {
1001 return ASSIGN_SUCCESS;
1002 } else if (is_type_pointer(type_right)) {
1003 type_t *points_to_left
1004 = skip_typeref(type_left->pointer.points_to);
1005 type_t *points_to_right
1006 = skip_typeref(type_right->pointer.points_to);
1008 /* the left type has all qualifiers from the right type */
1009 unsigned missing_qualifiers
1010 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1011 if (missing_qualifiers != 0) {
1012 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1015 points_to_left = get_unqualified_type(points_to_left);
1016 points_to_right = get_unqualified_type(points_to_right);
1018 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1019 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1020 return ASSIGN_SUCCESS;
1023 if (!types_compatible(points_to_left, points_to_right)) {
1024 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1027 return ASSIGN_SUCCESS;
1028 } else if (is_type_integer(type_right)) {
1029 return ASSIGN_WARNING_POINTER_FROM_INT;
1031 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1032 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1033 && is_type_pointer(type_right))) {
1034 return ASSIGN_SUCCESS;
1035 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1036 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1037 type_t *const unqual_type_left = get_unqualified_type(type_left);
1038 type_t *const unqual_type_right = get_unqualified_type(type_right);
1039 if (types_compatible(unqual_type_left, unqual_type_right)) {
1040 return ASSIGN_SUCCESS;
1042 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1043 return ASSIGN_WARNING_INT_FROM_POINTER;
1046 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1047 return ASSIGN_SUCCESS;
1049 return ASSIGN_ERROR_INCOMPATIBLE;
1052 static expression_t *parse_constant_expression(void)
1054 /* start parsing at precedence 7 (conditional expression) */
1055 expression_t *result = parse_sub_expression(7);
1057 if (!is_constant_expression(result)) {
1058 errorf(&result->base.source_position,
1059 "expression '%E' is not constant\n", result);
1065 static expression_t *parse_assignment_expression(void)
1067 /* start parsing at precedence 2 (assignment expression) */
1068 return parse_sub_expression(2);
1071 static type_t *make_global_typedef(const char *name, type_t *type)
1073 symbol_t *const symbol = symbol_table_insert(name);
1075 declaration_t *const declaration = allocate_declaration_zero();
1076 declaration->namespc = NAMESPACE_NORMAL;
1077 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1078 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1079 declaration->type = type;
1080 declaration->symbol = symbol;
1081 declaration->source_position = builtin_source_position;
1083 record_declaration(declaration);
1085 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1086 typedef_type->typedeft.declaration = declaration;
1088 return typedef_type;
1091 static string_t parse_string_literals(void)
1093 assert(token.type == T_STRING_LITERAL);
1094 string_t result = token.v.string;
1098 while (token.type == T_STRING_LITERAL) {
1099 result = concat_strings(&result, &token.v.string);
1106 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1107 [GNU_AK_CONST] = "const",
1108 [GNU_AK_VOLATILE] = "volatile",
1109 [GNU_AK_CDECL] = "cdecl",
1110 [GNU_AK_STDCALL] = "stdcall",
1111 [GNU_AK_FASTCALL] = "fastcall",
1112 [GNU_AK_DEPRECATED] = "deprecated",
1113 [GNU_AK_NOINLINE] = "noinline",
1114 [GNU_AK_NORETURN] = "noreturn",
1115 [GNU_AK_NAKED] = "naked",
1116 [GNU_AK_PURE] = "pure",
1117 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1118 [GNU_AK_MALLOC] = "malloc",
1119 [GNU_AK_WEAK] = "weak",
1120 [GNU_AK_CONSTRUCTOR] = "constructor",
1121 [GNU_AK_DESTRUCTOR] = "destructor",
1122 [GNU_AK_NOTHROW] = "nothrow",
1123 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1124 [GNU_AK_COMMON] = "common",
1125 [GNU_AK_NOCOMMON] = "nocommon",
1126 [GNU_AK_PACKED] = "packed",
1127 [GNU_AK_SHARED] = "shared",
1128 [GNU_AK_NOTSHARED] = "notshared",
1129 [GNU_AK_USED] = "used",
1130 [GNU_AK_UNUSED] = "unused",
1131 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1132 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1133 [GNU_AK_LONGCALL] = "longcall",
1134 [GNU_AK_SHORTCALL] = "shortcall",
1135 [GNU_AK_LONG_CALL] = "long_call",
1136 [GNU_AK_SHORT_CALL] = "short_call",
1137 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1138 [GNU_AK_INTERRUPT] = "interrupt",
1139 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1140 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1141 [GNU_AK_NESTING] = "nesting",
1142 [GNU_AK_NEAR] = "near",
1143 [GNU_AK_FAR] = "far",
1144 [GNU_AK_SIGNAL] = "signal",
1145 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1146 [GNU_AK_TINY_DATA] = "tiny_data",
1147 [GNU_AK_SAVEALL] = "saveall",
1148 [GNU_AK_FLATTEN] = "flatten",
1149 [GNU_AK_SSEREGPARM] = "sseregparm",
1150 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1151 [GNU_AK_RETURN_TWICE] = "return_twice",
1152 [GNU_AK_MAY_ALIAS] = "may_alias",
1153 [GNU_AK_MS_STRUCT] = "ms_struct",
1154 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1155 [GNU_AK_DLLIMPORT] = "dllimport",
1156 [GNU_AK_DLLEXPORT] = "dllexport",
1157 [GNU_AK_ALIGNED] = "aligned",
1158 [GNU_AK_ALIAS] = "alias",
1159 [GNU_AK_SECTION] = "section",
1160 [GNU_AK_FORMAT] = "format",
1161 [GNU_AK_FORMAT_ARG] = "format_arg",
1162 [GNU_AK_WEAKREF] = "weakref",
1163 [GNU_AK_NONNULL] = "nonnull",
1164 [GNU_AK_TLS_MODEL] = "tls_model",
1165 [GNU_AK_VISIBILITY] = "visibility",
1166 [GNU_AK_REGPARM] = "regparm",
1167 [GNU_AK_MODE] = "mode",
1168 [GNU_AK_MODEL] = "model",
1169 [GNU_AK_TRAP_EXIT] = "trap_exit",
1170 [GNU_AK_SP_SWITCH] = "sp_switch",
1171 [GNU_AK_SENTINEL] = "sentinel"
1175 * compare two string, ignoring double underscores on the second.
1177 static int strcmp_underscore(const char *s1, const char *s2)
1179 if (s2[0] == '_' && s2[1] == '_') {
1180 size_t len2 = strlen(s2);
1181 size_t len1 = strlen(s1);
1182 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1183 return strncmp(s1, s2+2, len2-4);
1187 return strcmp(s1, s2);
1191 * Allocate a new gnu temporal attribute.
1193 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1195 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1196 attribute->kind = kind;
1197 attribute->next = NULL;
1198 attribute->invalid = false;
1199 attribute->have_arguments = false;
1205 * parse one constant expression argument.
1207 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1209 expression_t *expression;
1210 add_anchor_token(')');
1211 expression = parse_constant_expression();
1212 rem_anchor_token(')');
1214 attribute->u.argument = fold_constant(expression);
1217 attribute->invalid = true;
1221 * parse a list of constant expressions arguments.
1223 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1225 argument_list_t **list = &attribute->u.arguments;
1226 argument_list_t *entry;
1227 expression_t *expression;
1228 add_anchor_token(')');
1229 add_anchor_token(',');
1231 expression = parse_constant_expression();
1232 entry = obstack_alloc(&temp_obst, sizeof(entry));
1233 entry->argument = fold_constant(expression);
1236 list = &entry->next;
1237 if (token.type != ',')
1241 rem_anchor_token(',');
1242 rem_anchor_token(')');
1246 attribute->invalid = true;
1250 * parse one string literal argument.
1252 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1255 add_anchor_token('(');
1256 if (token.type != T_STRING_LITERAL) {
1257 parse_error_expected("while parsing attribute directive",
1258 T_STRING_LITERAL, NULL);
1261 *string = parse_string_literals();
1262 rem_anchor_token('(');
1266 attribute->invalid = true;
1270 * parse one tls model.
1272 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1274 static const char *const tls_models[] = {
1280 string_t string = { NULL, 0 };
1281 parse_gnu_attribute_string_arg(attribute, &string);
1282 if (string.begin != NULL) {
1283 for(size_t i = 0; i < 4; ++i) {
1284 if (strcmp(tls_models[i], string.begin) == 0) {
1285 attribute->u.value = i;
1289 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1291 attribute->invalid = true;
1295 * parse one tls model.
1297 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1299 static const char *const visibilities[] = {
1305 string_t string = { NULL, 0 };
1306 parse_gnu_attribute_string_arg(attribute, &string);
1307 if (string.begin != NULL) {
1308 for(size_t i = 0; i < 4; ++i) {
1309 if (strcmp(visibilities[i], string.begin) == 0) {
1310 attribute->u.value = i;
1314 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1316 attribute->invalid = true;
1320 * parse one (code) model.
1322 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1324 static const char *const visibilities[] = {
1329 string_t string = { NULL, 0 };
1330 parse_gnu_attribute_string_arg(attribute, &string);
1331 if (string.begin != NULL) {
1332 for(int i = 0; i < 3; ++i) {
1333 if (strcmp(visibilities[i], string.begin) == 0) {
1334 attribute->u.value = i;
1338 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1340 attribute->invalid = true;
1343 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1345 /* TODO: find out what is allowed here... */
1347 /* at least: byte, word, pointer, list of machine modes
1348 * __XXX___ is interpreted as XXX */
1349 add_anchor_token(')');
1351 if (token.type != T_IDENTIFIER) {
1352 expect(T_IDENTIFIER);
1355 /* This isn't really correct, the backend should provide a list of machine
1356 * specific modes (according to gcc philosophy that is...) */
1357 const char *symbol_str = token.v.symbol->string;
1358 if (strcmp_underscore("QI", symbol_str) == 0 ||
1359 strcmp_underscore("byte", symbol_str) == 0) {
1360 attribute->u.akind = ATOMIC_TYPE_CHAR;
1361 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1362 attribute->u.akind = ATOMIC_TYPE_SHORT;
1363 } else if (strcmp_underscore("SI", symbol_str) == 0
1364 || strcmp_underscore("word", symbol_str) == 0
1365 || strcmp_underscore("pointer", symbol_str) == 0) {
1366 attribute->u.akind = ATOMIC_TYPE_INT;
1367 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1368 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1370 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1371 attribute->invalid = true;
1375 rem_anchor_token(')');
1379 attribute->invalid = true;
1383 * parse one interrupt argument.
1385 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1387 static const char *const interrupts[] = {
1394 string_t string = { NULL, 0 };
1395 parse_gnu_attribute_string_arg(attribute, &string);
1396 if (string.begin != NULL) {
1397 for(size_t i = 0; i < 5; ++i) {
1398 if (strcmp(interrupts[i], string.begin) == 0) {
1399 attribute->u.value = i;
1403 errorf(HERE, "'%s' is not an interrupt", string.begin);
1405 attribute->invalid = true;
1409 * parse ( identifier, const expression, const expression )
1411 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1413 static const char *const format_names[] = {
1421 if (token.type != T_IDENTIFIER) {
1422 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1425 const char *name = token.v.symbol->string;
1426 for(i = 0; i < 4; ++i) {
1427 if (strcmp_underscore(format_names[i], name) == 0)
1431 if (warning.attribute)
1432 warningf(HERE, "'%s' is an unrecognized format function type", name);
1437 add_anchor_token(')');
1438 add_anchor_token(',');
1439 parse_constant_expression();
1440 rem_anchor_token(',');
1441 rem_anchor_token('(');
1444 add_anchor_token(')');
1445 parse_constant_expression();
1446 rem_anchor_token('(');
1450 attribute->u.value = true;
1453 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1455 if (!attribute->have_arguments)
1458 /* should have no arguments */
1459 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1460 eat_until_matching_token('(');
1461 /* we have already consumed '(', so we stop before ')', eat it */
1463 attribute->invalid = true;
1467 * Parse one GNU attribute.
1469 * Note that attribute names can be specified WITH or WITHOUT
1470 * double underscores, ie const or __const__.
1472 * The following attributes are parsed without arguments
1497 * no_instrument_function
1498 * warn_unused_result
1515 * externally_visible
1523 * The following attributes are parsed with arguments
1524 * aligned( const expression )
1525 * alias( string literal )
1526 * section( string literal )
1527 * format( identifier, const expression, const expression )
1528 * format_arg( const expression )
1529 * tls_model( string literal )
1530 * visibility( string literal )
1531 * regparm( const expression )
1532 * model( string leteral )
1533 * trap_exit( const expression )
1534 * sp_switch( string literal )
1536 * The following attributes might have arguments
1537 * weak_ref( string literal )
1538 * non_null( const expression // ',' )
1539 * interrupt( string literal )
1540 * sentinel( constant expression )
1542 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1544 gnu_attribute_t *head = *attributes;
1545 gnu_attribute_t *last = *attributes;
1546 decl_modifiers_t modifiers = 0;
1547 gnu_attribute_t *attribute;
1549 eat(T___attribute__);
1553 if (token.type != ')') {
1554 /* find the end of the list */
1556 while (last->next != NULL)
1560 /* non-empty attribute list */
1563 if (token.type == T_const) {
1565 } else if (token.type == T_volatile) {
1567 } else if (token.type == T_cdecl) {
1568 /* __attribute__((cdecl)), WITH ms mode */
1570 } else if (token.type == T_IDENTIFIER) {
1571 const symbol_t *sym = token.v.symbol;
1574 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1581 for(i = 0; i < GNU_AK_LAST; ++i) {
1582 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1585 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1588 if (kind == GNU_AK_LAST) {
1589 if (warning.attribute)
1590 warningf(HERE, "'%s' attribute directive ignored", name);
1592 /* skip possible arguments */
1593 if (token.type == '(') {
1594 eat_until_matching_token(')');
1597 /* check for arguments */
1598 attribute = allocate_gnu_attribute(kind);
1599 if (token.type == '(') {
1601 if (token.type == ')') {
1602 /* empty args are allowed */
1605 attribute->have_arguments = true;
1610 case GNU_AK_VOLATILE:
1615 case GNU_AK_NOCOMMON:
1617 case GNU_AK_NOTSHARED:
1618 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1619 case GNU_AK_WARN_UNUSED_RESULT:
1620 case GNU_AK_LONGCALL:
1621 case GNU_AK_SHORTCALL:
1622 case GNU_AK_LONG_CALL:
1623 case GNU_AK_SHORT_CALL:
1624 case GNU_AK_FUNCTION_VECTOR:
1625 case GNU_AK_INTERRUPT_HANDLER:
1626 case GNU_AK_NMI_HANDLER:
1627 case GNU_AK_NESTING:
1631 case GNU_AK_EIGTHBIT_DATA:
1632 case GNU_AK_TINY_DATA:
1633 case GNU_AK_SAVEALL:
1634 case GNU_AK_FLATTEN:
1635 case GNU_AK_SSEREGPARM:
1636 case GNU_AK_EXTERNALLY_VISIBLE:
1637 case GNU_AK_RETURN_TWICE:
1638 case GNU_AK_MAY_ALIAS:
1639 case GNU_AK_MS_STRUCT:
1640 case GNU_AK_GCC_STRUCT:
1643 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1644 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1645 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1646 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1647 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1648 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1649 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1650 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1651 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1652 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1653 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1654 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1655 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1656 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1657 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1658 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1659 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1661 case GNU_AK_ALIGNED:
1662 /* __align__ may be used without an argument */
1663 if (attribute->have_arguments) {
1664 parse_gnu_attribute_const_arg(attribute);
1668 case GNU_AK_FORMAT_ARG:
1669 case GNU_AK_REGPARM:
1670 case GNU_AK_TRAP_EXIT:
1671 if (!attribute->have_arguments) {
1672 /* should have arguments */
1673 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1674 attribute->invalid = true;
1676 parse_gnu_attribute_const_arg(attribute);
1679 case GNU_AK_SECTION:
1680 case GNU_AK_SP_SWITCH:
1681 if (!attribute->have_arguments) {
1682 /* should have arguments */
1683 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1684 attribute->invalid = true;
1686 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1689 if (!attribute->have_arguments) {
1690 /* should have arguments */
1691 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1692 attribute->invalid = true;
1694 parse_gnu_attribute_format_args(attribute);
1696 case GNU_AK_WEAKREF:
1697 /* may have one string argument */
1698 if (attribute->have_arguments)
1699 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1701 case GNU_AK_NONNULL:
1702 if (attribute->have_arguments)
1703 parse_gnu_attribute_const_arg_list(attribute);
1705 case GNU_AK_TLS_MODEL:
1706 if (!attribute->have_arguments) {
1707 /* should have arguments */
1708 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1710 parse_gnu_attribute_tls_model_arg(attribute);
1712 case GNU_AK_VISIBILITY:
1713 if (!attribute->have_arguments) {
1714 /* should have arguments */
1715 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1717 parse_gnu_attribute_visibility_arg(attribute);
1720 if (!attribute->have_arguments) {
1721 /* should have arguments */
1722 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1724 parse_gnu_attribute_model_arg(attribute);
1728 if (!attribute->have_arguments) {
1729 /* should have arguments */
1730 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1732 parse_gnu_attribute_mode_arg(attribute);
1735 case GNU_AK_INTERRUPT:
1736 /* may have one string argument */
1737 if (attribute->have_arguments)
1738 parse_gnu_attribute_interrupt_arg(attribute);
1740 case GNU_AK_SENTINEL:
1741 /* may have one string argument */
1742 if (attribute->have_arguments)
1743 parse_gnu_attribute_const_arg(attribute);
1746 /* already handled */
1750 check_no_argument(attribute, name);
1753 if (attribute != NULL) {
1755 last->next = attribute;
1758 head = last = attribute;
1762 if (token.type != ',')
1776 * Parse GNU attributes.
1778 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1780 decl_modifiers_t modifiers = 0;
1783 switch(token.type) {
1784 case T___attribute__:
1785 modifiers |= parse_gnu_attribute(attributes);
1791 if (token.type != T_STRING_LITERAL) {
1792 parse_error_expected("while parsing assembler attribute",
1793 T_STRING_LITERAL, NULL);
1794 eat_until_matching_token('(');
1797 parse_string_literals();
1802 case T_cdecl: modifiers |= DM_CDECL; break;
1803 case T__fastcall: modifiers |= DM_FASTCALL; break;
1804 case T__stdcall: modifiers |= DM_STDCALL; break;
1807 /* TODO record modifier */
1808 warningf(HERE, "Ignoring declaration modifier %K", &token);
1812 default: return modifiers;
1819 static designator_t *parse_designation(void)
1821 designator_t *result = NULL;
1822 designator_t *last = NULL;
1825 designator_t *designator;
1826 switch(token.type) {
1828 designator = allocate_ast_zero(sizeof(designator[0]));
1829 designator->source_position = token.source_position;
1831 add_anchor_token(']');
1832 designator->array_index = parse_constant_expression();
1833 rem_anchor_token(']');
1837 designator = allocate_ast_zero(sizeof(designator[0]));
1838 designator->source_position = token.source_position;
1840 if (token.type != T_IDENTIFIER) {
1841 parse_error_expected("while parsing designator",
1842 T_IDENTIFIER, NULL);
1845 designator->symbol = token.v.symbol;
1853 assert(designator != NULL);
1855 last->next = designator;
1857 result = designator;
1865 static initializer_t *initializer_from_string(array_type_t *type,
1866 const string_t *const string)
1868 /* TODO: check len vs. size of array type */
1871 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1872 initializer->string.string = *string;
1877 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1878 wide_string_t *const string)
1880 /* TODO: check len vs. size of array type */
1883 initializer_t *const initializer =
1884 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1885 initializer->wide_string.string = *string;
1891 * Build an initializer from a given expression.
1893 static initializer_t *initializer_from_expression(type_t *orig_type,
1894 expression_t *expression)
1896 /* TODO check that expression is a constant expression */
1898 /* § 6.7.8.14/15 char array may be initialized by string literals */
1899 type_t *type = skip_typeref(orig_type);
1900 type_t *expr_type_orig = expression->base.type;
1901 type_t *expr_type = skip_typeref(expr_type_orig);
1902 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1903 array_type_t *const array_type = &type->array;
1904 type_t *const element_type = skip_typeref(array_type->element_type);
1906 if (element_type->kind == TYPE_ATOMIC) {
1907 atomic_type_kind_t akind = element_type->atomic.akind;
1908 switch (expression->kind) {
1909 case EXPR_STRING_LITERAL:
1910 if (akind == ATOMIC_TYPE_CHAR
1911 || akind == ATOMIC_TYPE_SCHAR
1912 || akind == ATOMIC_TYPE_UCHAR) {
1913 return initializer_from_string(array_type,
1914 &expression->string.value);
1917 case EXPR_WIDE_STRING_LITERAL: {
1918 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1919 if (get_unqualified_type(element_type) == bare_wchar_type) {
1920 return initializer_from_wide_string(array_type,
1921 &expression->wide_string.value);
1931 assign_error_t error = semantic_assign(type, expression);
1932 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1934 report_assign_error(error, type, expression, "initializer",
1935 &expression->base.source_position);
1937 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1938 result->value.value = create_implicit_cast(expression, type);
1944 * Checks if a given expression can be used as an constant initializer.
1946 static bool is_initializer_constant(const expression_t *expression)
1948 return is_constant_expression(expression)
1949 || is_address_constant(expression);
1953 * Parses an scalar initializer.
1955 * § 6.7.8.11; eat {} without warning
1957 static initializer_t *parse_scalar_initializer(type_t *type,
1958 bool must_be_constant)
1960 /* there might be extra {} hierarchies */
1962 if (token.type == '{') {
1963 warningf(HERE, "extra curly braces around scalar initializer");
1967 } while (token.type == '{');
1970 expression_t *expression = parse_assignment_expression();
1971 if (must_be_constant && !is_initializer_constant(expression)) {
1972 errorf(&expression->base.source_position,
1973 "Initialisation expression '%E' is not constant\n",
1977 initializer_t *initializer = initializer_from_expression(type, expression);
1979 if (initializer == NULL) {
1980 errorf(&expression->base.source_position,
1981 "expression '%E' (type '%T') doesn't match expected type '%T'",
1982 expression, expression->base.type, type);
1987 bool additional_warning_displayed = false;
1988 while (braces > 0) {
1989 if (token.type == ',') {
1992 if (token.type != '}') {
1993 if (!additional_warning_displayed) {
1994 warningf(HERE, "additional elements in scalar initializer");
1995 additional_warning_displayed = true;
2006 * An entry in the type path.
2008 typedef struct type_path_entry_t type_path_entry_t;
2009 struct type_path_entry_t {
2010 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2012 size_t index; /**< For array types: the current index. */
2013 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2018 * A type path expression a position inside compound or array types.
2020 typedef struct type_path_t type_path_t;
2021 struct type_path_t {
2022 type_path_entry_t *path; /**< An flexible array containing the current path. */
2023 type_t *top_type; /**< type of the element the path points */
2024 size_t max_index; /**< largest index in outermost array */
2028 * Prints a type path for debugging.
2030 static __attribute__((unused)) void debug_print_type_path(
2031 const type_path_t *path)
2033 size_t len = ARR_LEN(path->path);
2035 for(size_t i = 0; i < len; ++i) {
2036 const type_path_entry_t *entry = & path->path[i];
2038 type_t *type = skip_typeref(entry->type);
2039 if (is_type_compound(type)) {
2040 /* in gcc mode structs can have no members */
2041 if (entry->v.compound_entry == NULL) {
2045 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2046 } else if (is_type_array(type)) {
2047 fprintf(stderr, "[%zu]", entry->v.index);
2049 fprintf(stderr, "-INVALID-");
2052 if (path->top_type != NULL) {
2053 fprintf(stderr, " (");
2054 print_type(path->top_type);
2055 fprintf(stderr, ")");
2060 * Return the top type path entry, ie. in a path
2061 * (type).a.b returns the b.
2063 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2065 size_t len = ARR_LEN(path->path);
2067 return &path->path[len-1];
2071 * Enlarge the type path by an (empty) element.
2073 static type_path_entry_t *append_to_type_path(type_path_t *path)
2075 size_t len = ARR_LEN(path->path);
2076 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2078 type_path_entry_t *result = & path->path[len];
2079 memset(result, 0, sizeof(result[0]));
2084 * Descending into a sub-type. Enter the scope of the current
2087 static void descend_into_subtype(type_path_t *path)
2089 type_t *orig_top_type = path->top_type;
2090 type_t *top_type = skip_typeref(orig_top_type);
2092 assert(is_type_compound(top_type) || is_type_array(top_type));
2094 type_path_entry_t *top = append_to_type_path(path);
2095 top->type = top_type;
2097 if (is_type_compound(top_type)) {
2098 declaration_t *declaration = top_type->compound.declaration;
2099 declaration_t *entry = declaration->scope.declarations;
2100 top->v.compound_entry = entry;
2102 if (entry != NULL) {
2103 path->top_type = entry->type;
2105 path->top_type = NULL;
2108 assert(is_type_array(top_type));
2111 path->top_type = top_type->array.element_type;
2116 * Pop an entry from the given type path, ie. returning from
2117 * (type).a.b to (type).a
2119 static void ascend_from_subtype(type_path_t *path)
2121 type_path_entry_t *top = get_type_path_top(path);
2123 path->top_type = top->type;
2125 size_t len = ARR_LEN(path->path);
2126 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2130 * Pop entries from the given type path until the given
2131 * path level is reached.
2133 static void ascend_to(type_path_t *path, size_t top_path_level)
2135 size_t len = ARR_LEN(path->path);
2137 while (len > top_path_level) {
2138 ascend_from_subtype(path);
2139 len = ARR_LEN(path->path);
2143 static bool walk_designator(type_path_t *path, const designator_t *designator,
2144 bool used_in_offsetof)
2146 for( ; designator != NULL; designator = designator->next) {
2147 type_path_entry_t *top = get_type_path_top(path);
2148 type_t *orig_type = top->type;
2150 type_t *type = skip_typeref(orig_type);
2152 if (designator->symbol != NULL) {
2153 symbol_t *symbol = designator->symbol;
2154 if (!is_type_compound(type)) {
2155 if (is_type_valid(type)) {
2156 errorf(&designator->source_position,
2157 "'.%Y' designator used for non-compound type '%T'",
2163 declaration_t *declaration = type->compound.declaration;
2164 declaration_t *iter = declaration->scope.declarations;
2165 for( ; iter != NULL; iter = iter->next) {
2166 if (iter->symbol == symbol) {
2171 errorf(&designator->source_position,
2172 "'%T' has no member named '%Y'", orig_type, symbol);
2175 if (used_in_offsetof) {
2176 type_t *real_type = skip_typeref(iter->type);
2177 if (real_type->kind == TYPE_BITFIELD) {
2178 errorf(&designator->source_position,
2179 "offsetof designator '%Y' may not specify bitfield",
2185 top->type = orig_type;
2186 top->v.compound_entry = iter;
2187 orig_type = iter->type;
2189 expression_t *array_index = designator->array_index;
2190 assert(designator->array_index != NULL);
2192 if (!is_type_array(type)) {
2193 if (is_type_valid(type)) {
2194 errorf(&designator->source_position,
2195 "[%E] designator used for non-array type '%T'",
2196 array_index, orig_type);
2200 if (!is_type_valid(array_index->base.type)) {
2204 long index = fold_constant(array_index);
2205 if (!used_in_offsetof) {
2207 errorf(&designator->source_position,
2208 "array index [%E] must be positive", array_index);
2211 if (type->array.size_constant == true) {
2212 long array_size = type->array.size;
2213 if (index >= array_size) {
2214 errorf(&designator->source_position,
2215 "designator [%E] (%d) exceeds array size %d",
2216 array_index, index, array_size);
2222 top->type = orig_type;
2223 top->v.index = (size_t) index;
2224 orig_type = type->array.element_type;
2226 path->top_type = orig_type;
2228 if (designator->next != NULL) {
2229 descend_into_subtype(path);
2238 static void advance_current_object(type_path_t *path, size_t top_path_level)
2240 type_path_entry_t *top = get_type_path_top(path);
2242 type_t *type = skip_typeref(top->type);
2243 if (is_type_union(type)) {
2244 /* in unions only the first element is initialized */
2245 top->v.compound_entry = NULL;
2246 } else if (is_type_struct(type)) {
2247 declaration_t *entry = top->v.compound_entry;
2249 entry = entry->next;
2250 top->v.compound_entry = entry;
2251 if (entry != NULL) {
2252 path->top_type = entry->type;
2256 assert(is_type_array(type));
2260 if (!type->array.size_constant || top->v.index < type->array.size) {
2265 /* we're past the last member of the current sub-aggregate, try if we
2266 * can ascend in the type hierarchy and continue with another subobject */
2267 size_t len = ARR_LEN(path->path);
2269 if (len > top_path_level) {
2270 ascend_from_subtype(path);
2271 advance_current_object(path, top_path_level);
2273 path->top_type = NULL;
2278 * skip until token is found.
2280 static void skip_until(int type)
2282 while (token.type != type) {
2283 if (token.type == T_EOF)
2290 * skip any {...} blocks until a closing bracket is reached.
2292 static void skip_initializers(void)
2294 if (token.type == '{')
2297 while (token.type != '}') {
2298 if (token.type == T_EOF)
2300 if (token.type == '{') {
2308 static initializer_t *create_empty_initializer(void)
2310 static initializer_t empty_initializer
2311 = { .list = { { INITIALIZER_LIST }, 0 } };
2312 return &empty_initializer;
2316 * Parse a part of an initialiser for a struct or union,
2318 static initializer_t *parse_sub_initializer(type_path_t *path,
2319 type_t *outer_type, size_t top_path_level,
2320 parse_initializer_env_t *env)
2322 if (token.type == '}') {
2323 /* empty initializer */
2324 return create_empty_initializer();
2327 type_t *orig_type = path->top_type;
2328 type_t *type = NULL;
2330 if (orig_type == NULL) {
2331 /* We are initializing an empty compound. */
2333 type = skip_typeref(orig_type);
2335 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2336 * initializers in this case. */
2337 if (!is_type_valid(type)) {
2338 skip_initializers();
2339 return create_empty_initializer();
2343 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2346 designator_t *designator = NULL;
2347 if (token.type == '.' || token.type == '[') {
2348 designator = parse_designation();
2349 goto finish_designator;
2350 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2351 /* GNU-style designator ("identifier: value") */
2352 designator = allocate_ast_zero(sizeof(designator[0]));
2353 designator->source_position = token.source_position;
2354 designator->symbol = token.v.symbol;
2359 /* reset path to toplevel, evaluate designator from there */
2360 ascend_to(path, top_path_level);
2361 if (!walk_designator(path, designator, false)) {
2362 /* can't continue after designation error */
2366 initializer_t *designator_initializer
2367 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2368 designator_initializer->designator.designator = designator;
2369 ARR_APP1(initializer_t*, initializers, designator_initializer);
2371 orig_type = path->top_type;
2372 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2377 if (token.type == '{') {
2378 if (type != NULL && is_type_scalar(type)) {
2379 sub = parse_scalar_initializer(type, env->must_be_constant);
2383 if (env->declaration != NULL) {
2384 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2385 env->declaration->symbol);
2387 errorf(HERE, "extra brace group at end of initializer");
2390 descend_into_subtype(path);
2392 add_anchor_token('}');
2393 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2395 rem_anchor_token('}');
2398 ascend_from_subtype(path);
2402 goto error_parse_next;
2406 /* must be an expression */
2407 expression_t *expression = parse_assignment_expression();
2409 if (env->must_be_constant && !is_initializer_constant(expression)) {
2410 errorf(&expression->base.source_position,
2411 "Initialisation expression '%E' is not constant\n",
2416 /* we are already outside, ... */
2420 /* handle { "string" } special case */
2421 if ((expression->kind == EXPR_STRING_LITERAL
2422 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2423 && outer_type != NULL) {
2424 sub = initializer_from_expression(outer_type, expression);
2426 if (token.type == ',') {
2429 if (token.type != '}') {
2430 warningf(HERE, "excessive elements in initializer for type '%T'",
2433 /* TODO: eat , ... */
2438 /* descend into subtypes until expression matches type */
2440 orig_type = path->top_type;
2441 type = skip_typeref(orig_type);
2443 sub = initializer_from_expression(orig_type, expression);
2447 if (!is_type_valid(type)) {
2450 if (is_type_scalar(type)) {
2451 errorf(&expression->base.source_position,
2452 "expression '%E' doesn't match expected type '%T'",
2453 expression, orig_type);
2457 descend_into_subtype(path);
2461 /* update largest index of top array */
2462 const type_path_entry_t *first = &path->path[0];
2463 type_t *first_type = first->type;
2464 first_type = skip_typeref(first_type);
2465 if (is_type_array(first_type)) {
2466 size_t index = first->v.index;
2467 if (index > path->max_index)
2468 path->max_index = index;
2472 /* append to initializers list */
2473 ARR_APP1(initializer_t*, initializers, sub);
2476 if (env->declaration != NULL)
2477 warningf(HERE, "excess elements in struct initializer for '%Y'",
2478 env->declaration->symbol);
2480 warningf(HERE, "excess elements in struct initializer");
2484 if (token.type == '}') {
2488 if (token.type == '}') {
2493 /* advance to the next declaration if we are not at the end */
2494 advance_current_object(path, top_path_level);
2495 orig_type = path->top_type;
2496 if (orig_type != NULL)
2497 type = skip_typeref(orig_type);
2503 size_t len = ARR_LEN(initializers);
2504 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2505 initializer_t *result = allocate_ast_zero(size);
2506 result->kind = INITIALIZER_LIST;
2507 result->list.len = len;
2508 memcpy(&result->list.initializers, initializers,
2509 len * sizeof(initializers[0]));
2511 DEL_ARR_F(initializers);
2512 ascend_to(path, top_path_level+1);
2517 skip_initializers();
2518 DEL_ARR_F(initializers);
2519 ascend_to(path, top_path_level+1);
2524 * Parses an initializer. Parsers either a compound literal
2525 * (env->declaration == NULL) or an initializer of a declaration.
2527 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2529 type_t *type = skip_typeref(env->type);
2530 initializer_t *result = NULL;
2533 if (is_type_scalar(type)) {
2534 result = parse_scalar_initializer(type, env->must_be_constant);
2535 } else if (token.type == '{') {
2539 memset(&path, 0, sizeof(path));
2540 path.top_type = env->type;
2541 path.path = NEW_ARR_F(type_path_entry_t, 0);
2543 descend_into_subtype(&path);
2545 add_anchor_token('}');
2546 result = parse_sub_initializer(&path, env->type, 1, env);
2547 rem_anchor_token('}');
2549 max_index = path.max_index;
2550 DEL_ARR_F(path.path);
2554 /* parse_scalar_initializer() also works in this case: we simply
2555 * have an expression without {} around it */
2556 result = parse_scalar_initializer(type, env->must_be_constant);
2559 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2560 * the array type size */
2561 if (is_type_array(type) && type->array.size_expression == NULL
2562 && result != NULL) {
2564 switch (result->kind) {
2565 case INITIALIZER_LIST:
2566 size = max_index + 1;
2569 case INITIALIZER_STRING:
2570 size = result->string.string.size;
2573 case INITIALIZER_WIDE_STRING:
2574 size = result->wide_string.string.size;
2577 case INITIALIZER_DESIGNATOR:
2578 case INITIALIZER_VALUE:
2579 /* can happen for parse errors */
2584 internal_errorf(HERE, "invalid initializer type");
2587 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2588 cnst->base.type = type_size_t;
2589 cnst->conste.v.int_value = size;
2591 type_t *new_type = duplicate_type(type);
2593 new_type->array.size_expression = cnst;
2594 new_type->array.size_constant = true;
2595 new_type->array.size = size;
2596 env->type = new_type;
2604 static declaration_t *append_declaration(declaration_t *declaration);
2606 static declaration_t *parse_compound_type_specifier(bool is_struct)
2608 gnu_attribute_t *attributes = NULL;
2609 decl_modifiers_t modifiers = 0;
2616 symbol_t *symbol = NULL;
2617 declaration_t *declaration = NULL;
2619 if (token.type == T___attribute__) {
2620 modifiers |= parse_attributes(&attributes);
2623 if (token.type == T_IDENTIFIER) {
2624 symbol = token.v.symbol;
2627 namespace_t const namespc =
2628 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2629 declaration = get_declaration(symbol, namespc);
2630 if (declaration != NULL) {
2631 if (declaration->parent_scope != scope &&
2632 (token.type == '{' || token.type == ';')) {
2634 } else if (declaration->init.complete &&
2635 token.type == '{') {
2636 assert(symbol != NULL);
2637 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2638 is_struct ? "struct" : "union", symbol,
2639 &declaration->source_position);
2640 declaration->scope.declarations = NULL;
2643 } else if (token.type != '{') {
2645 parse_error_expected("while parsing struct type specifier",
2646 T_IDENTIFIER, '{', NULL);
2648 parse_error_expected("while parsing union type specifier",
2649 T_IDENTIFIER, '{', NULL);
2655 if (declaration == NULL) {
2656 declaration = allocate_declaration_zero();
2657 declaration->namespc =
2658 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2659 declaration->source_position = token.source_position;
2660 declaration->symbol = symbol;
2661 declaration->parent_scope = scope;
2662 if (symbol != NULL) {
2663 environment_push(declaration);
2665 append_declaration(declaration);
2668 if (token.type == '{') {
2669 declaration->init.complete = true;
2671 parse_compound_type_entries(declaration);
2672 modifiers |= parse_attributes(&attributes);
2675 declaration->modifiers |= modifiers;
2679 static void parse_enum_entries(type_t *const enum_type)
2683 if (token.type == '}') {
2685 errorf(HERE, "empty enum not allowed");
2689 add_anchor_token('}');
2691 if (token.type != T_IDENTIFIER) {
2692 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2694 rem_anchor_token('}');
2698 declaration_t *const entry = allocate_declaration_zero();
2699 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2700 entry->type = enum_type;
2701 entry->symbol = token.v.symbol;
2702 entry->source_position = token.source_position;
2705 if (token.type == '=') {
2707 expression_t *value = parse_constant_expression();
2709 value = create_implicit_cast(value, enum_type);
2710 entry->init.enum_value = value;
2715 record_declaration(entry);
2717 if (token.type != ',')
2720 } while (token.type != '}');
2721 rem_anchor_token('}');
2729 static type_t *parse_enum_specifier(void)
2731 gnu_attribute_t *attributes = NULL;
2732 declaration_t *declaration;
2736 if (token.type == T_IDENTIFIER) {
2737 symbol = token.v.symbol;
2740 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2741 } else if (token.type != '{') {
2742 parse_error_expected("while parsing enum type specifier",
2743 T_IDENTIFIER, '{', NULL);
2750 if (declaration == NULL) {
2751 declaration = allocate_declaration_zero();
2752 declaration->namespc = NAMESPACE_ENUM;
2753 declaration->source_position = token.source_position;
2754 declaration->symbol = symbol;
2755 declaration->parent_scope = scope;
2758 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2759 type->enumt.declaration = declaration;
2761 if (token.type == '{') {
2762 if (declaration->init.complete) {
2763 errorf(HERE, "multiple definitions of enum %Y", symbol);
2765 if (symbol != NULL) {
2766 environment_push(declaration);
2768 append_declaration(declaration);
2769 declaration->init.complete = true;
2771 parse_enum_entries(type);
2772 parse_attributes(&attributes);
2779 * if a symbol is a typedef to another type, return true
2781 static bool is_typedef_symbol(symbol_t *symbol)
2783 const declaration_t *const declaration =
2784 get_declaration(symbol, NAMESPACE_NORMAL);
2786 declaration != NULL &&
2787 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2790 static type_t *parse_typeof(void)
2797 add_anchor_token(')');
2799 expression_t *expression = NULL;
2802 switch(token.type) {
2803 case T___extension__:
2804 /* This can be a prefix to a typename or an expression. We simply eat
2808 } while (token.type == T___extension__);
2812 if (is_typedef_symbol(token.v.symbol)) {
2813 type = parse_typename();
2815 expression = parse_expression();
2816 type = expression->base.type;
2821 type = parse_typename();
2825 expression = parse_expression();
2826 type = expression->base.type;
2830 rem_anchor_token(')');
2833 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2834 typeof_type->typeoft.expression = expression;
2835 typeof_type->typeoft.typeof_type = type;
2842 typedef enum specifiers_t {
2843 SPECIFIER_SIGNED = 1 << 0,
2844 SPECIFIER_UNSIGNED = 1 << 1,
2845 SPECIFIER_LONG = 1 << 2,
2846 SPECIFIER_INT = 1 << 3,
2847 SPECIFIER_DOUBLE = 1 << 4,
2848 SPECIFIER_CHAR = 1 << 5,
2849 SPECIFIER_SHORT = 1 << 6,
2850 SPECIFIER_LONG_LONG = 1 << 7,
2851 SPECIFIER_FLOAT = 1 << 8,
2852 SPECIFIER_BOOL = 1 << 9,
2853 SPECIFIER_VOID = 1 << 10,
2854 SPECIFIER_INT8 = 1 << 11,
2855 SPECIFIER_INT16 = 1 << 12,
2856 SPECIFIER_INT32 = 1 << 13,
2857 SPECIFIER_INT64 = 1 << 14,
2858 SPECIFIER_INT128 = 1 << 15,
2859 SPECIFIER_COMPLEX = 1 << 16,
2860 SPECIFIER_IMAGINARY = 1 << 17,
2863 static type_t *create_builtin_type(symbol_t *const symbol,
2864 type_t *const real_type)
2866 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2867 type->builtin.symbol = symbol;
2868 type->builtin.real_type = real_type;
2870 type_t *result = typehash_insert(type);
2871 if (type != result) {
2878 static type_t *get_typedef_type(symbol_t *symbol)
2880 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2881 if (declaration == NULL ||
2882 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2885 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2886 type->typedeft.declaration = declaration;
2892 * check for the allowed MS alignment values.
2894 static bool check_alignment_value(long long intvalue)
2896 if (intvalue < 1 || intvalue > 8192) {
2897 errorf(HERE, "illegal alignment value");
2900 unsigned v = (unsigned)intvalue;
2901 for(unsigned i = 1; i <= 8192; i += i) {
2905 errorf(HERE, "alignment must be power of two");
2909 #define DET_MOD(name, tag) do { \
2910 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2911 *modifiers |= tag; \
2914 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2916 decl_modifiers_t *modifiers = &specifiers->modifiers;
2919 if (token.type == T_restrict) {
2921 DET_MOD(restrict, DM_RESTRICT);
2923 } else if (token.type != T_IDENTIFIER)
2925 symbol_t *symbol = token.v.symbol;
2926 if (symbol == sym_align) {
2929 if (token.type != T_INTEGER)
2931 if (check_alignment_value(token.v.intvalue)) {
2932 if (specifiers->alignment != 0)
2933 warningf(HERE, "align used more than once");
2934 specifiers->alignment = (unsigned char)token.v.intvalue;
2938 } else if (symbol == sym_allocate) {
2941 if (token.type != T_IDENTIFIER)
2943 (void)token.v.symbol;
2945 } else if (symbol == sym_dllimport) {
2947 DET_MOD(dllimport, DM_DLLIMPORT);
2948 } else if (symbol == sym_dllexport) {
2950 DET_MOD(dllexport, DM_DLLEXPORT);
2951 } else if (symbol == sym_thread) {
2953 DET_MOD(thread, DM_THREAD);
2954 } else if (symbol == sym_naked) {
2956 DET_MOD(naked, DM_NAKED);
2957 } else if (symbol == sym_noinline) {
2959 DET_MOD(noinline, DM_NOINLINE);
2960 } else if (symbol == sym_noreturn) {
2962 DET_MOD(noreturn, DM_NORETURN);
2963 } else if (symbol == sym_nothrow) {
2965 DET_MOD(nothrow, DM_NOTHROW);
2966 } else if (symbol == sym_novtable) {
2968 DET_MOD(novtable, DM_NOVTABLE);
2969 } else if (symbol == sym_property) {
2973 bool is_get = false;
2974 if (token.type != T_IDENTIFIER)
2976 if (token.v.symbol == sym_get) {
2978 } else if (token.v.symbol == sym_put) {
2980 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2985 if (token.type != T_IDENTIFIER)
2988 if (specifiers->get_property_sym != NULL) {
2989 errorf(HERE, "get property name already specified");
2991 specifiers->get_property_sym = token.v.symbol;
2994 if (specifiers->put_property_sym != NULL) {
2995 errorf(HERE, "put property name already specified");
2997 specifiers->put_property_sym = token.v.symbol;
3001 if (token.type == ',') {
3008 } else if (symbol == sym_selectany) {
3010 DET_MOD(selectany, DM_SELECTANY);
3011 } else if (symbol == sym_uuid) {
3014 if (token.type != T_STRING_LITERAL)
3018 } else if (symbol == sym_deprecated) {
3020 if (specifiers->deprecated != 0)
3021 warningf(HERE, "deprecated used more than once");
3022 specifiers->deprecated = 1;
3023 if (token.type == '(') {
3025 if (token.type == T_STRING_LITERAL) {
3026 specifiers->deprecated_string = token.v.string.begin;
3029 errorf(HERE, "string literal expected");
3033 } else if (symbol == sym_noalias) {
3035 DET_MOD(noalias, DM_NOALIAS);
3037 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3039 if (token.type == '(')
3043 if (token.type == ',')
3050 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3052 type_t *type = NULL;
3053 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3054 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3055 unsigned type_specifiers = 0;
3056 bool newtype = false;
3057 bool saw_error = false;
3059 specifiers->source_position = token.source_position;
3062 specifiers->modifiers
3063 |= parse_attributes(&specifiers->gnu_attributes);
3064 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3065 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3067 switch(token.type) {
3070 #define MATCH_STORAGE_CLASS(token, class) \
3072 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3073 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3075 specifiers->declared_storage_class = class; \
3079 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3080 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3081 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3082 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3083 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3088 add_anchor_token(')');
3089 parse_microsoft_extended_decl_modifier(specifiers);
3090 rem_anchor_token(')');
3095 switch (specifiers->declared_storage_class) {
3096 case STORAGE_CLASS_NONE:
3097 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3100 case STORAGE_CLASS_EXTERN:
3101 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3104 case STORAGE_CLASS_STATIC:
3105 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3109 errorf(HERE, "multiple storage classes in declaration specifiers");
3115 /* type qualifiers */
3116 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3118 qualifiers |= qualifier; \
3122 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3123 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3124 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3125 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3126 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3127 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3128 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3129 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3131 case T___extension__:
3136 /* type specifiers */
3137 #define MATCH_SPECIFIER(token, specifier, name) \
3140 if (type_specifiers & specifier) { \
3141 errorf(HERE, "multiple " name " type specifiers given"); \
3143 type_specifiers |= specifier; \
3147 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3148 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3149 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3150 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3151 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3152 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3153 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3154 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3155 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3156 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3157 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3158 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3159 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3160 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3161 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3162 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3164 case T__forceinline:
3165 /* only in microsoft mode */
3166 specifiers->modifiers |= DM_FORCEINLINE;
3171 specifiers->is_inline = true;
3176 if (type_specifiers & SPECIFIER_LONG_LONG) {
3177 errorf(HERE, "multiple type specifiers given");
3178 } else if (type_specifiers & SPECIFIER_LONG) {
3179 type_specifiers |= SPECIFIER_LONG_LONG;
3181 type_specifiers |= SPECIFIER_LONG;
3186 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3188 type->compound.declaration = parse_compound_type_specifier(true);
3192 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3193 type->compound.declaration = parse_compound_type_specifier(false);
3194 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3195 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3199 type = parse_enum_specifier();
3202 type = parse_typeof();
3204 case T___builtin_va_list:
3205 type = duplicate_type(type_valist);
3209 case T_IDENTIFIER: {
3210 /* only parse identifier if we haven't found a type yet */
3211 if (type != NULL || type_specifiers != 0) {
3212 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3213 * declaration, so it doesn't generate errors about expecting '(' or
3215 switch (look_ahead(1)->type) {
3222 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3225 errorf(HERE, "discarding stray %K in declaration specifer", &token);
3230 goto finish_specifiers;
3234 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3235 if (typedef_type == NULL) {
3236 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3237 * declaration, so it doesn't generate 'implicit int' followed by more
3238 * errors later on. */
3239 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3244 errorf(HERE, "%K does not name a type", &token);
3247 if (la1_type == '*')
3248 goto finish_specifiers;
3252 goto finish_specifiers;
3257 type = typedef_type;
3261 /* function specifier */
3263 goto finish_specifiers;
3270 atomic_type_kind_t atomic_type;
3272 /* match valid basic types */
3273 switch(type_specifiers) {
3274 case SPECIFIER_VOID:
3275 atomic_type = ATOMIC_TYPE_VOID;
3277 case SPECIFIER_CHAR:
3278 atomic_type = ATOMIC_TYPE_CHAR;
3280 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3281 atomic_type = ATOMIC_TYPE_SCHAR;
3283 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3284 atomic_type = ATOMIC_TYPE_UCHAR;
3286 case SPECIFIER_SHORT:
3287 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3288 case SPECIFIER_SHORT | SPECIFIER_INT:
3289 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3290 atomic_type = ATOMIC_TYPE_SHORT;
3292 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3293 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3294 atomic_type = ATOMIC_TYPE_USHORT;
3297 case SPECIFIER_SIGNED:
3298 case SPECIFIER_SIGNED | SPECIFIER_INT:
3299 atomic_type = ATOMIC_TYPE_INT;
3301 case SPECIFIER_UNSIGNED:
3302 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3303 atomic_type = ATOMIC_TYPE_UINT;
3305 case SPECIFIER_LONG:
3306 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3307 case SPECIFIER_LONG | SPECIFIER_INT:
3308 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3309 atomic_type = ATOMIC_TYPE_LONG;
3311 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3312 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3313 atomic_type = ATOMIC_TYPE_ULONG;
3316 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3317 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3318 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3319 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3321 atomic_type = ATOMIC_TYPE_LONGLONG;
3322 goto warn_about_long_long;
3324 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3325 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3327 atomic_type = ATOMIC_TYPE_ULONGLONG;
3328 warn_about_long_long:
3329 if (warning.long_long) {
3330 warningf(&specifiers->source_position,
3331 "ISO C90 does not support 'long long'");
3335 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3336 atomic_type = unsigned_int8_type_kind;
3339 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3340 atomic_type = unsigned_int16_type_kind;
3343 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3344 atomic_type = unsigned_int32_type_kind;
3347 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3348 atomic_type = unsigned_int64_type_kind;
3351 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3352 atomic_type = unsigned_int128_type_kind;
3355 case SPECIFIER_INT8:
3356 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3357 atomic_type = int8_type_kind;
3360 case SPECIFIER_INT16:
3361 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3362 atomic_type = int16_type_kind;
3365 case SPECIFIER_INT32:
3366 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3367 atomic_type = int32_type_kind;
3370 case SPECIFIER_INT64:
3371 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3372 atomic_type = int64_type_kind;
3375 case SPECIFIER_INT128:
3376 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3377 atomic_type = int128_type_kind;
3380 case SPECIFIER_FLOAT:
3381 atomic_type = ATOMIC_TYPE_FLOAT;
3383 case SPECIFIER_DOUBLE:
3384 atomic_type = ATOMIC_TYPE_DOUBLE;
3386 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3387 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3389 case SPECIFIER_BOOL:
3390 atomic_type = ATOMIC_TYPE_BOOL;
3392 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3393 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3394 atomic_type = ATOMIC_TYPE_FLOAT;
3396 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3397 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3398 atomic_type = ATOMIC_TYPE_DOUBLE;
3400 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3401 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3402 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3405 /* invalid specifier combination, give an error message */
3406 if (type_specifiers == 0) {
3408 specifiers->type = type_error_type;
3413 if (warning.implicit_int) {
3414 warningf(HERE, "no type specifiers in declaration, using 'int'");
3416 atomic_type = ATOMIC_TYPE_INT;
3419 errorf(HERE, "no type specifiers given in declaration");
3421 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3422 (type_specifiers & SPECIFIER_UNSIGNED)) {
3423 errorf(HERE, "signed and unsigned specifiers given");
3424 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3425 errorf(HERE, "only integer types can be signed or unsigned");
3427 errorf(HERE, "multiple datatypes in declaration");
3429 atomic_type = ATOMIC_TYPE_INVALID;
3432 if (type_specifiers & SPECIFIER_COMPLEX &&
3433 atomic_type != ATOMIC_TYPE_INVALID) {
3434 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3435 type->complex.akind = atomic_type;
3436 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3437 atomic_type != ATOMIC_TYPE_INVALID) {
3438 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3439 type->imaginary.akind = atomic_type;
3441 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3442 type->atomic.akind = atomic_type;
3445 } else if (type_specifiers != 0) {
3446 errorf(HERE, "multiple datatypes in declaration");
3449 /* FIXME: check type qualifiers here */
3451 type->base.qualifiers = qualifiers;
3452 type->base.modifiers = modifiers;
3454 type_t *result = typehash_insert(type);
3455 if (newtype && result != type) {
3459 specifiers->type = result;
3464 static type_qualifiers_t parse_type_qualifiers(void)
3466 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3469 switch(token.type) {
3470 /* type qualifiers */
3471 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3472 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3473 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3474 /* microsoft extended type modifiers */
3475 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3476 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3477 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3478 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3479 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3487 static declaration_t *parse_identifier_list(void)
3489 declaration_t *declarations = NULL;
3490 declaration_t *last_declaration = NULL;
3492 declaration_t *const declaration = allocate_declaration_zero();
3493 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3494 declaration->source_position = token.source_position;
3495 declaration->symbol = token.v.symbol;
3498 if (last_declaration != NULL) {
3499 last_declaration->next = declaration;
3501 declarations = declaration;
3503 last_declaration = declaration;
3505 if (token.type != ',') {
3509 } while (token.type == T_IDENTIFIER);
3511 return declarations;
3514 static type_t *automatic_type_conversion(type_t *orig_type);
3516 static void semantic_parameter(declaration_t *declaration)
3518 /* TODO: improve error messages */
3519 source_position_t const* const pos = &declaration->source_position;
3521 switch (declaration->declared_storage_class) {
3522 case STORAGE_CLASS_TYPEDEF:
3523 errorf(pos, "typedef not allowed in parameter list");
3526 /* Allowed storage classes */
3527 case STORAGE_CLASS_NONE:
3528 case STORAGE_CLASS_REGISTER:
3532 errorf(pos, "parameter may only have none or register storage class");
3536 type_t *const orig_type = declaration->type;
3537 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3538 * sugar. Turn it into a pointer.
3539 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3540 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3542 type_t *const type = automatic_type_conversion(orig_type);
3543 declaration->type = type;
3545 if (is_type_incomplete(skip_typeref(type))) {
3546 errorf(pos, "incomplete type '%T' not allowed for parameter '%Y'",
3547 orig_type, declaration->symbol);
3551 static declaration_t *parse_parameter(void)
3553 declaration_specifiers_t specifiers;
3554 memset(&specifiers, 0, sizeof(specifiers));
3556 parse_declaration_specifiers(&specifiers);
3558 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3563 static declaration_t *parse_parameters(function_type_t *type)
3565 declaration_t *declarations = NULL;
3568 add_anchor_token(')');
3569 int saved_comma_state = save_and_reset_anchor_state(',');
3571 if (token.type == T_IDENTIFIER) {
3572 symbol_t *symbol = token.v.symbol;
3573 if (!is_typedef_symbol(symbol)) {
3574 type->kr_style_parameters = true;
3575 declarations = parse_identifier_list();
3576 goto parameters_finished;
3580 if (token.type == ')') {
3581 type->unspecified_parameters = 1;
3582 goto parameters_finished;
3585 declaration_t *declaration;
3586 declaration_t *last_declaration = NULL;
3587 function_parameter_t *parameter;
3588 function_parameter_t *last_parameter = NULL;
3591 switch(token.type) {
3595 goto parameters_finished;
3598 case T___extension__:
3600 declaration = parse_parameter();
3602 /* func(void) is not a parameter */
3603 if (last_parameter == NULL
3604 && token.type == ')'
3605 && declaration->symbol == NULL
3606 && skip_typeref(declaration->type) == type_void) {
3607 goto parameters_finished;
3609 semantic_parameter(declaration);
3611 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3612 memset(parameter, 0, sizeof(parameter[0]));
3613 parameter->type = declaration->type;
3615 if (last_parameter != NULL) {
3616 last_declaration->next = declaration;
3617 last_parameter->next = parameter;
3619 type->parameters = parameter;
3620 declarations = declaration;
3622 last_parameter = parameter;
3623 last_declaration = declaration;
3627 goto parameters_finished;
3629 if (token.type != ',') {
3630 goto parameters_finished;
3636 parameters_finished:
3637 rem_anchor_token(')');
3640 restore_anchor_state(',', saved_comma_state);
3641 return declarations;
3644 restore_anchor_state(',', saved_comma_state);
3648 typedef enum construct_type_kind_t {
3653 } construct_type_kind_t;
3655 typedef struct construct_type_t construct_type_t;
3656 struct construct_type_t {
3657 construct_type_kind_t kind;
3658 construct_type_t *next;
3661 typedef struct parsed_pointer_t parsed_pointer_t;
3662 struct parsed_pointer_t {
3663 construct_type_t construct_type;
3664 type_qualifiers_t type_qualifiers;
3667 typedef struct construct_function_type_t construct_function_type_t;
3668 struct construct_function_type_t {
3669 construct_type_t construct_type;
3670 type_t *function_type;
3673 typedef struct parsed_array_t parsed_array_t;
3674 struct parsed_array_t {
3675 construct_type_t construct_type;
3676 type_qualifiers_t type_qualifiers;
3682 typedef struct construct_base_type_t construct_base_type_t;
3683 struct construct_base_type_t {
3684 construct_type_t construct_type;
3688 static construct_type_t *parse_pointer_declarator(void)
3692 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3693 memset(pointer, 0, sizeof(pointer[0]));
3694 pointer->construct_type.kind = CONSTRUCT_POINTER;
3695 pointer->type_qualifiers = parse_type_qualifiers();
3697 return (construct_type_t*) pointer;
3700 static construct_type_t *parse_array_declarator(void)
3703 add_anchor_token(']');
3705 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3706 memset(array, 0, sizeof(array[0]));
3707 array->construct_type.kind = CONSTRUCT_ARRAY;
3709 if (token.type == T_static) {
3710 array->is_static = true;
3714 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3715 if (type_qualifiers != 0) {
3716 if (token.type == T_static) {
3717 array->is_static = true;
3721 array->type_qualifiers = type_qualifiers;
3723 if (token.type == '*' && look_ahead(1)->type == ']') {
3724 array->is_variable = true;
3726 } else if (token.type != ']') {
3727 array->size = parse_assignment_expression();
3730 rem_anchor_token(']');
3733 return (construct_type_t*) array;
3738 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3741 if (declaration != NULL) {
3742 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3744 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3746 if (mask & (mask-1)) {
3747 const char *first = NULL, *second = NULL;
3749 /* more than one calling convention set */
3750 if (declaration->modifiers & DM_CDECL) {
3751 if (first == NULL) first = "cdecl";
3752 else if (second == NULL) second = "cdecl";
3754 if (declaration->modifiers & DM_STDCALL) {
3755 if (first == NULL) first = "stdcall";
3756 else if (second == NULL) second = "stdcall";
3758 if (declaration->modifiers & DM_FASTCALL) {
3759 if (first == NULL) first = "fastcall";
3760 else if (second == NULL) second = "fastcall";
3762 if (declaration->modifiers & DM_THISCALL) {
3763 if (first == NULL) first = "thiscall";
3764 else if (second == NULL) second = "thiscall";
3766 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3769 if (declaration->modifiers & DM_CDECL)
3770 type->function.calling_convention = CC_CDECL;
3771 else if (declaration->modifiers & DM_STDCALL)
3772 type->function.calling_convention = CC_STDCALL;
3773 else if (declaration->modifiers & DM_FASTCALL)
3774 type->function.calling_convention = CC_FASTCALL;
3775 else if (declaration->modifiers & DM_THISCALL)
3776 type->function.calling_convention = CC_THISCALL;
3778 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3781 declaration_t *parameters = parse_parameters(&type->function);
3782 if (declaration != NULL) {
3783 declaration->scope.declarations = parameters;
3786 construct_function_type_t *construct_function_type =
3787 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3788 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3789 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3790 construct_function_type->function_type = type;
3792 return &construct_function_type->construct_type;
3795 static void fix_declaration_type(declaration_t *declaration)
3797 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3798 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3800 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3801 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3803 if (declaration->type->base.modifiers == type_modifiers)
3806 type_t *copy = duplicate_type(declaration->type);
3807 copy->base.modifiers = type_modifiers;
3809 type_t *result = typehash_insert(copy);
3810 if (result != copy) {
3811 obstack_free(type_obst, copy);
3814 declaration->type = result;
3817 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3818 bool may_be_abstract)
3820 /* construct a single linked list of construct_type_t's which describe
3821 * how to construct the final declarator type */
3822 construct_type_t *first = NULL;
3823 construct_type_t *last = NULL;
3824 gnu_attribute_t *attributes = NULL;
3826 decl_modifiers_t modifiers = parse_attributes(&attributes);
3829 while (token.type == '*') {
3830 construct_type_t *type = parse_pointer_declarator();
3840 /* TODO: find out if this is correct */
3841 modifiers |= parse_attributes(&attributes);
3844 if (declaration != NULL)
3845 declaration->modifiers |= modifiers;
3847 construct_type_t *inner_types = NULL;
3849 switch(token.type) {
3851 if (declaration == NULL) {
3852 errorf(HERE, "no identifier expected in typename");
3854 declaration->symbol = token.v.symbol;
3855 declaration->source_position = token.source_position;
3861 add_anchor_token(')');
3862 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3863 /* All later declarators only modify the return type, not declaration */
3865 rem_anchor_token(')');
3869 if (may_be_abstract)
3871 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3872 /* avoid a loop in the outermost scope, because eat_statement doesn't
3874 if (token.type == '}' && current_function == NULL) {
3882 construct_type_t *p = last;
3885 construct_type_t *type;
3886 switch(token.type) {
3888 type = parse_function_declarator(declaration);
3891 type = parse_array_declarator();
3894 goto declarator_finished;
3897 /* insert in the middle of the list (behind p) */
3899 type->next = p->next;
3910 declarator_finished:
3911 /* append inner_types at the end of the list, we don't to set last anymore
3912 * as it's not needed anymore */
3914 assert(first == NULL);
3915 first = inner_types;
3917 last->next = inner_types;
3925 static void parse_declaration_attributes(declaration_t *declaration)
3927 gnu_attribute_t *attributes = NULL;
3928 decl_modifiers_t modifiers = parse_attributes(&attributes);
3930 if (declaration == NULL)
3933 declaration->modifiers |= modifiers;
3934 /* check if we have these stupid mode attributes... */
3935 type_t *old_type = declaration->type;
3936 if (old_type == NULL)
3939 gnu_attribute_t *attribute = attributes;
3940 for ( ; attribute != NULL; attribute = attribute->next) {
3941 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3944 atomic_type_kind_t akind = attribute->u.akind;
3945 if (!is_type_signed(old_type)) {
3947 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3948 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3949 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3950 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3952 panic("invalid akind in mode attribute");
3956 = make_atomic_type(akind, old_type->base.qualifiers);
3960 static type_t *construct_declarator_type(construct_type_t *construct_list,
3963 construct_type_t *iter = construct_list;
3964 for( ; iter != NULL; iter = iter->next) {
3965 switch(iter->kind) {
3966 case CONSTRUCT_INVALID:
3967 internal_errorf(HERE, "invalid type construction found");
3968 case CONSTRUCT_FUNCTION: {
3969 construct_function_type_t *construct_function_type
3970 = (construct_function_type_t*) iter;
3972 type_t *function_type = construct_function_type->function_type;
3974 function_type->function.return_type = type;
3976 type_t *skipped_return_type = skip_typeref(type);
3977 if (is_type_function(skipped_return_type)) {
3978 errorf(HERE, "function returning function is not allowed");
3979 type = type_error_type;
3980 } else if (is_type_array(skipped_return_type)) {
3981 errorf(HERE, "function returning array is not allowed");
3982 type = type_error_type;
3984 type = function_type;
3989 case CONSTRUCT_POINTER: {
3990 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3991 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3992 pointer_type->pointer.points_to = type;
3993 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3995 type = pointer_type;
3999 case CONSTRUCT_ARRAY: {
4000 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4001 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4003 expression_t *size_expression = parsed_array->size;
4004 if (size_expression != NULL) {
4006 = create_implicit_cast(size_expression, type_size_t);
4009 array_type->base.qualifiers = parsed_array->type_qualifiers;
4010 array_type->array.element_type = type;
4011 array_type->array.is_static = parsed_array->is_static;
4012 array_type->array.is_variable = parsed_array->is_variable;
4013 array_type->array.size_expression = size_expression;
4015 if (size_expression != NULL) {
4016 if (is_constant_expression(size_expression)) {
4017 array_type->array.size_constant = true;
4018 array_type->array.size
4019 = fold_constant(size_expression);
4021 array_type->array.is_vla = true;
4025 type_t *skipped_type = skip_typeref(type);
4026 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4027 errorf(HERE, "array of void is not allowed");
4028 type = type_error_type;
4036 type_t *hashed_type = typehash_insert(type);
4037 if (hashed_type != type) {
4038 /* the function type was constructed earlier freeing it here will
4039 * destroy other types... */
4040 if (iter->kind != CONSTRUCT_FUNCTION) {
4050 static declaration_t *parse_declarator(
4051 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4053 declaration_t *const declaration = allocate_declaration_zero();
4054 declaration->source_position = specifiers->source_position;
4055 declaration->declared_storage_class = specifiers->declared_storage_class;
4056 declaration->modifiers = specifiers->modifiers;
4057 declaration->deprecated_string = specifiers->deprecated_string;
4058 declaration->get_property_sym = specifiers->get_property_sym;
4059 declaration->put_property_sym = specifiers->put_property_sym;
4060 declaration->is_inline = specifiers->is_inline;
4062 declaration->storage_class = specifiers->declared_storage_class;
4063 if (declaration->storage_class == STORAGE_CLASS_NONE
4064 && scope != global_scope) {
4065 declaration->storage_class = STORAGE_CLASS_AUTO;
4068 if (specifiers->alignment != 0) {
4069 /* TODO: add checks here */
4070 declaration->alignment = specifiers->alignment;
4073 construct_type_t *construct_type
4074 = parse_inner_declarator(declaration, may_be_abstract);
4075 type_t *const type = specifiers->type;
4076 declaration->type = construct_declarator_type(construct_type, type);
4078 parse_declaration_attributes(declaration);
4080 fix_declaration_type(declaration);
4082 if (construct_type != NULL) {
4083 obstack_free(&temp_obst, construct_type);
4089 static type_t *parse_abstract_declarator(type_t *base_type)
4091 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4093 type_t *result = construct_declarator_type(construct_type, base_type);
4094 if (construct_type != NULL) {
4095 obstack_free(&temp_obst, construct_type);
4101 static declaration_t *append_declaration(declaration_t* const declaration)
4103 if (last_declaration != NULL) {
4104 last_declaration->next = declaration;
4106 scope->declarations = declaration;
4108 last_declaration = declaration;
4113 * Check if the declaration of main is suspicious. main should be a
4114 * function with external linkage, returning int, taking either zero
4115 * arguments, two, or three arguments of appropriate types, ie.
4117 * int main([ int argc, char **argv [, char **env ] ]).
4119 * @param decl the declaration to check
4120 * @param type the function type of the declaration
4122 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4124 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4125 warningf(&decl->source_position,
4126 "'main' is normally a non-static function");
4128 if (skip_typeref(func_type->return_type) != type_int) {
4129 warningf(&decl->source_position,
4130 "return type of 'main' should be 'int', but is '%T'",
4131 func_type->return_type);
4133 const function_parameter_t *parm = func_type->parameters;
4135 type_t *const first_type = parm->type;
4136 if (!types_compatible(skip_typeref(first_type), type_int)) {
4137 warningf(&decl->source_position,
4138 "first argument of 'main' should be 'int', but is '%T'", first_type);
4142 type_t *const second_type = parm->type;
4143 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4144 warningf(&decl->source_position,
4145 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4149 type_t *const third_type = parm->type;
4150 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4151 warningf(&decl->source_position,
4152 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4156 goto warn_arg_count;
4160 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4166 * Check if a symbol is the equal to "main".
4168 static bool is_sym_main(const symbol_t *const sym)
4170 return strcmp(sym->string, "main") == 0;
4173 static declaration_t *internal_record_declaration(
4174 declaration_t *const declaration,
4175 const bool is_definition)
4177 const symbol_t *const symbol = declaration->symbol;
4178 const namespace_t namespc = (namespace_t)declaration->namespc;
4180 assert(symbol != NULL);
4181 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4183 type_t *const orig_type = declaration->type;
4184 type_t *const type = skip_typeref(orig_type);
4185 if (is_type_function(type) &&
4186 type->function.unspecified_parameters &&
4187 warning.strict_prototypes &&
4188 previous_declaration == NULL) {
4189 warningf(&declaration->source_position,
4190 "function declaration '%#T' is not a prototype",
4191 orig_type, declaration->symbol);
4194 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4195 check_type_of_main(declaration, &type->function);
4198 if (warning.nested_externs &&
4199 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4200 scope != global_scope) {
4201 warningf(&declaration->source_position,
4202 "nested extern declaration of '%#T'", declaration->type, symbol);
4205 assert(declaration != previous_declaration);
4206 if (previous_declaration != NULL
4207 && previous_declaration->parent_scope == scope) {
4208 /* can happen for K&R style declarations */
4209 if (previous_declaration->type == NULL) {
4210 previous_declaration->type = declaration->type;
4213 const type_t *prev_type = skip_typeref(previous_declaration->type);
4214 if (!types_compatible(type, prev_type)) {
4215 errorf(&declaration->source_position,
4216 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4217 orig_type, symbol, previous_declaration->type, symbol,
4218 &previous_declaration->source_position);
4220 unsigned old_storage_class = previous_declaration->storage_class;
4221 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4222 errorf(&declaration->source_position,
4223 "redeclaration of enum entry '%Y' (declared %P)",
4224 symbol, &previous_declaration->source_position);
4225 return previous_declaration;
4228 if (warning.redundant_decls &&
4230 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4231 !(previous_declaration->modifiers & DM_USED) &&
4232 !previous_declaration->used) {
4233 warningf(&previous_declaration->source_position,
4234 "unnecessary static forward declaration for '%#T'",
4235 previous_declaration->type, symbol);
4238 unsigned new_storage_class = declaration->storage_class;
4240 if (is_type_incomplete(prev_type)) {
4241 previous_declaration->type = type;
4245 /* pretend no storage class means extern for function
4246 * declarations (except if the previous declaration is neither
4247 * none nor extern) */
4248 if (is_type_function(type)) {
4249 if (prev_type->function.unspecified_parameters) {
4250 previous_declaration->type = type;
4254 switch (old_storage_class) {
4255 case STORAGE_CLASS_NONE:
4256 old_storage_class = STORAGE_CLASS_EXTERN;
4259 case STORAGE_CLASS_EXTERN:
4260 if (is_definition) {
4261 if (warning.missing_prototypes &&
4262 prev_type->function.unspecified_parameters &&
4263 !is_sym_main(symbol)) {
4264 warningf(&declaration->source_position,
4265 "no previous prototype for '%#T'",
4268 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4269 new_storage_class = STORAGE_CLASS_EXTERN;
4278 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4279 new_storage_class == STORAGE_CLASS_EXTERN) {
4280 warn_redundant_declaration:
4281 if (!is_definition &&
4282 warning.redundant_decls &&
4283 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4284 warningf(&declaration->source_position,
4285 "redundant declaration for '%Y' (declared %P)",
4286 symbol, &previous_declaration->source_position);
4288 } else if (current_function == NULL) {
4289 if (old_storage_class != STORAGE_CLASS_STATIC &&
4290 new_storage_class == STORAGE_CLASS_STATIC) {
4291 errorf(&declaration->source_position,
4292 "static declaration of '%Y' follows non-static declaration (declared %P)",
4293 symbol, &previous_declaration->source_position);
4294 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4295 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4296 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4298 goto warn_redundant_declaration;
4300 } else if (old_storage_class == new_storage_class) {
4301 errorf(&declaration->source_position,
4302 "redeclaration of '%Y' (declared %P)",
4303 symbol, &previous_declaration->source_position);
4305 errorf(&declaration->source_position,
4306 "redeclaration of '%Y' with different linkage (declared %P)",
4307 symbol, &previous_declaration->source_position);
4311 previous_declaration->modifiers |= declaration->modifiers;
4312 previous_declaration->is_inline |= declaration->is_inline;
4313 return previous_declaration;
4314 } else if (is_type_function(type)) {
4315 if (is_definition &&
4316 declaration->storage_class != STORAGE_CLASS_STATIC) {
4317 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4318 warningf(&declaration->source_position,
4319 "no previous prototype for '%#T'", orig_type, symbol);
4320 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4321 warningf(&declaration->source_position,
4322 "no previous declaration for '%#T'", orig_type,
4327 if (warning.missing_declarations &&
4328 scope == global_scope && (
4329 declaration->storage_class == STORAGE_CLASS_NONE ||
4330 declaration->storage_class == STORAGE_CLASS_THREAD
4332 warningf(&declaration->source_position,
4333 "no previous declaration for '%#T'", orig_type, symbol);
4337 assert(declaration->parent_scope == NULL);
4338 assert(scope != NULL);
4340 declaration->parent_scope = scope;
4342 environment_push(declaration);
4343 return append_declaration(declaration);
4346 static declaration_t *record_declaration(declaration_t *declaration)
4348 return internal_record_declaration(declaration, false);
4351 static declaration_t *record_definition(declaration_t *declaration)
4353 return internal_record_declaration(declaration, true);
4356 static void parser_error_multiple_definition(declaration_t *declaration,
4357 const source_position_t *source_position)
4359 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4360 declaration->symbol, &declaration->source_position);
4363 static bool is_declaration_specifier(const token_t *token,
4364 bool only_specifiers_qualifiers)
4366 switch(token->type) {
4371 return is_typedef_symbol(token->v.symbol);
4373 case T___extension__:
4375 return !only_specifiers_qualifiers;
4382 static void parse_init_declarator_rest(declaration_t *declaration)
4386 type_t *orig_type = declaration->type;
4387 type_t *type = skip_typeref(orig_type);
4389 if (declaration->init.initializer != NULL) {
4390 parser_error_multiple_definition(declaration, HERE);
4393 bool must_be_constant = false;
4394 if (declaration->storage_class == STORAGE_CLASS_STATIC
4395 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4396 || declaration->parent_scope == global_scope) {
4397 must_be_constant = true;
4400 parse_initializer_env_t env;
4401 env.type = orig_type;
4402 env.must_be_constant = must_be_constant;
4403 env.declaration = declaration;
4405 initializer_t *initializer = parse_initializer(&env);
4407 if (env.type != orig_type) {
4408 orig_type = env.type;
4409 type = skip_typeref(orig_type);
4410 declaration->type = env.type;
4413 if (is_type_function(type)) {
4414 errorf(&declaration->source_position,
4415 "initializers not allowed for function types at declator '%Y' (type '%T')",
4416 declaration->symbol, orig_type);
4418 declaration->init.initializer = initializer;
4422 /* parse rest of a declaration without any declarator */
4423 static void parse_anonymous_declaration_rest(
4424 const declaration_specifiers_t *specifiers,
4425 parsed_declaration_func finished_declaration)
4429 declaration_t *const declaration = allocate_declaration_zero();
4430 declaration->type = specifiers->type;
4431 declaration->declared_storage_class = specifiers->declared_storage_class;
4432 declaration->source_position = specifiers->source_position;
4433 declaration->modifiers = specifiers->modifiers;
4435 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4436 warningf(&declaration->source_position,
4437 "useless storage class in empty declaration");
4439 declaration->storage_class = STORAGE_CLASS_NONE;
4441 type_t *type = declaration->type;
4442 switch (type->kind) {
4443 case TYPE_COMPOUND_STRUCT:
4444 case TYPE_COMPOUND_UNION: {
4445 if (type->compound.declaration->symbol == NULL) {
4446 warningf(&declaration->source_position,
4447 "unnamed struct/union that defines no instances");
4456 warningf(&declaration->source_position, "empty declaration");
4460 finished_declaration(declaration);
4463 static void parse_declaration_rest(declaration_t *ndeclaration,
4464 const declaration_specifiers_t *specifiers,
4465 parsed_declaration_func finished_declaration)
4467 add_anchor_token(';');
4468 add_anchor_token('=');
4469 add_anchor_token(',');
4471 declaration_t *declaration = finished_declaration(ndeclaration);
4473 type_t *orig_type = declaration->type;
4474 type_t *type = skip_typeref(orig_type);
4476 if (type->kind != TYPE_FUNCTION &&
4477 declaration->is_inline &&
4478 is_type_valid(type)) {
4479 warningf(&declaration->source_position,
4480 "variable '%Y' declared 'inline'\n", declaration->symbol);
4483 if (token.type == '=') {
4484 parse_init_declarator_rest(declaration);
4487 if (token.type != ',')
4491 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4496 rem_anchor_token(';');
4497 rem_anchor_token('=');
4498 rem_anchor_token(',');
4501 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4503 symbol_t *symbol = declaration->symbol;
4504 if (symbol == NULL) {
4505 errorf(HERE, "anonymous declaration not valid as function parameter");
4508 namespace_t namespc = (namespace_t) declaration->namespc;
4509 if (namespc != NAMESPACE_NORMAL) {
4510 return record_declaration(declaration);
4513 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4514 if (previous_declaration == NULL ||
4515 previous_declaration->parent_scope != scope) {
4516 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4521 if (previous_declaration->type == NULL) {
4522 previous_declaration->type = declaration->type;
4523 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4524 previous_declaration->storage_class = declaration->storage_class;
4525 previous_declaration->parent_scope = scope;
4526 return previous_declaration;
4528 return record_declaration(declaration);
4532 static void parse_declaration(parsed_declaration_func finished_declaration)
4534 declaration_specifiers_t specifiers;
4535 memset(&specifiers, 0, sizeof(specifiers));
4536 parse_declaration_specifiers(&specifiers);
4538 if (token.type == ';') {
4539 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4541 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4542 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4546 static type_t *get_default_promoted_type(type_t *orig_type)
4548 type_t *result = orig_type;
4550 type_t *type = skip_typeref(orig_type);
4551 if (is_type_integer(type)) {
4552 result = promote_integer(type);
4553 } else if (type == type_float) {
4554 result = type_double;
4560 static void parse_kr_declaration_list(declaration_t *declaration)
4562 type_t *type = skip_typeref(declaration->type);
4563 if (!is_type_function(type))
4566 if (!type->function.kr_style_parameters)
4569 /* push function parameters */
4570 int top = environment_top();
4571 scope_t *last_scope = scope;
4572 set_scope(&declaration->scope);
4574 declaration_t *parameter = declaration->scope.declarations;
4575 for ( ; parameter != NULL; parameter = parameter->next) {
4576 assert(parameter->parent_scope == NULL);
4577 parameter->parent_scope = scope;
4578 environment_push(parameter);
4581 /* parse declaration list */
4582 while (is_declaration_specifier(&token, false)) {
4583 parse_declaration(finished_kr_declaration);
4586 /* pop function parameters */
4587 assert(scope == &declaration->scope);
4588 set_scope(last_scope);
4589 environment_pop_to(top);
4591 /* update function type */
4592 type_t *new_type = duplicate_type(type);
4594 function_parameter_t *parameters = NULL;
4595 function_parameter_t *last_parameter = NULL;
4597 declaration_t *parameter_declaration = declaration->scope.declarations;
4598 for( ; parameter_declaration != NULL;
4599 parameter_declaration = parameter_declaration->next) {
4600 type_t *parameter_type = parameter_declaration->type;
4601 if (parameter_type == NULL) {
4603 errorf(HERE, "no type specified for function parameter '%Y'",
4604 parameter_declaration->symbol);
4606 if (warning.implicit_int) {
4607 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4608 parameter_declaration->symbol);
4610 parameter_type = type_int;
4611 parameter_declaration->type = parameter_type;
4615 semantic_parameter(parameter_declaration);
4616 parameter_type = parameter_declaration->type;
4619 * we need the default promoted types for the function type
4621 parameter_type = get_default_promoted_type(parameter_type);
4623 function_parameter_t *function_parameter
4624 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4625 memset(function_parameter, 0, sizeof(function_parameter[0]));
4627 function_parameter->type = parameter_type;
4628 if (last_parameter != NULL) {
4629 last_parameter->next = function_parameter;
4631 parameters = function_parameter;
4633 last_parameter = function_parameter;
4636 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4638 new_type->function.parameters = parameters;
4639 new_type->function.unspecified_parameters = true;
4641 type = typehash_insert(new_type);
4642 if (type != new_type) {
4643 obstack_free(type_obst, new_type);
4646 declaration->type = type;
4649 static bool first_err = true;
4652 * When called with first_err set, prints the name of the current function,
4655 static void print_in_function(void)
4659 diagnosticf("%s: In function '%Y':\n",
4660 current_function->source_position.input_name,
4661 current_function->symbol);
4666 * Check if all labels are defined in the current function.
4667 * Check if all labels are used in the current function.
4669 static void check_labels(void)
4671 for (const goto_statement_t *goto_statement = goto_first;
4672 goto_statement != NULL;
4673 goto_statement = goto_statement->next) {
4674 declaration_t *label = goto_statement->label;
4677 if (label->source_position.input_name == NULL) {
4678 print_in_function();
4679 errorf(&goto_statement->base.source_position,
4680 "label '%Y' used but not defined", label->symbol);
4683 goto_first = goto_last = NULL;
4685 if (warning.unused_label) {
4686 for (const label_statement_t *label_statement = label_first;
4687 label_statement != NULL;
4688 label_statement = label_statement->next) {
4689 const declaration_t *label = label_statement->label;
4691 if (! label->used) {
4692 print_in_function();
4693 warningf(&label_statement->base.source_position,
4694 "label '%Y' defined but not used", label->symbol);
4698 label_first = label_last = NULL;
4702 * Check declarations of current_function for unused entities.
4704 static void check_declarations(void)
4706 if (warning.unused_parameter) {
4707 const scope_t *scope = ¤t_function->scope;
4709 const declaration_t *parameter = scope->declarations;
4710 for (; parameter != NULL; parameter = parameter->next) {
4711 if (! parameter->used) {
4712 print_in_function();
4713 warningf(¶meter->source_position,
4714 "unused parameter '%Y'", parameter->symbol);
4718 if (warning.unused_variable) {
4722 static int determine_truth(expression_t const* const cond)
4725 !is_constant_expression(cond) ? 0 :
4726 fold_constant(cond) != 0 ? 1 :
4730 static bool noreturn_candidate;
4732 static void check_reachable(statement_t *const stmt)
4734 if (stmt->base.reachable)
4736 if (stmt->kind != STATEMENT_DO_WHILE)
4737 stmt->base.reachable = true;
4739 statement_t *last = stmt;
4741 switch (stmt->kind) {
4742 case STATEMENT_INVALID:
4743 case STATEMENT_EMPTY:
4744 case STATEMENT_DECLARATION:
4746 next = stmt->base.next;
4749 case STATEMENT_COMPOUND:
4750 next = stmt->compound.statements;
4753 case STATEMENT_RETURN:
4754 noreturn_candidate = false;
4757 case STATEMENT_IF: {
4758 if_statement_t const* const ifs = &stmt->ifs;
4759 int const val = determine_truth(ifs->condition);
4762 check_reachable(ifs->true_statement);
4767 if (ifs->false_statement != NULL) {
4768 check_reachable(ifs->false_statement);
4772 next = stmt->base.next;
4776 case STATEMENT_SWITCH: {
4777 switch_statement_t const *const switchs = &stmt->switchs;
4778 expression_t const *const expr = switchs->expression;
4780 if (is_constant_expression(expr)) {
4781 long const val = fold_constant(expr);
4782 case_label_statement_t * defaults = NULL;
4783 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4784 if (i->expression == NULL) {
4789 if (i->first_case <= val && val <= i->last_case) {
4790 check_reachable((statement_t*)i);
4795 if (defaults != NULL) {
4796 check_reachable((statement_t*)defaults);
4800 bool has_default = false;
4801 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4802 if (i->expression == NULL)
4805 check_reachable((statement_t*)i);
4812 next = stmt->base.next;
4816 case STATEMENT_EXPRESSION: {
4817 /* Check for noreturn function call */
4818 expression_t const *const expr = stmt->expression.expression;
4819 if (expr->kind == EXPR_CALL) {
4820 expression_t const *const func = expr->call.function;
4821 if (func->kind == EXPR_REFERENCE) {
4822 declaration_t const *const decl = func->reference.declaration;
4823 if (decl != NULL && decl->modifiers & DM_NORETURN) {
4829 next = stmt->base.next;
4833 case STATEMENT_CONTINUE: {
4834 statement_t *parent = stmt;
4836 parent = parent->base.parent;
4837 if (parent == NULL) /* continue not within loop */
4841 switch (parent->kind) {
4842 case STATEMENT_WHILE: goto continue_while;
4843 case STATEMENT_DO_WHILE: goto continue_do_while;
4844 case STATEMENT_FOR: goto continue_for;
4851 case STATEMENT_BREAK: {
4852 statement_t *parent = stmt;
4854 parent = parent->base.parent;
4855 if (parent == NULL) /* break not within loop/switch */
4858 switch (parent->kind) {
4859 case STATEMENT_SWITCH:
4860 case STATEMENT_WHILE:
4861 case STATEMENT_DO_WHILE:
4864 next = parent->base.next;
4865 goto found_break_parent;
4874 case STATEMENT_GOTO:
4875 next = stmt->gotos.label->init.statement;
4876 if (next == NULL) /* missing label */
4880 case STATEMENT_LABEL:
4881 next = stmt->label.statement;
4884 case STATEMENT_CASE_LABEL:
4885 next = stmt->case_label.statement;
4888 case STATEMENT_WHILE: {
4889 while_statement_t const *const whiles = &stmt->whiles;
4890 int const val = determine_truth(whiles->condition);
4893 check_reachable(whiles->body);
4898 next = stmt->base.next;
4902 case STATEMENT_DO_WHILE:
4903 next = stmt->do_while.body;
4906 case STATEMENT_FOR: {
4907 for_statement_t *const fors = &stmt->fors;
4909 if (fors->condition_reachable)
4911 fors->condition_reachable = true;
4913 expression_t const *const cond = fors->condition;
4915 cond == NULL ? 1 : determine_truth(cond);
4918 check_reachable(fors->body);
4923 next = stmt->base.next;
4927 case STATEMENT_MS_TRY:
4928 case STATEMENT_LEAVE:
4929 panic("unimplemented");
4932 while (next == NULL) {
4933 next = last->base.parent;
4935 noreturn_candidate = false;
4937 type_t *const type = current_function->type;
4938 assert(is_type_function(type));
4939 type_t *const ret = skip_typeref(type->function.return_type);
4940 if (warning.return_type &&
4941 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
4942 is_type_valid(ret) &&
4943 !is_sym_main(current_function->symbol)) {
4944 warningf(&stmt->base.source_position,
4945 "control reaches end of non-void function");
4950 switch (next->kind) {
4951 case STATEMENT_INVALID:
4952 case STATEMENT_EMPTY:
4953 case STATEMENT_DECLARATION:
4954 case STATEMENT_EXPRESSION:
4956 case STATEMENT_RETURN:
4957 case STATEMENT_CONTINUE:
4958 case STATEMENT_BREAK:
4959 case STATEMENT_GOTO:
4960 case STATEMENT_LEAVE:
4961 panic("invalid control flow in function");
4963 case STATEMENT_COMPOUND:
4965 case STATEMENT_SWITCH:
4966 case STATEMENT_LABEL:
4967 case STATEMENT_CASE_LABEL:
4969 next = next->base.next;
4972 case STATEMENT_WHILE: {
4974 if (next->base.reachable)
4976 next->base.reachable = true;
4978 while_statement_t const *const whiles = &next->whiles;
4979 int const val = determine_truth(whiles->condition);
4982 check_reachable(whiles->body);
4988 next = next->base.next;
4992 case STATEMENT_DO_WHILE: {
4994 if (next->base.reachable)
4996 next->base.reachable = true;
4998 do_while_statement_t const *const dw = &next->do_while;
4999 int const val = determine_truth(dw->condition);
5002 check_reachable(dw->body);
5008 next = next->base.next;
5012 case STATEMENT_FOR: {
5014 for_statement_t *const fors = &next->fors;
5016 fors->step_reachable = true;
5018 if (fors->condition_reachable)
5020 fors->condition_reachable = true;
5022 expression_t const *const cond = fors->condition;
5024 cond == NULL ? 1 : determine_truth(cond);
5027 check_reachable(fors->body);
5033 next = next->base.next;
5037 case STATEMENT_MS_TRY:
5038 panic("unimplemented");
5043 next = stmt->base.parent;
5045 warningf(&stmt->base.source_position,
5046 "control reaches end of non-void function");
5050 check_reachable(next);
5053 static void check_unreachable(statement_t const* const stmt)
5055 if (!stmt->base.reachable &&
5056 stmt->kind != STATEMENT_COMPOUND &&
5057 stmt->kind != STATEMENT_DO_WHILE &&
5058 stmt->kind != STATEMENT_FOR) {
5059 warningf(&stmt->base.source_position, "statement is unreachable");
5062 switch (stmt->kind) {
5063 case STATEMENT_INVALID:
5064 case STATEMENT_EMPTY:
5065 case STATEMENT_RETURN:
5066 case STATEMENT_DECLARATION:
5067 case STATEMENT_EXPRESSION:
5068 case STATEMENT_CONTINUE:
5069 case STATEMENT_BREAK:
5070 case STATEMENT_GOTO:
5072 case STATEMENT_LEAVE:
5075 case STATEMENT_COMPOUND:
5076 if (stmt->compound.statements)
5077 check_unreachable(stmt->compound.statements);
5081 check_unreachable(stmt->ifs.true_statement);
5082 if (stmt->ifs.false_statement != NULL)
5083 check_unreachable(stmt->ifs.false_statement);
5086 case STATEMENT_SWITCH:
5087 check_unreachable(stmt->switchs.body);
5090 case STATEMENT_LABEL:
5091 check_unreachable(stmt->label.statement);
5094 case STATEMENT_CASE_LABEL:
5095 check_unreachable(stmt->case_label.statement);
5098 case STATEMENT_WHILE:
5099 check_unreachable(stmt->whiles.body);
5102 case STATEMENT_DO_WHILE:
5103 check_unreachable(stmt->do_while.body);
5104 if (!stmt->base.reachable) {
5105 expression_t const *const cond = stmt->do_while.condition;
5106 if (determine_truth(cond) >= 0) {
5107 warningf(&cond->base.source_position,
5108 "condition of do-while-loop is unreachable");
5113 case STATEMENT_FOR: {
5114 for_statement_t const* const fors = &stmt->fors;
5116 // if init and step are unreachable, cond is unreachable, too
5117 if (!stmt->base.reachable && !fors->step_reachable) {
5118 warningf(&stmt->base.source_position, "statement is unreachable");
5120 if (!stmt->base.reachable && fors->initialisation != NULL) {
5121 warningf(&fors->initialisation->base.source_position,
5122 "initialisation of for-statement is unreachable");
5125 if (!fors->condition_reachable && fors->condition != NULL) {
5126 warningf(&fors->condition->base.source_position,
5127 "condition of for-statement is unreachable");
5130 if (!fors->step_reachable && fors->step != NULL) {
5131 warningf(&fors->step->base.source_position,
5132 "step of for-statement is unreachable");
5136 check_unreachable(stmt->fors.body);
5140 case STATEMENT_MS_TRY:
5141 panic("unimplemented");
5144 if (stmt->base.next)
5145 check_unreachable(stmt->base.next);
5148 static void parse_external_declaration(void)
5150 /* function-definitions and declarations both start with declaration
5152 declaration_specifiers_t specifiers;
5153 memset(&specifiers, 0, sizeof(specifiers));
5155 add_anchor_token(';');
5156 parse_declaration_specifiers(&specifiers);
5157 rem_anchor_token(';');
5159 /* must be a declaration */
5160 if (token.type == ';') {
5161 parse_anonymous_declaration_rest(&specifiers, append_declaration);
5165 add_anchor_token(',');
5166 add_anchor_token('=');
5167 rem_anchor_token(';');
5169 /* declarator is common to both function-definitions and declarations */
5170 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5172 rem_anchor_token(',');
5173 rem_anchor_token('=');
5174 rem_anchor_token(';');
5176 /* must be a declaration */
5177 switch (token.type) {
5180 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5184 parse_declaration_rest(ndeclaration, &specifiers, record_definition);
5188 /* must be a function definition */
5189 parse_kr_declaration_list(ndeclaration);
5191 if (token.type != '{') {
5192 parse_error_expected("while parsing function definition", '{', NULL);
5193 eat_until_matching_token(';');
5197 type_t *type = ndeclaration->type;
5199 /* note that we don't skip typerefs: the standard doesn't allow them here
5200 * (so we can't use is_type_function here) */
5201 if (type->kind != TYPE_FUNCTION) {
5202 if (is_type_valid(type)) {
5203 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5204 type, ndeclaration->symbol);
5210 /* § 6.7.5.3 (14) a function definition with () means no
5211 * parameters (and not unspecified parameters) */
5212 if (type->function.unspecified_parameters
5213 && type->function.parameters == NULL
5214 && !type->function.kr_style_parameters) {
5215 type_t *duplicate = duplicate_type(type);
5216 duplicate->function.unspecified_parameters = false;
5218 type = typehash_insert(duplicate);
5219 if (type != duplicate) {
5220 obstack_free(type_obst, duplicate);
5222 ndeclaration->type = type;
5225 declaration_t *const declaration = record_definition(ndeclaration);
5226 if (ndeclaration != declaration) {
5227 declaration->scope = ndeclaration->scope;
5229 type = skip_typeref(declaration->type);
5231 /* push function parameters and switch scope */
5232 int top = environment_top();
5233 scope_t *last_scope = scope;
5234 set_scope(&declaration->scope);
5236 declaration_t *parameter = declaration->scope.declarations;
5237 for( ; parameter != NULL; parameter = parameter->next) {
5238 if (parameter->parent_scope == &ndeclaration->scope) {
5239 parameter->parent_scope = scope;
5241 assert(parameter->parent_scope == NULL
5242 || parameter->parent_scope == scope);
5243 parameter->parent_scope = scope;
5244 if (parameter->symbol == NULL) {
5245 errorf(¶meter->source_position, "parameter name omitted");
5248 environment_push(parameter);
5251 if (declaration->init.statement != NULL) {
5252 parser_error_multiple_definition(declaration, HERE);
5255 /* parse function body */
5256 int label_stack_top = label_top();
5257 declaration_t *old_current_function = current_function;
5258 current_function = declaration;
5259 current_parent = NULL;
5261 statement_t *const body = parse_compound_statement(false);
5262 declaration->init.statement = body;
5265 check_declarations();
5266 if (warning.return_type ||
5267 warning.unreachable_code ||
5268 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5269 noreturn_candidate = true;
5270 check_reachable(body);
5271 if (warning.unreachable_code)
5272 check_unreachable(body);
5273 if (warning.missing_noreturn &&
5274 noreturn_candidate &&
5275 !(declaration->modifiers & DM_NORETURN)) {
5276 warningf(&body->base.source_position,
5277 "function '%#T' is candidate for attribute 'noreturn'",
5278 type, declaration->symbol);
5282 assert(current_parent == NULL);
5283 assert(current_function == declaration);
5284 current_function = old_current_function;
5285 label_pop_to(label_stack_top);
5288 assert(scope == &declaration->scope);
5289 set_scope(last_scope);
5290 environment_pop_to(top);
5293 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5294 source_position_t *source_position)
5296 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5298 type->bitfield.base_type = base_type;
5299 type->bitfield.size = size;
5304 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5307 declaration_t *iter = compound_declaration->scope.declarations;
5308 for( ; iter != NULL; iter = iter->next) {
5309 if (iter->namespc != NAMESPACE_NORMAL)
5312 if (iter->symbol == NULL) {
5313 type_t *type = skip_typeref(iter->type);
5314 if (is_type_compound(type)) {
5315 declaration_t *result
5316 = find_compound_entry(type->compound.declaration, symbol);
5323 if (iter->symbol == symbol) {
5331 static void parse_compound_declarators(declaration_t *struct_declaration,
5332 const declaration_specifiers_t *specifiers)
5334 declaration_t *last_declaration = struct_declaration->scope.declarations;
5335 if (last_declaration != NULL) {
5336 while(last_declaration->next != NULL) {
5337 last_declaration = last_declaration->next;
5342 declaration_t *declaration;
5344 if (token.type == ':') {
5345 source_position_t source_position = *HERE;
5348 type_t *base_type = specifiers->type;
5349 expression_t *size = parse_constant_expression();
5351 if (!is_type_integer(skip_typeref(base_type))) {
5352 errorf(HERE, "bitfield base type '%T' is not an integer type",
5356 type_t *type = make_bitfield_type(base_type, size, &source_position);
5358 declaration = allocate_declaration_zero();
5359 declaration->namespc = NAMESPACE_NORMAL;
5360 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5361 declaration->storage_class = STORAGE_CLASS_NONE;
5362 declaration->source_position = source_position;
5363 declaration->modifiers = specifiers->modifiers;
5364 declaration->type = type;
5366 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5368 type_t *orig_type = declaration->type;
5369 type_t *type = skip_typeref(orig_type);
5371 if (token.type == ':') {
5372 source_position_t source_position = *HERE;
5374 expression_t *size = parse_constant_expression();
5376 if (!is_type_integer(type)) {
5377 errorf(HERE, "bitfield base type '%T' is not an "
5378 "integer type", orig_type);
5381 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5382 declaration->type = bitfield_type;
5384 /* TODO we ignore arrays for now... what is missing is a check
5385 * that they're at the end of the struct */
5386 if (is_type_incomplete(type) && !is_type_array(type)) {
5388 "compound member '%Y' has incomplete type '%T'",
5389 declaration->symbol, orig_type);
5390 } else if (is_type_function(type)) {
5391 errorf(HERE, "compound member '%Y' must not have function "
5392 "type '%T'", declaration->symbol, orig_type);
5397 /* make sure we don't define a symbol multiple times */
5398 symbol_t *symbol = declaration->symbol;
5399 if (symbol != NULL) {
5400 declaration_t *prev_decl
5401 = find_compound_entry(struct_declaration, symbol);
5403 if (prev_decl != NULL) {
5404 assert(prev_decl->symbol == symbol);
5405 errorf(&declaration->source_position,
5406 "multiple declarations of symbol '%Y' (declared %P)",
5407 symbol, &prev_decl->source_position);
5411 /* append declaration */
5412 if (last_declaration != NULL) {
5413 last_declaration->next = declaration;
5415 struct_declaration->scope.declarations = declaration;
5417 last_declaration = declaration;
5419 if (token.type != ',')
5429 static void parse_compound_type_entries(declaration_t *compound_declaration)
5432 add_anchor_token('}');
5434 while(token.type != '}' && token.type != T_EOF) {
5435 declaration_specifiers_t specifiers;
5436 memset(&specifiers, 0, sizeof(specifiers));
5437 parse_declaration_specifiers(&specifiers);
5439 parse_compound_declarators(compound_declaration, &specifiers);
5441 rem_anchor_token('}');
5443 if (token.type == T_EOF) {
5444 errorf(HERE, "EOF while parsing struct");
5449 static type_t *parse_typename(void)
5451 declaration_specifiers_t specifiers;
5452 memset(&specifiers, 0, sizeof(specifiers));
5453 parse_declaration_specifiers(&specifiers);
5454 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5455 /* TODO: improve error message, user does probably not know what a
5456 * storage class is...
5458 errorf(HERE, "typename may not have a storage class");
5461 type_t *result = parse_abstract_declarator(specifiers.type);
5469 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5470 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5471 expression_t *left);
5473 typedef struct expression_parser_function_t expression_parser_function_t;
5474 struct expression_parser_function_t {
5475 unsigned precedence;
5476 parse_expression_function parser;
5477 unsigned infix_precedence;
5478 parse_expression_infix_function infix_parser;
5481 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5484 * Prints an error message if an expression was expected but not read
5486 static expression_t *expected_expression_error(void)
5488 /* skip the error message if the error token was read */
5489 if (token.type != T_ERROR) {
5490 errorf(HERE, "expected expression, got token '%K'", &token);
5494 return create_invalid_expression();
5498 * Parse a string constant.
5500 static expression_t *parse_string_const(void)
5503 if (token.type == T_STRING_LITERAL) {
5504 string_t res = token.v.string;
5506 while (token.type == T_STRING_LITERAL) {
5507 res = concat_strings(&res, &token.v.string);
5510 if (token.type != T_WIDE_STRING_LITERAL) {
5511 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5512 /* note: that we use type_char_ptr here, which is already the
5513 * automatic converted type. revert_automatic_type_conversion
5514 * will construct the array type */
5515 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5516 cnst->string.value = res;
5520 wres = concat_string_wide_string(&res, &token.v.wide_string);
5522 wres = token.v.wide_string;
5527 switch (token.type) {
5528 case T_WIDE_STRING_LITERAL:
5529 wres = concat_wide_strings(&wres, &token.v.wide_string);
5532 case T_STRING_LITERAL:
5533 wres = concat_wide_string_string(&wres, &token.v.string);
5537 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5538 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_wchar_t_ptr;
5539 cnst->wide_string.value = wres;
5548 * Parse an integer constant.
5550 static expression_t *parse_int_const(void)
5552 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5553 cnst->base.source_position = *HERE;
5554 cnst->base.type = token.datatype;
5555 cnst->conste.v.int_value = token.v.intvalue;
5563 * Parse a character constant.
5565 static expression_t *parse_character_constant(void)
5567 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5569 cnst->base.source_position = *HERE;
5570 cnst->base.type = token.datatype;
5571 cnst->conste.v.character = token.v.string;
5573 if (cnst->conste.v.character.size != 1) {
5574 if (warning.multichar && (c_mode & _GNUC)) {
5576 warningf(HERE, "multi-character character constant");
5578 errorf(HERE, "more than 1 characters in character constant");
5587 * Parse a wide character constant.
5589 static expression_t *parse_wide_character_constant(void)
5591 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5593 cnst->base.source_position = *HERE;
5594 cnst->base.type = token.datatype;
5595 cnst->conste.v.wide_character = token.v.wide_string;
5597 if (cnst->conste.v.wide_character.size != 1) {
5598 if (warning.multichar && (c_mode & _GNUC)) {
5600 warningf(HERE, "multi-character character constant");
5602 errorf(HERE, "more than 1 characters in character constant");
5611 * Parse a float constant.
5613 static expression_t *parse_float_const(void)
5615 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5616 cnst->base.type = token.datatype;
5617 cnst->conste.v.float_value = token.v.floatvalue;
5624 static declaration_t *create_implicit_function(symbol_t *symbol,
5625 const source_position_t *source_position)
5627 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5628 ntype->function.return_type = type_int;
5629 ntype->function.unspecified_parameters = true;
5631 type_t *type = typehash_insert(ntype);
5632 if (type != ntype) {
5636 declaration_t *const declaration = allocate_declaration_zero();
5637 declaration->storage_class = STORAGE_CLASS_EXTERN;
5638 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5639 declaration->type = type;
5640 declaration->symbol = symbol;
5641 declaration->source_position = *source_position;
5643 bool strict_prototypes_old = warning.strict_prototypes;
5644 warning.strict_prototypes = false;
5645 record_declaration(declaration);
5646 warning.strict_prototypes = strict_prototypes_old;
5652 * Creates a return_type (func)(argument_type) function type if not
5655 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5656 type_t *argument_type2)
5658 function_parameter_t *parameter2
5659 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5660 memset(parameter2, 0, sizeof(parameter2[0]));
5661 parameter2->type = argument_type2;
5663 function_parameter_t *parameter1
5664 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5665 memset(parameter1, 0, sizeof(parameter1[0]));
5666 parameter1->type = argument_type1;
5667 parameter1->next = parameter2;
5669 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5670 type->function.return_type = return_type;
5671 type->function.parameters = parameter1;
5673 type_t *result = typehash_insert(type);
5674 if (result != type) {
5682 * Creates a return_type (func)(argument_type) function type if not
5685 * @param return_type the return type
5686 * @param argument_type the argument type
5688 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5690 function_parameter_t *parameter
5691 = obstack_alloc(type_obst, sizeof(parameter[0]));
5692 memset(parameter, 0, sizeof(parameter[0]));
5693 parameter->type = argument_type;
5695 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5696 type->function.return_type = return_type;
5697 type->function.parameters = parameter;
5699 type_t *result = typehash_insert(type);
5700 if (result != type) {
5707 static type_t *make_function_0_type(type_t *return_type)
5709 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5710 type->function.return_type = return_type;
5711 type->function.parameters = NULL;
5713 type_t *result = typehash_insert(type);
5714 if (result != type) {
5722 * Creates a function type for some function like builtins.
5724 * @param symbol the symbol describing the builtin
5726 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5728 switch(symbol->ID) {
5729 case T___builtin_alloca:
5730 return make_function_1_type(type_void_ptr, type_size_t);
5731 case T___builtin_huge_val:
5732 return make_function_0_type(type_double);
5733 case T___builtin_nan:
5734 return make_function_1_type(type_double, type_char_ptr);
5735 case T___builtin_nanf:
5736 return make_function_1_type(type_float, type_char_ptr);
5737 case T___builtin_nand:
5738 return make_function_1_type(type_long_double, type_char_ptr);
5739 case T___builtin_va_end:
5740 return make_function_1_type(type_void, type_valist);
5741 case T___builtin_expect:
5742 return make_function_2_type(type_long, type_long, type_long);
5744 internal_errorf(HERE, "not implemented builtin symbol found");
5749 * Performs automatic type cast as described in § 6.3.2.1.
5751 * @param orig_type the original type
5753 static type_t *automatic_type_conversion(type_t *orig_type)
5755 type_t *type = skip_typeref(orig_type);
5756 if (is_type_array(type)) {
5757 array_type_t *array_type = &type->array;
5758 type_t *element_type = array_type->element_type;
5759 unsigned qualifiers = array_type->base.qualifiers;
5761 return make_pointer_type(element_type, qualifiers);
5764 if (is_type_function(type)) {
5765 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5772 * reverts the automatic casts of array to pointer types and function
5773 * to function-pointer types as defined § 6.3.2.1
5775 type_t *revert_automatic_type_conversion(const expression_t *expression)
5777 switch (expression->kind) {
5778 case EXPR_REFERENCE: return expression->reference.declaration->type;
5779 case EXPR_SELECT: return expression->select.compound_entry->type;
5781 case EXPR_UNARY_DEREFERENCE: {
5782 const expression_t *const value = expression->unary.value;
5783 type_t *const type = skip_typeref(value->base.type);
5784 assert(is_type_pointer(type));
5785 return type->pointer.points_to;
5788 case EXPR_BUILTIN_SYMBOL:
5789 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5791 case EXPR_ARRAY_ACCESS: {
5792 const expression_t *array_ref = expression->array_access.array_ref;
5793 type_t *type_left = skip_typeref(array_ref->base.type);
5794 if (!is_type_valid(type_left))
5796 assert(is_type_pointer(type_left));
5797 return type_left->pointer.points_to;
5800 case EXPR_STRING_LITERAL: {
5801 size_t size = expression->string.value.size;
5802 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5805 case EXPR_WIDE_STRING_LITERAL: {
5806 size_t size = expression->wide_string.value.size;
5807 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5810 case EXPR_COMPOUND_LITERAL:
5811 return expression->compound_literal.type;
5816 return expression->base.type;
5819 static expression_t *parse_reference(void)
5821 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5823 reference_expression_t *ref = &expression->reference;
5824 symbol_t *const symbol = token.v.symbol;
5826 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5828 source_position_t source_position = token.source_position;
5831 if (declaration == NULL) {
5832 if (! strict_mode && token.type == '(') {
5833 /* an implicitly defined function */
5834 if (warning.implicit_function_declaration) {
5835 warningf(HERE, "implicit declaration of function '%Y'",
5839 declaration = create_implicit_function(symbol,
5842 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5843 return create_invalid_expression();
5847 type_t *type = declaration->type;
5849 /* we always do the auto-type conversions; the & and sizeof parser contains
5850 * code to revert this! */
5851 type = automatic_type_conversion(type);
5853 ref->declaration = declaration;
5854 ref->base.type = type;
5856 /* this declaration is used */
5857 declaration->used = true;
5859 /* check for deprecated functions */
5860 if (warning.deprecated_declarations &&
5861 declaration->modifiers & DM_DEPRECATED) {
5862 char const *const prefix = is_type_function(declaration->type) ?
5863 "function" : "variable";
5865 if (declaration->deprecated_string != NULL) {
5866 warningf(&source_position,
5867 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
5868 declaration->symbol, &declaration->source_position,
5869 declaration->deprecated_string);
5871 warningf(&source_position,
5872 "%s '%Y' is deprecated (declared %P)", prefix,
5873 declaration->symbol, &declaration->source_position);
5880 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5884 /* TODO check if explicit cast is allowed and issue warnings/errors */
5887 static expression_t *parse_compound_literal(type_t *type)
5889 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5891 parse_initializer_env_t env;
5893 env.declaration = NULL;
5894 env.must_be_constant = false;
5895 initializer_t *initializer = parse_initializer(&env);
5898 expression->compound_literal.initializer = initializer;
5899 expression->compound_literal.type = type;
5900 expression->base.type = automatic_type_conversion(type);
5906 * Parse a cast expression.
5908 static expression_t *parse_cast(void)
5910 source_position_t source_position = token.source_position;
5912 type_t *type = parse_typename();
5914 /* matching add_anchor_token() is at call site */
5915 rem_anchor_token(')');
5918 if (token.type == '{') {
5919 return parse_compound_literal(type);
5922 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5923 cast->base.source_position = source_position;
5925 expression_t *value = parse_sub_expression(20);
5927 check_cast_allowed(value, type);
5929 cast->base.type = type;
5930 cast->unary.value = value;
5934 return create_invalid_expression();
5938 * Parse a statement expression.
5940 static expression_t *parse_statement_expression(void)
5942 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5944 statement_t *statement = parse_compound_statement(true);
5945 expression->statement.statement = statement;
5946 expression->base.source_position = statement->base.source_position;
5948 /* find last statement and use its type */
5949 type_t *type = type_void;
5950 const statement_t *stmt = statement->compound.statements;
5952 while (stmt->base.next != NULL)
5953 stmt = stmt->base.next;
5955 if (stmt->kind == STATEMENT_EXPRESSION) {
5956 type = stmt->expression.expression->base.type;
5959 warningf(&expression->base.source_position, "empty statement expression ({})");
5961 expression->base.type = type;
5967 return create_invalid_expression();
5971 * Parse a braced expression.
5973 static expression_t *parse_brace_expression(void)
5976 add_anchor_token(')');
5978 switch(token.type) {
5980 /* gcc extension: a statement expression */
5981 return parse_statement_expression();
5985 return parse_cast();
5987 if (is_typedef_symbol(token.v.symbol)) {
5988 return parse_cast();
5992 expression_t *result = parse_expression();
5993 rem_anchor_token(')');
5998 return create_invalid_expression();
6001 static expression_t *parse_function_keyword(void)
6006 if (current_function == NULL) {
6007 errorf(HERE, "'__func__' used outside of a function");
6010 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6011 expression->base.type = type_char_ptr;
6012 expression->funcname.kind = FUNCNAME_FUNCTION;
6017 static expression_t *parse_pretty_function_keyword(void)
6019 eat(T___PRETTY_FUNCTION__);
6021 if (current_function == NULL) {
6022 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6025 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6026 expression->base.type = type_char_ptr;
6027 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6032 static expression_t *parse_funcsig_keyword(void)
6036 if (current_function == NULL) {
6037 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6040 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6041 expression->base.type = type_char_ptr;
6042 expression->funcname.kind = FUNCNAME_FUNCSIG;
6047 static expression_t *parse_funcdname_keyword(void)
6049 eat(T___FUNCDNAME__);
6051 if (current_function == NULL) {
6052 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6055 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6056 expression->base.type = type_char_ptr;
6057 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6062 static designator_t *parse_designator(void)
6064 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6065 result->source_position = *HERE;
6067 if (token.type != T_IDENTIFIER) {
6068 parse_error_expected("while parsing member designator",
6069 T_IDENTIFIER, NULL);
6072 result->symbol = token.v.symbol;
6075 designator_t *last_designator = result;
6077 if (token.type == '.') {
6079 if (token.type != T_IDENTIFIER) {
6080 parse_error_expected("while parsing member designator",
6081 T_IDENTIFIER, NULL);
6084 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6085 designator->source_position = *HERE;
6086 designator->symbol = token.v.symbol;
6089 last_designator->next = designator;
6090 last_designator = designator;
6093 if (token.type == '[') {
6095 add_anchor_token(']');
6096 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6097 designator->source_position = *HERE;
6098 designator->array_index = parse_expression();
6099 rem_anchor_token(']');
6101 if (designator->array_index == NULL) {
6105 last_designator->next = designator;
6106 last_designator = designator;
6118 * Parse the __builtin_offsetof() expression.
6120 static expression_t *parse_offsetof(void)
6122 eat(T___builtin_offsetof);
6124 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6125 expression->base.type = type_size_t;
6128 add_anchor_token(',');
6129 type_t *type = parse_typename();
6130 rem_anchor_token(',');
6132 add_anchor_token(')');
6133 designator_t *designator = parse_designator();
6134 rem_anchor_token(')');
6137 expression->offsetofe.type = type;
6138 expression->offsetofe.designator = designator;
6141 memset(&path, 0, sizeof(path));
6142 path.top_type = type;
6143 path.path = NEW_ARR_F(type_path_entry_t, 0);
6145 descend_into_subtype(&path);
6147 if (!walk_designator(&path, designator, true)) {
6148 return create_invalid_expression();
6151 DEL_ARR_F(path.path);
6155 return create_invalid_expression();
6159 * Parses a _builtin_va_start() expression.
6161 static expression_t *parse_va_start(void)
6163 eat(T___builtin_va_start);
6165 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6168 add_anchor_token(',');
6169 expression->va_starte.ap = parse_assignment_expression();
6170 rem_anchor_token(',');
6172 expression_t *const expr = parse_assignment_expression();
6173 if (expr->kind == EXPR_REFERENCE) {
6174 declaration_t *const decl = expr->reference.declaration;
6176 return create_invalid_expression();
6177 if (decl->parent_scope == ¤t_function->scope &&
6178 decl->next == NULL) {
6179 expression->va_starte.parameter = decl;
6184 errorf(&expr->base.source_position,
6185 "second argument of 'va_start' must be last parameter of the current function");
6187 return create_invalid_expression();
6191 * Parses a _builtin_va_arg() expression.
6193 static expression_t *parse_va_arg(void)
6195 eat(T___builtin_va_arg);
6197 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6200 expression->va_arge.ap = parse_assignment_expression();
6202 expression->base.type = parse_typename();
6207 return create_invalid_expression();
6210 static expression_t *parse_builtin_symbol(void)
6212 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6214 symbol_t *symbol = token.v.symbol;
6216 expression->builtin_symbol.symbol = symbol;
6219 type_t *type = get_builtin_symbol_type(symbol);
6220 type = automatic_type_conversion(type);
6222 expression->base.type = type;
6227 * Parses a __builtin_constant() expression.
6229 static expression_t *parse_builtin_constant(void)
6231 eat(T___builtin_constant_p);
6233 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6236 add_anchor_token(')');
6237 expression->builtin_constant.value = parse_assignment_expression();
6238 rem_anchor_token(')');
6240 expression->base.type = type_int;
6244 return create_invalid_expression();
6248 * Parses a __builtin_prefetch() expression.
6250 static expression_t *parse_builtin_prefetch(void)
6252 eat(T___builtin_prefetch);
6254 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6257 add_anchor_token(')');
6258 expression->builtin_prefetch.adr = parse_assignment_expression();
6259 if (token.type == ',') {
6261 expression->builtin_prefetch.rw = parse_assignment_expression();
6263 if (token.type == ',') {
6265 expression->builtin_prefetch.locality = parse_assignment_expression();
6267 rem_anchor_token(')');
6269 expression->base.type = type_void;
6273 return create_invalid_expression();
6277 * Parses a __builtin_is_*() compare expression.
6279 static expression_t *parse_compare_builtin(void)
6281 expression_t *expression;
6283 switch(token.type) {
6284 case T___builtin_isgreater:
6285 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6287 case T___builtin_isgreaterequal:
6288 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6290 case T___builtin_isless:
6291 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6293 case T___builtin_islessequal:
6294 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6296 case T___builtin_islessgreater:
6297 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6299 case T___builtin_isunordered:
6300 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6303 internal_errorf(HERE, "invalid compare builtin found");
6306 expression->base.source_position = *HERE;
6310 expression->binary.left = parse_assignment_expression();
6312 expression->binary.right = parse_assignment_expression();
6315 type_t *const orig_type_left = expression->binary.left->base.type;
6316 type_t *const orig_type_right = expression->binary.right->base.type;
6318 type_t *const type_left = skip_typeref(orig_type_left);
6319 type_t *const type_right = skip_typeref(orig_type_right);
6320 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6321 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6322 type_error_incompatible("invalid operands in comparison",
6323 &expression->base.source_position, orig_type_left, orig_type_right);
6326 semantic_comparison(&expression->binary);
6331 return create_invalid_expression();
6336 * Parses a __builtin_expect() expression.
6338 static expression_t *parse_builtin_expect(void)
6340 eat(T___builtin_expect);
6342 expression_t *expression
6343 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6346 expression->binary.left = parse_assignment_expression();
6348 expression->binary.right = parse_constant_expression();
6351 expression->base.type = expression->binary.left->base.type;
6355 return create_invalid_expression();
6360 * Parses a MS assume() expression.
6362 static expression_t *parse_assume(void)
6366 expression_t *expression
6367 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6370 add_anchor_token(')');
6371 expression->unary.value = parse_assignment_expression();
6372 rem_anchor_token(')');
6375 expression->base.type = type_void;
6378 return create_invalid_expression();
6382 * Parse a microsoft __noop expression.
6384 static expression_t *parse_noop_expression(void)
6386 source_position_t source_position = *HERE;
6389 if (token.type == '(') {
6390 /* parse arguments */
6392 add_anchor_token(')');
6393 add_anchor_token(',');
6395 if (token.type != ')') {
6397 (void)parse_assignment_expression();
6398 if (token.type != ',')
6404 rem_anchor_token(',');
6405 rem_anchor_token(')');
6408 /* the result is a (int)0 */
6409 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6410 cnst->base.source_position = source_position;
6411 cnst->base.type = type_int;
6412 cnst->conste.v.int_value = 0;
6413 cnst->conste.is_ms_noop = true;
6418 return create_invalid_expression();
6422 * Parses a primary expression.
6424 static expression_t *parse_primary_expression(void)
6426 switch (token.type) {
6427 case T_INTEGER: return parse_int_const();
6428 case T_CHARACTER_CONSTANT: return parse_character_constant();
6429 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6430 case T_FLOATINGPOINT: return parse_float_const();
6431 case T_STRING_LITERAL:
6432 case T_WIDE_STRING_LITERAL: return parse_string_const();
6433 case T_IDENTIFIER: return parse_reference();
6434 case T___FUNCTION__:
6435 case T___func__: return parse_function_keyword();
6436 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6437 case T___FUNCSIG__: return parse_funcsig_keyword();
6438 case T___FUNCDNAME__: return parse_funcdname_keyword();
6439 case T___builtin_offsetof: return parse_offsetof();
6440 case T___builtin_va_start: return parse_va_start();
6441 case T___builtin_va_arg: return parse_va_arg();
6442 case T___builtin_expect:
6443 case T___builtin_alloca:
6444 case T___builtin_nan:
6445 case T___builtin_nand:
6446 case T___builtin_nanf:
6447 case T___builtin_huge_val:
6448 case T___builtin_va_end: return parse_builtin_symbol();
6449 case T___builtin_isgreater:
6450 case T___builtin_isgreaterequal:
6451 case T___builtin_isless:
6452 case T___builtin_islessequal:
6453 case T___builtin_islessgreater:
6454 case T___builtin_isunordered: return parse_compare_builtin();
6455 case T___builtin_constant_p: return parse_builtin_constant();
6456 case T___builtin_prefetch: return parse_builtin_prefetch();
6457 case T__assume: return parse_assume();
6459 case '(': return parse_brace_expression();
6460 case T___noop: return parse_noop_expression();
6463 errorf(HERE, "unexpected token %K, expected an expression", &token);
6464 return create_invalid_expression();
6468 * Check if the expression has the character type and issue a warning then.
6470 static void check_for_char_index_type(const expression_t *expression)
6472 type_t *const type = expression->base.type;
6473 const type_t *const base_type = skip_typeref(type);
6475 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6476 warning.char_subscripts) {
6477 warningf(&expression->base.source_position,
6478 "array subscript has type '%T'", type);
6482 static expression_t *parse_array_expression(unsigned precedence,
6488 add_anchor_token(']');
6490 expression_t *inside = parse_expression();
6492 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6494 array_access_expression_t *array_access = &expression->array_access;
6496 type_t *const orig_type_left = left->base.type;
6497 type_t *const orig_type_inside = inside->base.type;
6499 type_t *const type_left = skip_typeref(orig_type_left);
6500 type_t *const type_inside = skip_typeref(orig_type_inside);
6502 type_t *return_type;
6503 if (is_type_pointer(type_left)) {
6504 return_type = type_left->pointer.points_to;
6505 array_access->array_ref = left;
6506 array_access->index = inside;
6507 check_for_char_index_type(inside);
6508 } else if (is_type_pointer(type_inside)) {
6509 return_type = type_inside->pointer.points_to;
6510 array_access->array_ref = inside;
6511 array_access->index = left;
6512 array_access->flipped = true;
6513 check_for_char_index_type(left);
6515 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6517 "array access on object with non-pointer types '%T', '%T'",
6518 orig_type_left, orig_type_inside);
6520 return_type = type_error_type;
6521 array_access->array_ref = create_invalid_expression();
6524 rem_anchor_token(']');
6525 if (token.type != ']') {
6526 parse_error_expected("Problem while parsing array access", ']', NULL);
6531 return_type = automatic_type_conversion(return_type);
6532 expression->base.type = return_type;
6537 static expression_t *parse_typeprop(expression_kind_t const kind,
6538 source_position_t const pos,
6539 unsigned const precedence)
6541 expression_t *tp_expression = allocate_expression_zero(kind);
6542 tp_expression->base.type = type_size_t;
6543 tp_expression->base.source_position = pos;
6545 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6547 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6549 add_anchor_token(')');
6550 type_t* const orig_type = parse_typename();
6551 tp_expression->typeprop.type = orig_type;
6553 type_t const* const type = skip_typeref(orig_type);
6554 char const* const wrong_type =
6555 is_type_incomplete(type) ? "incomplete" :
6556 type->kind == TYPE_FUNCTION ? "function designator" :
6557 type->kind == TYPE_BITFIELD ? "bitfield" :
6559 if (wrong_type != NULL) {
6560 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6561 what, wrong_type, type);
6564 rem_anchor_token(')');
6567 expression_t *expression = parse_sub_expression(precedence);
6569 type_t* const orig_type = revert_automatic_type_conversion(expression);
6570 expression->base.type = orig_type;
6572 type_t const* const type = skip_typeref(orig_type);
6573 char const* const wrong_type =
6574 is_type_incomplete(type) ? "incomplete" :
6575 type->kind == TYPE_FUNCTION ? "function designator" :
6576 type->kind == TYPE_BITFIELD ? "bitfield" :
6578 if (wrong_type != NULL) {
6579 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6582 tp_expression->typeprop.type = expression->base.type;
6583 tp_expression->typeprop.tp_expression = expression;
6586 return tp_expression;
6588 return create_invalid_expression();
6591 static expression_t *parse_sizeof(unsigned precedence)
6593 source_position_t pos = *HERE;
6595 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6598 static expression_t *parse_alignof(unsigned precedence)
6600 source_position_t pos = *HERE;
6602 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6605 static expression_t *parse_select_expression(unsigned precedence,
6606 expression_t *compound)
6609 assert(token.type == '.' || token.type == T_MINUSGREATER);
6611 bool is_pointer = (token.type == T_MINUSGREATER);
6614 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6615 select->select.compound = compound;
6617 if (token.type != T_IDENTIFIER) {
6618 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6621 symbol_t *symbol = token.v.symbol;
6622 select->select.symbol = symbol;
6625 type_t *const orig_type = compound->base.type;
6626 type_t *const type = skip_typeref(orig_type);
6628 type_t *type_left = type;
6630 if (!is_type_pointer(type)) {
6631 if (is_type_valid(type)) {
6632 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6634 return create_invalid_expression();
6636 type_left = type->pointer.points_to;
6638 type_left = skip_typeref(type_left);
6640 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6641 type_left->kind != TYPE_COMPOUND_UNION) {
6642 if (is_type_valid(type_left)) {
6643 errorf(HERE, "request for member '%Y' in something not a struct or "
6644 "union, but '%T'", symbol, type_left);
6646 return create_invalid_expression();
6649 declaration_t *const declaration = type_left->compound.declaration;
6651 if (!declaration->init.complete) {
6652 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6654 return create_invalid_expression();
6657 declaration_t *iter = find_compound_entry(declaration, symbol);
6659 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6660 return create_invalid_expression();
6663 /* we always do the auto-type conversions; the & and sizeof parser contains
6664 * code to revert this! */
6665 type_t *expression_type = automatic_type_conversion(iter->type);
6667 select->select.compound_entry = iter;
6668 select->base.type = expression_type;
6670 type_t *skipped = skip_typeref(iter->type);
6671 if (skipped->kind == TYPE_BITFIELD) {
6672 select->base.type = skipped->bitfield.base_type;
6678 static void check_call_argument(const function_parameter_t *parameter,
6679 call_argument_t *argument)
6681 type_t *expected_type = parameter->type;
6682 type_t *expected_type_skip = skip_typeref(expected_type);
6683 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6684 expression_t *arg_expr = argument->expression;
6686 /* handle transparent union gnu extension */
6687 if (is_type_union(expected_type_skip)
6688 && (expected_type_skip->base.modifiers
6689 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6690 declaration_t *union_decl = expected_type_skip->compound.declaration;
6692 declaration_t *declaration = union_decl->scope.declarations;
6693 type_t *best_type = NULL;
6694 for ( ; declaration != NULL; declaration = declaration->next) {
6695 type_t *decl_type = declaration->type;
6696 error = semantic_assign(decl_type, arg_expr);
6697 if (error == ASSIGN_ERROR_INCOMPATIBLE
6698 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6701 if (error == ASSIGN_SUCCESS) {
6702 best_type = decl_type;
6703 } else if (best_type == NULL) {
6704 best_type = decl_type;
6708 if (best_type != NULL) {
6709 expected_type = best_type;
6713 error = semantic_assign(expected_type, arg_expr);
6714 argument->expression = create_implicit_cast(argument->expression,
6717 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6718 report_assign_error(error, expected_type, arg_expr, "function call",
6719 &arg_expr->base.source_position);
6723 * Parse a call expression, ie. expression '( ... )'.
6725 * @param expression the function address
6727 static expression_t *parse_call_expression(unsigned precedence,
6728 expression_t *expression)
6731 expression_t *result = allocate_expression_zero(EXPR_CALL);
6732 result->base.source_position = expression->base.source_position;
6734 call_expression_t *call = &result->call;
6735 call->function = expression;
6737 type_t *const orig_type = expression->base.type;
6738 type_t *const type = skip_typeref(orig_type);
6740 function_type_t *function_type = NULL;
6741 if (is_type_pointer(type)) {
6742 type_t *const to_type = skip_typeref(type->pointer.points_to);
6744 if (is_type_function(to_type)) {
6745 function_type = &to_type->function;
6746 call->base.type = function_type->return_type;
6750 if (function_type == NULL && is_type_valid(type)) {
6751 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6754 /* parse arguments */
6756 add_anchor_token(')');
6757 add_anchor_token(',');
6759 if (token.type != ')') {
6760 call_argument_t *last_argument = NULL;
6763 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6765 argument->expression = parse_assignment_expression();
6766 if (last_argument == NULL) {
6767 call->arguments = argument;
6769 last_argument->next = argument;
6771 last_argument = argument;
6773 if (token.type != ',')
6778 rem_anchor_token(',');
6779 rem_anchor_token(')');
6782 if (function_type == NULL)
6785 function_parameter_t *parameter = function_type->parameters;
6786 call_argument_t *argument = call->arguments;
6787 if (!function_type->unspecified_parameters) {
6788 for( ; parameter != NULL && argument != NULL;
6789 parameter = parameter->next, argument = argument->next) {
6790 check_call_argument(parameter, argument);
6793 if (parameter != NULL) {
6794 errorf(HERE, "too few arguments to function '%E'", expression);
6795 } else if (argument != NULL && !function_type->variadic) {
6796 errorf(HERE, "too many arguments to function '%E'", expression);
6800 /* do default promotion */
6801 for( ; argument != NULL; argument = argument->next) {
6802 type_t *type = argument->expression->base.type;
6804 type = get_default_promoted_type(type);
6806 argument->expression
6807 = create_implicit_cast(argument->expression, type);
6810 check_format(&result->call);
6814 return create_invalid_expression();
6817 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6819 static bool same_compound_type(const type_t *type1, const type_t *type2)
6822 is_type_compound(type1) &&
6823 type1->kind == type2->kind &&
6824 type1->compound.declaration == type2->compound.declaration;
6828 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6830 * @param expression the conditional expression
6832 static expression_t *parse_conditional_expression(unsigned precedence,
6833 expression_t *expression)
6835 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6837 conditional_expression_t *conditional = &result->conditional;
6838 conditional->base.source_position = *HERE;
6839 conditional->condition = expression;
6842 add_anchor_token(':');
6845 type_t *const condition_type_orig = expression->base.type;
6846 type_t *const condition_type = skip_typeref(condition_type_orig);
6847 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6848 type_error("expected a scalar type in conditional condition",
6849 &expression->base.source_position, condition_type_orig);
6852 expression_t *true_expression = parse_expression();
6853 rem_anchor_token(':');
6855 expression_t *false_expression = parse_sub_expression(precedence);
6857 type_t *const orig_true_type = true_expression->base.type;
6858 type_t *const orig_false_type = false_expression->base.type;
6859 type_t *const true_type = skip_typeref(orig_true_type);
6860 type_t *const false_type = skip_typeref(orig_false_type);
6863 type_t *result_type;
6864 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6865 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6866 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6867 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6868 warningf(&conditional->base.source_position,
6869 "ISO C forbids conditional expression with only one void side");
6871 result_type = type_void;
6872 } else if (is_type_arithmetic(true_type)
6873 && is_type_arithmetic(false_type)) {
6874 result_type = semantic_arithmetic(true_type, false_type);
6876 true_expression = create_implicit_cast(true_expression, result_type);
6877 false_expression = create_implicit_cast(false_expression, result_type);
6879 conditional->true_expression = true_expression;
6880 conditional->false_expression = false_expression;
6881 conditional->base.type = result_type;
6882 } else if (same_compound_type(true_type, false_type)) {
6883 /* just take 1 of the 2 types */
6884 result_type = true_type;
6885 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6886 type_t *pointer_type;
6888 expression_t *other_expression;
6889 if (is_type_pointer(true_type) &&
6890 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6891 pointer_type = true_type;
6892 other_type = false_type;
6893 other_expression = false_expression;
6895 pointer_type = false_type;
6896 other_type = true_type;
6897 other_expression = true_expression;
6900 if (is_null_pointer_constant(other_expression)) {
6901 result_type = pointer_type;
6902 } else if (is_type_pointer(other_type)) {
6903 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6904 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6907 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6908 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6910 } else if (types_compatible(get_unqualified_type(to1),
6911 get_unqualified_type(to2))) {
6914 warningf(&conditional->base.source_position,
6915 "pointer types '%T' and '%T' in conditional expression are incompatible",
6916 true_type, false_type);
6920 type_t *const copy = duplicate_type(to);
6921 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6923 type_t *const type = typehash_insert(copy);
6927 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6928 } else if (is_type_integer(other_type)) {
6929 warningf(&conditional->base.source_position,
6930 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6931 result_type = pointer_type;
6933 type_error_incompatible("while parsing conditional",
6934 &expression->base.source_position, true_type, false_type);
6935 result_type = type_error_type;
6938 /* TODO: one pointer to void*, other some pointer */
6940 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6941 type_error_incompatible("while parsing conditional",
6942 &conditional->base.source_position, true_type,
6945 result_type = type_error_type;
6948 conditional->true_expression
6949 = create_implicit_cast(true_expression, result_type);
6950 conditional->false_expression
6951 = create_implicit_cast(false_expression, result_type);
6952 conditional->base.type = result_type;
6955 return create_invalid_expression();
6959 * Parse an extension expression.
6961 static expression_t *parse_extension(unsigned precedence)
6963 eat(T___extension__);
6965 /* TODO enable extensions */
6966 expression_t *expression = parse_sub_expression(precedence);
6967 /* TODO disable extensions */
6972 * Parse a __builtin_classify_type() expression.
6974 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6976 eat(T___builtin_classify_type);
6978 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6979 result->base.type = type_int;
6982 add_anchor_token(')');
6983 expression_t *expression = parse_sub_expression(precedence);
6984 rem_anchor_token(')');
6986 result->classify_type.type_expression = expression;
6990 return create_invalid_expression();
6993 static bool check_pointer_arithmetic(const source_position_t *source_position,
6994 type_t *pointer_type,
6995 type_t *orig_pointer_type)
6997 type_t *points_to = pointer_type->pointer.points_to;
6998 points_to = skip_typeref(points_to);
7000 if (is_type_incomplete(points_to) &&
7002 && is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
7003 errorf(source_position,
7004 "arithmetic with pointer to incomplete type '%T' not allowed",
7007 } else if (!(c_mode & _GNUC) && is_type_function(points_to)) {
7008 errorf(source_position,
7009 "arithmetic with pointer to function type '%T' not allowed",
7013 if (warning.pointer_arith) {
7014 if (is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7015 warningf(source_position,
7016 "pointer of type '%T' used in arithmetic",
7018 } else if (is_type_function(points_to)) {
7019 warningf(source_position,
7020 "pointer to a function '%T' used in arithmetic",
7027 static void semantic_incdec(unary_expression_t *expression)
7029 type_t *const orig_type = expression->value->base.type;
7030 type_t *const type = skip_typeref(orig_type);
7031 if (is_type_pointer(type)) {
7032 if (!check_pointer_arithmetic(&expression->base.source_position,
7036 } else if (!is_type_real(type) && is_type_valid(type)) {
7037 /* TODO: improve error message */
7038 errorf(&expression->base.source_position,
7039 "operation needs an arithmetic or pointer type");
7042 expression->base.type = orig_type;
7045 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7047 type_t *const orig_type = expression->value->base.type;
7048 type_t *const type = skip_typeref(orig_type);
7049 if (!is_type_arithmetic(type)) {
7050 if (is_type_valid(type)) {
7051 /* TODO: improve error message */
7052 errorf(&expression->base.source_position,
7053 "operation needs an arithmetic type");
7058 expression->base.type = orig_type;
7061 static void semantic_not(unary_expression_t *expression)
7063 type_t *const orig_type = expression->value->base.type;
7064 type_t *const type = skip_typeref(orig_type);
7065 if (!is_type_scalar(type) && is_type_valid(type)) {
7066 errorf(&expression->base.source_position,
7067 "operand of ! must be of scalar type");
7070 expression->base.type = type_int;
7073 static void semantic_unexpr_integer(unary_expression_t *expression)
7075 type_t *const orig_type = expression->value->base.type;
7076 type_t *const type = skip_typeref(orig_type);
7077 if (!is_type_integer(type)) {
7078 if (is_type_valid(type)) {
7079 errorf(&expression->base.source_position,
7080 "operand of ~ must be of integer type");
7085 expression->base.type = orig_type;
7088 static void semantic_dereference(unary_expression_t *expression)
7090 type_t *const orig_type = expression->value->base.type;
7091 type_t *const type = skip_typeref(orig_type);
7092 if (!is_type_pointer(type)) {
7093 if (is_type_valid(type)) {
7094 errorf(&expression->base.source_position,
7095 "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
7100 type_t *result_type = type->pointer.points_to;
7101 result_type = automatic_type_conversion(result_type);
7102 expression->base.type = result_type;
7105 static void set_address_taken(expression_t *expression, bool may_be_register)
7107 if (expression->kind != EXPR_REFERENCE)
7110 declaration_t *const declaration = expression->reference.declaration;
7111 /* happens for parse errors */
7112 if (declaration == NULL)
7115 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7116 errorf(&expression->base.source_position,
7117 "address of register variable '%Y' requested",
7118 declaration->symbol);
7120 declaration->address_taken = 1;
7125 * Check the semantic of the address taken expression.
7127 static void semantic_take_addr(unary_expression_t *expression)
7129 expression_t *value = expression->value;
7130 value->base.type = revert_automatic_type_conversion(value);
7132 type_t *orig_type = value->base.type;
7133 if (!is_type_valid(orig_type))
7136 set_address_taken(value, false);
7138 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7141 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7142 static expression_t *parse_##unexpression_type(unsigned precedence) \
7144 expression_t *unary_expression \
7145 = allocate_expression_zero(unexpression_type); \
7146 unary_expression->base.source_position = *HERE; \
7148 unary_expression->unary.value = parse_sub_expression(precedence); \
7150 sfunc(&unary_expression->unary); \
7152 return unary_expression; \
7155 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7156 semantic_unexpr_arithmetic)
7157 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7158 semantic_unexpr_arithmetic)
7159 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7161 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7162 semantic_dereference)
7163 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7165 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7166 semantic_unexpr_integer)
7167 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7169 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7172 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7174 static expression_t *parse_##unexpression_type(unsigned precedence, \
7175 expression_t *left) \
7177 (void) precedence; \
7179 expression_t *unary_expression \
7180 = allocate_expression_zero(unexpression_type); \
7181 unary_expression->base.source_position = *HERE; \
7183 unary_expression->unary.value = left; \
7185 sfunc(&unary_expression->unary); \
7187 return unary_expression; \
7190 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7191 EXPR_UNARY_POSTFIX_INCREMENT,
7193 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7194 EXPR_UNARY_POSTFIX_DECREMENT,
7197 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7199 /* TODO: handle complex + imaginary types */
7201 /* § 6.3.1.8 Usual arithmetic conversions */
7202 if (type_left == type_long_double || type_right == type_long_double) {
7203 return type_long_double;
7204 } else if (type_left == type_double || type_right == type_double) {
7206 } else if (type_left == type_float || type_right == type_float) {
7210 type_left = promote_integer(type_left);
7211 type_right = promote_integer(type_right);
7213 if (type_left == type_right)
7216 bool const signed_left = is_type_signed(type_left);
7217 bool const signed_right = is_type_signed(type_right);
7218 atomic_type_kind_t const rank_left = get_rank(type_left);
7219 atomic_type_kind_t const rank_right = get_rank(type_right);
7221 if (signed_left == signed_right)
7222 return rank_left >= rank_right ? type_left : type_right;
7224 atomic_type_kind_t s_rank;
7225 atomic_type_kind_t u_rank;
7231 u_rank = rank_right;
7232 u_type = type_right;
7234 s_rank = rank_right;
7235 s_type = type_right;
7240 if (u_rank >= s_rank)
7243 if (get_atomic_type_size(s_rank) > get_atomic_type_size(u_rank))
7247 case ATOMIC_TYPE_INT: return type_int;
7248 case ATOMIC_TYPE_LONG: return type_long;
7249 case ATOMIC_TYPE_LONGLONG: return type_long_long;
7251 default: panic("invalid atomic type");
7256 * Check the semantic restrictions for a binary expression.
7258 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7260 expression_t *const left = expression->left;
7261 expression_t *const right = expression->right;
7262 type_t *const orig_type_left = left->base.type;
7263 type_t *const orig_type_right = right->base.type;
7264 type_t *const type_left = skip_typeref(orig_type_left);
7265 type_t *const type_right = skip_typeref(orig_type_right);
7267 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7268 /* TODO: improve error message */
7269 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7270 errorf(&expression->base.source_position,
7271 "operation needs arithmetic types");
7276 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7277 expression->left = create_implicit_cast(left, arithmetic_type);
7278 expression->right = create_implicit_cast(right, arithmetic_type);
7279 expression->base.type = arithmetic_type;
7282 static void semantic_shift_op(binary_expression_t *expression)
7284 expression_t *const left = expression->left;
7285 expression_t *const right = expression->right;
7286 type_t *const orig_type_left = left->base.type;
7287 type_t *const orig_type_right = right->base.type;
7288 type_t * type_left = skip_typeref(orig_type_left);
7289 type_t * type_right = skip_typeref(orig_type_right);
7291 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7292 /* TODO: improve error message */
7293 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7294 errorf(&expression->base.source_position,
7295 "operands of shift operation must have integer types");
7300 type_left = promote_integer(type_left);
7301 type_right = promote_integer(type_right);
7303 expression->left = create_implicit_cast(left, type_left);
7304 expression->right = create_implicit_cast(right, type_right);
7305 expression->base.type = type_left;
7308 static void semantic_add(binary_expression_t *expression)
7310 expression_t *const left = expression->left;
7311 expression_t *const right = expression->right;
7312 type_t *const orig_type_left = left->base.type;
7313 type_t *const orig_type_right = right->base.type;
7314 type_t *const type_left = skip_typeref(orig_type_left);
7315 type_t *const type_right = skip_typeref(orig_type_right);
7318 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7319 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7320 expression->left = create_implicit_cast(left, arithmetic_type);
7321 expression->right = create_implicit_cast(right, arithmetic_type);
7322 expression->base.type = arithmetic_type;
7324 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7325 check_pointer_arithmetic(&expression->base.source_position,
7326 type_left, orig_type_left);
7327 expression->base.type = type_left;
7328 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7329 check_pointer_arithmetic(&expression->base.source_position,
7330 type_right, orig_type_right);
7331 expression->base.type = type_right;
7332 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7333 errorf(&expression->base.source_position,
7334 "invalid operands to binary + ('%T', '%T')",
7335 orig_type_left, orig_type_right);
7339 static void semantic_sub(binary_expression_t *expression)
7341 expression_t *const left = expression->left;
7342 expression_t *const right = expression->right;
7343 type_t *const orig_type_left = left->base.type;
7344 type_t *const orig_type_right = right->base.type;
7345 type_t *const type_left = skip_typeref(orig_type_left);
7346 type_t *const type_right = skip_typeref(orig_type_right);
7347 source_position_t const *const pos = &expression->base.source_position;
7350 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7351 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7352 expression->left = create_implicit_cast(left, arithmetic_type);
7353 expression->right = create_implicit_cast(right, arithmetic_type);
7354 expression->base.type = arithmetic_type;
7356 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7357 check_pointer_arithmetic(&expression->base.source_position,
7358 type_left, orig_type_left);
7359 expression->base.type = type_left;
7360 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7361 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7362 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7363 if (!types_compatible(unqual_left, unqual_right)) {
7365 "subtracting pointers to incompatible types '%T' and '%T'",
7366 orig_type_left, orig_type_right);
7367 } else if (!is_type_object(unqual_left)) {
7368 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7369 warningf(pos, "subtracting pointers to void");
7371 errorf(pos, "subtracting pointers to non-object types '%T'",
7375 expression->base.type = type_ptrdiff_t;
7376 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7377 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7378 orig_type_left, orig_type_right);
7383 * Check the semantics of comparison expressions.
7385 * @param expression The expression to check.
7387 static void semantic_comparison(binary_expression_t *expression)
7389 expression_t *left = expression->left;
7390 expression_t *right = expression->right;
7391 type_t *orig_type_left = left->base.type;
7392 type_t *orig_type_right = right->base.type;
7394 type_t *type_left = skip_typeref(orig_type_left);
7395 type_t *type_right = skip_typeref(orig_type_right);
7397 /* TODO non-arithmetic types */
7398 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7399 /* test for signed vs unsigned compares */
7400 if (warning.sign_compare &&
7401 (expression->base.kind != EXPR_BINARY_EQUAL &&
7402 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7403 (is_type_signed(type_left) != is_type_signed(type_right))) {
7405 /* check if 1 of the operands is a constant, in this case we just
7406 * check wether we can safely represent the resulting constant in
7407 * the type of the other operand. */
7408 expression_t *const_expr = NULL;
7409 expression_t *other_expr = NULL;
7411 if (is_constant_expression(left)) {
7414 } else if (is_constant_expression(right)) {
7419 if (const_expr != NULL) {
7420 type_t *other_type = skip_typeref(other_expr->base.type);
7421 long val = fold_constant(const_expr);
7422 /* TODO: check if val can be represented by other_type */
7426 warningf(&expression->base.source_position,
7427 "comparison between signed and unsigned");
7429 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7430 expression->left = create_implicit_cast(left, arithmetic_type);
7431 expression->right = create_implicit_cast(right, arithmetic_type);
7432 expression->base.type = arithmetic_type;
7433 if (warning.float_equal &&
7434 (expression->base.kind == EXPR_BINARY_EQUAL ||
7435 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7436 is_type_float(arithmetic_type)) {
7437 warningf(&expression->base.source_position,
7438 "comparing floating point with == or != is unsafe");
7440 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7441 /* TODO check compatibility */
7442 } else if (is_type_pointer(type_left)) {
7443 expression->right = create_implicit_cast(right, type_left);
7444 } else if (is_type_pointer(type_right)) {
7445 expression->left = create_implicit_cast(left, type_right);
7446 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7447 type_error_incompatible("invalid operands in comparison",
7448 &expression->base.source_position,
7449 type_left, type_right);
7451 expression->base.type = type_int;
7455 * Checks if a compound type has constant fields.
7457 static bool has_const_fields(const compound_type_t *type)
7459 const scope_t *scope = &type->declaration->scope;
7460 const declaration_t *declaration = scope->declarations;
7462 for (; declaration != NULL; declaration = declaration->next) {
7463 if (declaration->namespc != NAMESPACE_NORMAL)
7466 const type_t *decl_type = skip_typeref(declaration->type);
7467 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7474 static bool is_lvalue(const expression_t *expression)
7476 switch (expression->kind) {
7477 case EXPR_REFERENCE:
7478 case EXPR_ARRAY_ACCESS:
7480 case EXPR_UNARY_DEREFERENCE:
7488 static bool is_valid_assignment_lhs(expression_t const* const left)
7490 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7491 type_t *const type_left = skip_typeref(orig_type_left);
7493 if (!is_lvalue(left)) {
7494 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7499 if (is_type_array(type_left)) {
7500 errorf(HERE, "cannot assign to arrays ('%E')", left);
7503 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7504 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7508 if (is_type_incomplete(type_left)) {
7509 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7510 left, orig_type_left);
7513 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7514 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7515 left, orig_type_left);
7522 static void semantic_arithmetic_assign(binary_expression_t *expression)
7524 expression_t *left = expression->left;
7525 expression_t *right = expression->right;
7526 type_t *orig_type_left = left->base.type;
7527 type_t *orig_type_right = right->base.type;
7529 if (!is_valid_assignment_lhs(left))
7532 type_t *type_left = skip_typeref(orig_type_left);
7533 type_t *type_right = skip_typeref(orig_type_right);
7535 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7536 /* TODO: improve error message */
7537 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7538 errorf(&expression->base.source_position,
7539 "operation needs arithmetic types");
7544 /* combined instructions are tricky. We can't create an implicit cast on
7545 * the left side, because we need the uncasted form for the store.
7546 * The ast2firm pass has to know that left_type must be right_type
7547 * for the arithmetic operation and create a cast by itself */
7548 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7549 expression->right = create_implicit_cast(right, arithmetic_type);
7550 expression->base.type = type_left;
7553 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7555 expression_t *const left = expression->left;
7556 expression_t *const right = expression->right;
7557 type_t *const orig_type_left = left->base.type;
7558 type_t *const orig_type_right = right->base.type;
7559 type_t *const type_left = skip_typeref(orig_type_left);
7560 type_t *const type_right = skip_typeref(orig_type_right);
7562 if (!is_valid_assignment_lhs(left))
7565 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7566 /* combined instructions are tricky. We can't create an implicit cast on
7567 * the left side, because we need the uncasted form for the store.
7568 * The ast2firm pass has to know that left_type must be right_type
7569 * for the arithmetic operation and create a cast by itself */
7570 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7571 expression->right = create_implicit_cast(right, arithmetic_type);
7572 expression->base.type = type_left;
7573 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7574 check_pointer_arithmetic(&expression->base.source_position,
7575 type_left, orig_type_left);
7576 expression->base.type = type_left;
7577 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7578 errorf(&expression->base.source_position,
7579 "incompatible types '%T' and '%T' in assignment",
7580 orig_type_left, orig_type_right);
7585 * Check the semantic restrictions of a logical expression.
7587 static void semantic_logical_op(binary_expression_t *expression)
7589 expression_t *const left = expression->left;
7590 expression_t *const right = expression->right;
7591 type_t *const orig_type_left = left->base.type;
7592 type_t *const orig_type_right = right->base.type;
7593 type_t *const type_left = skip_typeref(orig_type_left);
7594 type_t *const type_right = skip_typeref(orig_type_right);
7596 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7597 /* TODO: improve error message */
7598 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7599 errorf(&expression->base.source_position,
7600 "operation needs scalar types");
7605 expression->base.type = type_int;
7609 * Check the semantic restrictions of a binary assign expression.
7611 static void semantic_binexpr_assign(binary_expression_t *expression)
7613 expression_t *left = expression->left;
7614 type_t *orig_type_left = left->base.type;
7616 type_t *type_left = revert_automatic_type_conversion(left);
7617 type_left = skip_typeref(orig_type_left);
7619 if (!is_valid_assignment_lhs(left))
7622 assign_error_t error = semantic_assign(orig_type_left, expression->right);
7623 report_assign_error(error, orig_type_left, expression->right,
7624 "assignment", &left->base.source_position);
7625 expression->right = create_implicit_cast(expression->right, orig_type_left);
7626 expression->base.type = orig_type_left;
7630 * Determine if the outermost operation (or parts thereof) of the given
7631 * expression has no effect in order to generate a warning about this fact.
7632 * Therefore in some cases this only examines some of the operands of the
7633 * expression (see comments in the function and examples below).
7635 * f() + 23; // warning, because + has no effect
7636 * x || f(); // no warning, because x controls execution of f()
7637 * x ? y : f(); // warning, because y has no effect
7638 * (void)x; // no warning to be able to suppress the warning
7639 * This function can NOT be used for an "expression has definitely no effect"-
7641 static bool expression_has_effect(const expression_t *const expr)
7643 switch (expr->kind) {
7644 case EXPR_UNKNOWN: break;
7645 case EXPR_INVALID: return true; /* do NOT warn */
7646 case EXPR_REFERENCE: return false;
7647 /* suppress the warning for microsoft __noop operations */
7648 case EXPR_CONST: return expr->conste.is_ms_noop;
7649 case EXPR_CHARACTER_CONSTANT: return false;
7650 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
7651 case EXPR_STRING_LITERAL: return false;
7652 case EXPR_WIDE_STRING_LITERAL: return false;
7655 const call_expression_t *const call = &expr->call;
7656 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7659 switch (call->function->builtin_symbol.symbol->ID) {
7660 case T___builtin_va_end: return true;
7661 default: return false;
7665 /* Generate the warning if either the left or right hand side of a
7666 * conditional expression has no effect */
7667 case EXPR_CONDITIONAL: {
7668 const conditional_expression_t *const cond = &expr->conditional;
7670 expression_has_effect(cond->true_expression) &&
7671 expression_has_effect(cond->false_expression);
7674 case EXPR_SELECT: return false;
7675 case EXPR_ARRAY_ACCESS: return false;
7676 case EXPR_SIZEOF: return false;
7677 case EXPR_CLASSIFY_TYPE: return false;
7678 case EXPR_ALIGNOF: return false;
7680 case EXPR_FUNCNAME: return false;
7681 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7682 case EXPR_BUILTIN_CONSTANT_P: return false;
7683 case EXPR_BUILTIN_PREFETCH: return true;
7684 case EXPR_OFFSETOF: return false;
7685 case EXPR_VA_START: return true;
7686 case EXPR_VA_ARG: return true;
7687 case EXPR_STATEMENT: return true; // TODO
7688 case EXPR_COMPOUND_LITERAL: return false;
7690 case EXPR_UNARY_NEGATE: return false;
7691 case EXPR_UNARY_PLUS: return false;
7692 case EXPR_UNARY_BITWISE_NEGATE: return false;
7693 case EXPR_UNARY_NOT: return false;
7694 case EXPR_UNARY_DEREFERENCE: return false;
7695 case EXPR_UNARY_TAKE_ADDRESS: return false;
7696 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7697 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7698 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7699 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7701 /* Treat void casts as if they have an effect in order to being able to
7702 * suppress the warning */
7703 case EXPR_UNARY_CAST: {
7704 type_t *const type = skip_typeref(expr->base.type);
7705 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7708 case EXPR_UNARY_CAST_IMPLICIT: return true;
7709 case EXPR_UNARY_ASSUME: return true;
7711 case EXPR_BINARY_ADD: return false;
7712 case EXPR_BINARY_SUB: return false;
7713 case EXPR_BINARY_MUL: return false;
7714 case EXPR_BINARY_DIV: return false;
7715 case EXPR_BINARY_MOD: return false;
7716 case EXPR_BINARY_EQUAL: return false;
7717 case EXPR_BINARY_NOTEQUAL: return false;
7718 case EXPR_BINARY_LESS: return false;
7719 case EXPR_BINARY_LESSEQUAL: return false;
7720 case EXPR_BINARY_GREATER: return false;
7721 case EXPR_BINARY_GREATEREQUAL: return false;
7722 case EXPR_BINARY_BITWISE_AND: return false;
7723 case EXPR_BINARY_BITWISE_OR: return false;
7724 case EXPR_BINARY_BITWISE_XOR: return false;
7725 case EXPR_BINARY_SHIFTLEFT: return false;
7726 case EXPR_BINARY_SHIFTRIGHT: return false;
7727 case EXPR_BINARY_ASSIGN: return true;
7728 case EXPR_BINARY_MUL_ASSIGN: return true;
7729 case EXPR_BINARY_DIV_ASSIGN: return true;
7730 case EXPR_BINARY_MOD_ASSIGN: return true;
7731 case EXPR_BINARY_ADD_ASSIGN: return true;
7732 case EXPR_BINARY_SUB_ASSIGN: return true;
7733 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7734 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7735 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7736 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7737 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7739 /* Only examine the right hand side of && and ||, because the left hand
7740 * side already has the effect of controlling the execution of the right
7742 case EXPR_BINARY_LOGICAL_AND:
7743 case EXPR_BINARY_LOGICAL_OR:
7744 /* Only examine the right hand side of a comma expression, because the left
7745 * hand side has a separate warning */
7746 case EXPR_BINARY_COMMA:
7747 return expression_has_effect(expr->binary.right);
7749 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7750 case EXPR_BINARY_ISGREATER: return false;
7751 case EXPR_BINARY_ISGREATEREQUAL: return false;
7752 case EXPR_BINARY_ISLESS: return false;
7753 case EXPR_BINARY_ISLESSEQUAL: return false;
7754 case EXPR_BINARY_ISLESSGREATER: return false;
7755 case EXPR_BINARY_ISUNORDERED: return false;
7758 internal_errorf(HERE, "unexpected expression");
7761 static void semantic_comma(binary_expression_t *expression)
7763 if (warning.unused_value) {
7764 const expression_t *const left = expression->left;
7765 if (!expression_has_effect(left)) {
7766 warningf(&left->base.source_position,
7767 "left-hand operand of comma expression has no effect");
7770 expression->base.type = expression->right->base.type;
7773 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7774 static expression_t *parse_##binexpression_type(unsigned precedence, \
7775 expression_t *left) \
7777 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7778 binexpr->base.source_position = *HERE; \
7779 binexpr->binary.left = left; \
7782 expression_t *right = parse_sub_expression(precedence + lr); \
7784 binexpr->binary.right = right; \
7785 sfunc(&binexpr->binary); \
7790 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7791 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7792 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7793 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7794 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7795 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7796 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7797 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7798 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7800 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7801 semantic_comparison, 1)
7802 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7803 semantic_comparison, 1)
7804 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7805 semantic_comparison, 1)
7806 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7807 semantic_comparison, 1)
7809 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7810 semantic_binexpr_arithmetic, 1)
7811 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7812 semantic_binexpr_arithmetic, 1)
7813 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7814 semantic_binexpr_arithmetic, 1)
7815 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7816 semantic_logical_op, 1)
7817 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7818 semantic_logical_op, 1)
7819 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7820 semantic_shift_op, 1)
7821 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7822 semantic_shift_op, 1)
7823 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7824 semantic_arithmetic_addsubb_assign, 0)
7825 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7826 semantic_arithmetic_addsubb_assign, 0)
7827 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7828 semantic_arithmetic_assign, 0)
7829 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7830 semantic_arithmetic_assign, 0)
7831 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7832 semantic_arithmetic_assign, 0)
7833 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7834 semantic_arithmetic_assign, 0)
7835 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7836 semantic_arithmetic_assign, 0)
7837 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7838 semantic_arithmetic_assign, 0)
7839 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7840 semantic_arithmetic_assign, 0)
7841 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7842 semantic_arithmetic_assign, 0)
7844 static expression_t *parse_sub_expression(unsigned precedence)
7846 if (token.type < 0) {
7847 return expected_expression_error();
7850 expression_parser_function_t *parser
7851 = &expression_parsers[token.type];
7852 source_position_t source_position = token.source_position;
7855 if (parser->parser != NULL) {
7856 left = parser->parser(parser->precedence);
7858 left = parse_primary_expression();
7860 assert(left != NULL);
7861 left->base.source_position = source_position;
7864 if (token.type < 0) {
7865 return expected_expression_error();
7868 parser = &expression_parsers[token.type];
7869 if (parser->infix_parser == NULL)
7871 if (parser->infix_precedence < precedence)
7874 left = parser->infix_parser(parser->infix_precedence, left);
7876 assert(left != NULL);
7877 assert(left->kind != EXPR_UNKNOWN);
7878 left->base.source_position = source_position;
7885 * Parse an expression.
7887 static expression_t *parse_expression(void)
7889 return parse_sub_expression(1);
7893 * Register a parser for a prefix-like operator with given precedence.
7895 * @param parser the parser function
7896 * @param token_type the token type of the prefix token
7897 * @param precedence the precedence of the operator
7899 static void register_expression_parser(parse_expression_function parser,
7900 int token_type, unsigned precedence)
7902 expression_parser_function_t *entry = &expression_parsers[token_type];
7904 if (entry->parser != NULL) {
7905 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7906 panic("trying to register multiple expression parsers for a token");
7908 entry->parser = parser;
7909 entry->precedence = precedence;
7913 * Register a parser for an infix operator with given precedence.
7915 * @param parser the parser function
7916 * @param token_type the token type of the infix operator
7917 * @param precedence the precedence of the operator
7919 static void register_infix_parser(parse_expression_infix_function parser,
7920 int token_type, unsigned precedence)
7922 expression_parser_function_t *entry = &expression_parsers[token_type];
7924 if (entry->infix_parser != NULL) {
7925 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7926 panic("trying to register multiple infix expression parsers for a "
7929 entry->infix_parser = parser;
7930 entry->infix_precedence = precedence;
7934 * Initialize the expression parsers.
7936 static void init_expression_parsers(void)
7938 memset(&expression_parsers, 0, sizeof(expression_parsers));
7940 register_infix_parser(parse_array_expression, '[', 30);
7941 register_infix_parser(parse_call_expression, '(', 30);
7942 register_infix_parser(parse_select_expression, '.', 30);
7943 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7944 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7946 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7949 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7950 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7951 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7952 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7953 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7954 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7955 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7956 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7957 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7958 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7959 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7960 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7961 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7962 T_EXCLAMATIONMARKEQUAL, 13);
7963 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7964 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7965 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7966 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7967 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7968 register_infix_parser(parse_conditional_expression, '?', 7);
7969 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7970 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7971 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7972 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7973 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7974 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7975 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7976 T_LESSLESSEQUAL, 2);
7977 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7978 T_GREATERGREATEREQUAL, 2);
7979 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7981 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7983 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7986 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7988 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7989 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7990 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7991 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7992 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7993 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7994 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7996 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7998 register_expression_parser(parse_sizeof, T_sizeof, 25);
7999 register_expression_parser(parse_alignof, T___alignof__, 25);
8000 register_expression_parser(parse_extension, T___extension__, 25);
8001 register_expression_parser(parse_builtin_classify_type,
8002 T___builtin_classify_type, 25);
8006 * Parse a asm statement arguments specification.
8008 static asm_argument_t *parse_asm_arguments(bool is_out)
8010 asm_argument_t *result = NULL;
8011 asm_argument_t *last = NULL;
8013 while (token.type == T_STRING_LITERAL || token.type == '[') {
8014 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8015 memset(argument, 0, sizeof(argument[0]));
8017 if (token.type == '[') {
8019 if (token.type != T_IDENTIFIER) {
8020 parse_error_expected("while parsing asm argument",
8021 T_IDENTIFIER, NULL);
8024 argument->symbol = token.v.symbol;
8029 argument->constraints = parse_string_literals();
8031 add_anchor_token(')');
8032 expression_t *expression = parse_expression();
8033 rem_anchor_token(')');
8035 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8036 * change size or type representation (e.g. int -> long is ok, but
8037 * int -> float is not) */
8038 if (expression->kind == EXPR_UNARY_CAST) {
8039 type_t *const type = expression->base.type;
8040 type_kind_t const kind = type->kind;
8041 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8044 if (kind == TYPE_ATOMIC) {
8045 atomic_type_kind_t const akind = type->atomic.akind;
8046 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8047 size = get_atomic_type_size(akind);
8049 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8050 size = get_atomic_type_size(get_intptr_kind());
8054 expression_t *const value = expression->unary.value;
8055 type_t *const value_type = value->base.type;
8056 type_kind_t const value_kind = value_type->kind;
8058 unsigned value_flags;
8059 unsigned value_size;
8060 if (value_kind == TYPE_ATOMIC) {
8061 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8062 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8063 value_size = get_atomic_type_size(value_akind);
8064 } else if (value_kind == TYPE_POINTER) {
8065 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8066 value_size = get_atomic_type_size(get_intptr_kind());
8071 if (value_flags != flags || value_size != size)
8075 } while (expression->kind == EXPR_UNARY_CAST);
8079 if (!is_lvalue(expression)) {
8080 errorf(&expression->base.source_position,
8081 "asm output argument is not an lvalue");
8084 argument->expression = expression;
8087 set_address_taken(expression, true);
8090 last->next = argument;
8096 if (token.type != ',')
8107 * Parse a asm statement clobber specification.
8109 static asm_clobber_t *parse_asm_clobbers(void)
8111 asm_clobber_t *result = NULL;
8112 asm_clobber_t *last = NULL;
8114 while(token.type == T_STRING_LITERAL) {
8115 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8116 clobber->clobber = parse_string_literals();
8119 last->next = clobber;
8125 if (token.type != ',')
8134 * Parse an asm statement.
8136 static statement_t *parse_asm_statement(void)
8140 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8141 statement->base.source_position = token.source_position;
8143 asm_statement_t *asm_statement = &statement->asms;
8145 if (token.type == T_volatile) {
8147 asm_statement->is_volatile = true;
8151 add_anchor_token(')');
8152 add_anchor_token(':');
8153 asm_statement->asm_text = parse_string_literals();
8155 if (token.type != ':') {
8156 rem_anchor_token(':');
8161 asm_statement->outputs = parse_asm_arguments(true);
8162 if (token.type != ':') {
8163 rem_anchor_token(':');
8168 asm_statement->inputs = parse_asm_arguments(false);
8169 if (token.type != ':') {
8170 rem_anchor_token(':');
8173 rem_anchor_token(':');
8176 asm_statement->clobbers = parse_asm_clobbers();
8179 rem_anchor_token(')');
8183 if (asm_statement->outputs == NULL) {
8184 /* GCC: An 'asm' instruction without any output operands will be treated
8185 * identically to a volatile 'asm' instruction. */
8186 asm_statement->is_volatile = true;
8191 return create_invalid_statement();
8195 * Parse a case statement.
8197 static statement_t *parse_case_statement(void)
8201 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8202 source_position_t *const pos = &statement->base.source_position;
8204 *pos = token.source_position;
8205 statement->case_label.expression = parse_expression();
8206 if (! is_constant_expression(statement->case_label.expression)) {
8207 errorf(pos, "case label does not reduce to an integer constant");
8208 statement->case_label.is_bad = true;
8210 long const val = fold_constant(statement->case_label.expression);
8211 statement->case_label.first_case = val;
8212 statement->case_label.last_case = val;
8215 if (c_mode & _GNUC) {
8216 if (token.type == T_DOTDOTDOT) {
8218 statement->case_label.end_range = parse_expression();
8219 if (! is_constant_expression(statement->case_label.end_range)) {
8220 errorf(pos, "case range does not reduce to an integer constant");
8221 statement->case_label.is_bad = true;
8223 long const val = fold_constant(statement->case_label.end_range);
8224 statement->case_label.last_case = val;
8226 if (val < statement->case_label.first_case) {
8227 statement->case_label.is_empty = true;
8228 warningf(pos, "empty range specified");
8234 PUSH_PARENT(statement);
8238 if (current_switch != NULL) {
8239 if (! statement->case_label.is_bad) {
8240 /* Check for duplicate case values */
8241 case_label_statement_t *c = &statement->case_label;
8242 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8243 if (l->is_bad || l->is_empty)
8246 if (c->last_case < l->first_case || c->first_case > l->last_case)
8249 errorf(pos, "duplicate case value (previously used %P)",
8250 &l->base.source_position);
8254 /* link all cases into the switch statement */
8255 if (current_switch->last_case == NULL) {
8256 current_switch->first_case = &statement->case_label;
8258 current_switch->last_case->next = &statement->case_label;
8260 current_switch->last_case = &statement->case_label;
8262 errorf(pos, "case label not within a switch statement");
8265 statement_t *const inner_stmt = parse_statement();
8266 statement->case_label.statement = inner_stmt;
8267 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8268 errorf(&inner_stmt->base.source_position, "declaration after case label");
8275 return create_invalid_statement();
8279 * Parse a default statement.
8281 static statement_t *parse_default_statement(void)
8285 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8286 statement->base.source_position = token.source_position;
8288 PUSH_PARENT(statement);
8291 if (current_switch != NULL) {
8292 const case_label_statement_t *def_label = current_switch->default_label;
8293 if (def_label != NULL) {
8294 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8295 &def_label->base.source_position);
8297 current_switch->default_label = &statement->case_label;
8299 /* link all cases into the switch statement */
8300 if (current_switch->last_case == NULL) {
8301 current_switch->first_case = &statement->case_label;
8303 current_switch->last_case->next = &statement->case_label;
8305 current_switch->last_case = &statement->case_label;
8308 errorf(&statement->base.source_position,
8309 "'default' label not within a switch statement");
8312 statement_t *const inner_stmt = parse_statement();
8313 statement->case_label.statement = inner_stmt;
8314 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8315 errorf(&inner_stmt->base.source_position, "declaration after default label");
8322 return create_invalid_statement();
8326 * Return the declaration for a given label symbol or create a new one.
8328 * @param symbol the symbol of the label
8330 static declaration_t *get_label(symbol_t *symbol)
8332 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
8333 assert(current_function != NULL);
8334 /* if we found a label in the same function, then we already created the
8336 if (candidate != NULL
8337 && candidate->parent_scope == ¤t_function->scope) {
8341 /* otherwise we need to create a new one */
8342 declaration_t *const declaration = allocate_declaration_zero();
8343 declaration->namespc = NAMESPACE_LABEL;
8344 declaration->symbol = symbol;
8346 label_push(declaration);
8352 * Parse a label statement.
8354 static statement_t *parse_label_statement(void)
8356 assert(token.type == T_IDENTIFIER);
8357 symbol_t *symbol = token.v.symbol;
8360 declaration_t *label = get_label(symbol);
8362 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8363 statement->base.source_position = token.source_position;
8364 statement->label.label = label;
8366 PUSH_PARENT(statement);
8368 /* if source position is already set then the label is defined twice,
8369 * otherwise it was just mentioned in a goto so far */
8370 if (label->source_position.input_name != NULL) {
8371 errorf(HERE, "duplicate label '%Y' (declared %P)",
8372 symbol, &label->source_position);
8374 label->source_position = token.source_position;
8375 label->init.statement = statement;
8380 if (token.type == '}') {
8381 /* TODO only warn? */
8383 warningf(HERE, "label at end of compound statement");
8384 statement->label.statement = create_empty_statement();
8386 errorf(HERE, "label at end of compound statement");
8387 statement->label.statement = create_invalid_statement();
8389 } else if (token.type == ';') {
8390 /* Eat an empty statement here, to avoid the warning about an empty
8391 * statement after a label. label:; is commonly used to have a label
8392 * before a closing brace. */
8393 statement->label.statement = create_empty_statement();
8396 statement_t *const inner_stmt = parse_statement();
8397 statement->label.statement = inner_stmt;
8398 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8399 errorf(&inner_stmt->base.source_position, "declaration after label");
8403 /* remember the labels in a list for later checking */
8404 if (label_last == NULL) {
8405 label_first = &statement->label;
8407 label_last->next = &statement->label;
8409 label_last = &statement->label;
8416 * Parse an if statement.
8418 static statement_t *parse_if(void)
8422 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8423 statement->base.source_position = token.source_position;
8425 PUSH_PARENT(statement);
8428 add_anchor_token(')');
8429 statement->ifs.condition = parse_expression();
8430 rem_anchor_token(')');
8433 add_anchor_token(T_else);
8434 statement->ifs.true_statement = parse_statement();
8435 rem_anchor_token(T_else);
8437 if (token.type == T_else) {
8439 statement->ifs.false_statement = parse_statement();
8446 return create_invalid_statement();
8450 * Check that all enums are handled in a switch.
8452 * @param statement the switch statement to check
8454 static void check_enum_cases(const switch_statement_t *statement) {
8455 const type_t *type = skip_typeref(statement->expression->base.type);
8456 if (! is_type_enum(type))
8458 const enum_type_t *enumt = &type->enumt;
8460 /* if we have a default, no warnings */
8461 if (statement->default_label != NULL)
8464 /* FIXME: calculation of value should be done while parsing */
8465 const declaration_t *declaration;
8466 long last_value = -1;
8467 for (declaration = enumt->declaration->next;
8468 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8469 declaration = declaration->next) {
8470 const expression_t *expression = declaration->init.enum_value;
8471 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8473 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8474 if (l->expression == NULL)
8476 if (l->first_case <= value && value <= l->last_case) {
8482 warningf(&statement->base.source_position,
8483 "enumeration value '%Y' not handled in switch", declaration->symbol);
8490 * Parse a switch statement.
8492 static statement_t *parse_switch(void)
8496 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8497 statement->base.source_position = token.source_position;
8499 PUSH_PARENT(statement);
8502 add_anchor_token(')');
8503 expression_t *const expr = parse_expression();
8504 type_t * type = skip_typeref(expr->base.type);
8505 if (is_type_integer(type)) {
8506 type = promote_integer(type);
8507 } else if (is_type_valid(type)) {
8508 errorf(&expr->base.source_position,
8509 "switch quantity is not an integer, but '%T'", type);
8510 type = type_error_type;
8512 statement->switchs.expression = create_implicit_cast(expr, type);
8514 rem_anchor_token(')');
8516 switch_statement_t *rem = current_switch;
8517 current_switch = &statement->switchs;
8518 statement->switchs.body = parse_statement();
8519 current_switch = rem;
8521 if (warning.switch_default &&
8522 statement->switchs.default_label == NULL) {
8523 warningf(&statement->base.source_position, "switch has no default case");
8525 if (warning.switch_enum)
8526 check_enum_cases(&statement->switchs);
8532 return create_invalid_statement();
8535 static statement_t *parse_loop_body(statement_t *const loop)
8537 statement_t *const rem = current_loop;
8538 current_loop = loop;
8540 statement_t *const body = parse_statement();
8547 * Parse a while statement.
8549 static statement_t *parse_while(void)
8553 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8554 statement->base.source_position = token.source_position;
8556 PUSH_PARENT(statement);
8559 add_anchor_token(')');
8560 statement->whiles.condition = parse_expression();
8561 rem_anchor_token(')');
8564 statement->whiles.body = parse_loop_body(statement);
8570 return create_invalid_statement();
8574 * Parse a do statement.
8576 static statement_t *parse_do(void)
8580 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8581 statement->base.source_position = token.source_position;
8583 PUSH_PARENT(statement)
8585 add_anchor_token(T_while);
8586 statement->do_while.body = parse_loop_body(statement);
8587 rem_anchor_token(T_while);
8591 add_anchor_token(')');
8592 statement->do_while.condition = parse_expression();
8593 rem_anchor_token(')');
8601 return create_invalid_statement();
8605 * Parse a for statement.
8607 static statement_t *parse_for(void)
8611 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
8612 statement->base.source_position = token.source_position;
8614 PUSH_PARENT(statement);
8616 int top = environment_top();
8617 scope_t *last_scope = scope;
8618 set_scope(&statement->fors.scope);
8621 add_anchor_token(')');
8623 if (token.type != ';') {
8624 if (is_declaration_specifier(&token, false)) {
8625 parse_declaration(record_declaration);
8627 add_anchor_token(';');
8628 expression_t *const init = parse_expression();
8629 statement->fors.initialisation = init;
8630 if (warning.unused_value && !expression_has_effect(init)) {
8631 warningf(&init->base.source_position,
8632 "initialisation of 'for'-statement has no effect");
8634 rem_anchor_token(';');
8641 if (token.type != ';') {
8642 add_anchor_token(';');
8643 statement->fors.condition = parse_expression();
8644 rem_anchor_token(';');
8647 if (token.type != ')') {
8648 expression_t *const step = parse_expression();
8649 statement->fors.step = step;
8650 if (warning.unused_value && !expression_has_effect(step)) {
8651 warningf(&step->base.source_position,
8652 "step of 'for'-statement has no effect");
8655 rem_anchor_token(')');
8657 statement->fors.body = parse_loop_body(statement);
8659 assert(scope == &statement->fors.scope);
8660 set_scope(last_scope);
8661 environment_pop_to(top);
8668 rem_anchor_token(')');
8669 assert(scope == &statement->fors.scope);
8670 set_scope(last_scope);
8671 environment_pop_to(top);
8673 return create_invalid_statement();
8677 * Parse a goto statement.
8679 static statement_t *parse_goto(void)
8683 if (token.type != T_IDENTIFIER) {
8684 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8688 symbol_t *symbol = token.v.symbol;
8691 declaration_t *label = get_label(symbol);
8693 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
8694 statement->base.source_position = token.source_position;
8696 statement->gotos.label = label;
8698 /* remember the goto's in a list for later checking */
8699 if (goto_last == NULL) {
8700 goto_first = &statement->gotos;
8702 goto_last->next = &statement->gotos;
8704 goto_last = &statement->gotos;
8710 return create_invalid_statement();
8714 * Parse a continue statement.
8716 static statement_t *parse_continue(void)
8718 statement_t *statement;
8719 if (current_loop == NULL) {
8720 errorf(HERE, "continue statement not within loop");
8721 statement = create_invalid_statement();
8723 statement = allocate_statement_zero(STATEMENT_CONTINUE);
8725 statement->base.source_position = token.source_position;
8733 return create_invalid_statement();
8737 * Parse a break statement.
8739 static statement_t *parse_break(void)
8741 statement_t *statement;
8742 if (current_switch == NULL && current_loop == NULL) {
8743 errorf(HERE, "break statement not within loop or switch");
8744 statement = create_invalid_statement();
8746 statement = allocate_statement_zero(STATEMENT_BREAK);
8748 statement->base.source_position = token.source_position;
8756 return create_invalid_statement();
8760 * Parse a __leave statement.
8762 static statement_t *parse_leave(void)
8764 statement_t *statement;
8765 if (current_try == NULL) {
8766 errorf(HERE, "__leave statement not within __try");
8767 statement = create_invalid_statement();
8769 statement = allocate_statement_zero(STATEMENT_LEAVE);
8771 statement->base.source_position = token.source_position;
8779 return create_invalid_statement();
8783 * Check if a given declaration represents a local variable.
8785 static bool is_local_var_declaration(const declaration_t *declaration)
8787 switch ((storage_class_tag_t) declaration->storage_class) {
8788 case STORAGE_CLASS_AUTO:
8789 case STORAGE_CLASS_REGISTER: {
8790 const type_t *type = skip_typeref(declaration->type);
8791 if (is_type_function(type)) {
8803 * Check if a given declaration represents a variable.
8805 static bool is_var_declaration(const declaration_t *declaration)
8807 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
8810 const type_t *type = skip_typeref(declaration->type);
8811 return !is_type_function(type);
8815 * Check if a given expression represents a local variable.
8817 static bool is_local_variable(const expression_t *expression)
8819 if (expression->base.kind != EXPR_REFERENCE) {
8822 const declaration_t *declaration = expression->reference.declaration;
8823 return is_local_var_declaration(declaration);
8827 * Check if a given expression represents a local variable and
8828 * return its declaration then, else return NULL.
8830 declaration_t *expr_is_variable(const expression_t *expression)
8832 if (expression->base.kind != EXPR_REFERENCE) {
8835 declaration_t *declaration = expression->reference.declaration;
8836 if (is_var_declaration(declaration))
8842 * Parse a return statement.
8844 static statement_t *parse_return(void)
8846 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
8847 statement->base.source_position = token.source_position;
8851 expression_t *return_value = NULL;
8852 if (token.type != ';') {
8853 return_value = parse_expression();
8857 const type_t *const func_type = current_function->type;
8858 assert(is_type_function(func_type));
8859 type_t *const return_type = skip_typeref(func_type->function.return_type);
8861 if (return_value != NULL) {
8862 type_t *return_value_type = skip_typeref(return_value->base.type);
8864 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8865 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8866 warningf(&statement->base.source_position,
8867 "'return' with a value, in function returning void");
8868 return_value = NULL;
8870 assign_error_t error = semantic_assign(return_type, return_value);
8871 report_assign_error(error, return_type, return_value, "'return'",
8872 &statement->base.source_position);
8873 return_value = create_implicit_cast(return_value, return_type);
8875 /* check for returning address of a local var */
8876 if (return_value != NULL &&
8877 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8878 const expression_t *expression = return_value->unary.value;
8879 if (is_local_variable(expression)) {
8880 warningf(&statement->base.source_position,
8881 "function returns address of local variable");
8885 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8886 warningf(&statement->base.source_position,
8887 "'return' without value, in function returning non-void");
8890 statement->returns.value = return_value;
8894 return create_invalid_statement();
8898 * Parse a declaration statement.
8900 static statement_t *parse_declaration_statement(void)
8902 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8904 statement->base.source_position = token.source_position;
8906 declaration_t *before = last_declaration;
8907 parse_declaration(record_declaration);
8909 if (before == NULL) {
8910 statement->declaration.declarations_begin = scope->declarations;
8912 statement->declaration.declarations_begin = before->next;
8914 statement->declaration.declarations_end = last_declaration;
8920 * Parse an expression statement, ie. expr ';'.
8922 static statement_t *parse_expression_statement(void)
8924 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8926 statement->base.source_position = token.source_position;
8927 expression_t *const expr = parse_expression();
8928 statement->expression.expression = expr;
8934 return create_invalid_statement();
8938 * Parse a microsoft __try { } __finally { } or
8939 * __try{ } __except() { }
8941 static statement_t *parse_ms_try_statment(void)
8943 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8945 statement->base.source_position = token.source_position;
8948 ms_try_statement_t *rem = current_try;
8949 current_try = &statement->ms_try;
8950 statement->ms_try.try_statement = parse_compound_statement(false);
8953 if (token.type == T___except) {
8956 add_anchor_token(')');
8957 expression_t *const expr = parse_expression();
8958 type_t * type = skip_typeref(expr->base.type);
8959 if (is_type_integer(type)) {
8960 type = promote_integer(type);
8961 } else if (is_type_valid(type)) {
8962 errorf(&expr->base.source_position,
8963 "__expect expression is not an integer, but '%T'", type);
8964 type = type_error_type;
8966 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8967 rem_anchor_token(')');
8969 statement->ms_try.final_statement = parse_compound_statement(false);
8970 } else if (token.type == T__finally) {
8972 statement->ms_try.final_statement = parse_compound_statement(false);
8974 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8975 return create_invalid_statement();
8979 return create_invalid_statement();
8982 static statement_t *parse_empty_statement(void)
8984 if (warning.empty_statement) {
8985 warningf(HERE, "statement is empty");
8988 return create_empty_statement();
8992 * Parse a statement.
8993 * There's also parse_statement() which additionally checks for
8994 * "statement has no effect" warnings
8996 static statement_t *intern_parse_statement(void)
8998 statement_t *statement = NULL;
9000 /* declaration or statement */
9001 add_anchor_token(';');
9002 switch (token.type) {
9004 if (look_ahead(1)->type == ':') {
9005 statement = parse_label_statement();
9006 } else if (is_typedef_symbol(token.v.symbol)) {
9007 statement = parse_declaration_statement();
9009 statement = parse_expression_statement();
9013 case T___extension__:
9014 /* This can be a prefix to a declaration or an expression statement.
9015 * We simply eat it now and parse the rest with tail recursion. */
9018 } while (token.type == T___extension__);
9019 statement = parse_statement();
9023 statement = parse_declaration_statement();
9026 case ';': statement = parse_empty_statement(); break;
9027 case '{': statement = parse_compound_statement(false); break;
9028 case T___leave: statement = parse_leave(); break;
9029 case T___try: statement = parse_ms_try_statment(); break;
9030 case T_asm: statement = parse_asm_statement(); break;
9031 case T_break: statement = parse_break(); break;
9032 case T_case: statement = parse_case_statement(); break;
9033 case T_continue: statement = parse_continue(); break;
9034 case T_default: statement = parse_default_statement(); break;
9035 case T_do: statement = parse_do(); break;
9036 case T_for: statement = parse_for(); break;
9037 case T_goto: statement = parse_goto(); break;
9038 case T_if: statement = parse_if (); break;
9039 case T_return: statement = parse_return(); break;
9040 case T_switch: statement = parse_switch(); break;
9041 case T_while: statement = parse_while(); break;
9042 default: statement = parse_expression_statement(); break;
9044 rem_anchor_token(';');
9046 assert(statement != NULL
9047 && statement->base.source_position.input_name != NULL);
9053 * parse a statement and emits "statement has no effect" warning if needed
9054 * (This is really a wrapper around intern_parse_statement with check for 1
9055 * single warning. It is needed, because for statement expressions we have
9056 * to avoid the warning on the last statement)
9058 static statement_t *parse_statement(void)
9060 statement_t *statement = intern_parse_statement();
9062 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9063 expression_t *expression = statement->expression.expression;
9064 if (!expression_has_effect(expression)) {
9065 warningf(&expression->base.source_position,
9066 "statement has no effect");
9074 * Parse a compound statement.
9076 static statement_t *parse_compound_statement(bool inside_expression_statement)
9078 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9079 statement->base.source_position = token.source_position;
9081 PUSH_PARENT(statement);
9084 add_anchor_token('}');
9086 int top = environment_top();
9087 scope_t *last_scope = scope;
9088 set_scope(&statement->compound.scope);
9090 statement_t *last_statement = NULL;
9092 bool only_decls_so_far = true;
9093 while (token.type != '}' && token.type != T_EOF) {
9094 statement_t *sub_statement = intern_parse_statement();
9095 if (is_invalid_statement(sub_statement)) {
9096 /* an error occurred. if we are at an anchor, return */
9102 if (warning.declaration_after_statement) {
9103 if (sub_statement->kind != STATEMENT_DECLARATION) {
9104 only_decls_so_far = false;
9105 } else if (!only_decls_so_far) {
9106 warningf(&sub_statement->base.source_position,
9107 "ISO C90 forbids mixed declarations and code");
9111 if (last_statement != NULL) {
9112 last_statement->base.next = sub_statement;
9114 statement->compound.statements = sub_statement;
9117 while (sub_statement->base.next != NULL)
9118 sub_statement = sub_statement->base.next;
9120 last_statement = sub_statement;
9123 if (token.type == '}') {
9126 errorf(&statement->base.source_position,
9127 "end of file while looking for closing '}'");
9130 /* look over all statements again to produce no effect warnings */
9131 if (warning.unused_value) {
9132 statement_t *sub_statement = statement->compound.statements;
9133 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9134 if (sub_statement->kind != STATEMENT_EXPRESSION)
9136 /* don't emit a warning for the last expression in an expression
9137 * statement as it has always an effect */
9138 if (inside_expression_statement && sub_statement->base.next == NULL)
9141 expression_t *expression = sub_statement->expression.expression;
9142 if (!expression_has_effect(expression)) {
9143 warningf(&expression->base.source_position,
9144 "statement has no effect");
9150 rem_anchor_token('}');
9151 assert(scope == &statement->compound.scope);
9152 set_scope(last_scope);
9153 environment_pop_to(top);
9160 * Initialize builtin types.
9162 static void initialize_builtin_types(void)
9164 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9165 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9166 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9167 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9168 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9169 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9170 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
9171 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9173 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9174 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9175 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9176 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9178 /* const version of wchar_t */
9179 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9180 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9181 type_const_wchar_t->base.modifiers |= TYPE_QUALIFIER_CONST;
9183 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9187 * Check for unused global static functions and variables
9189 static void check_unused_globals(void)
9191 if (!warning.unused_function && !warning.unused_variable)
9194 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9196 decl->modifiers & DM_UNUSED ||
9197 decl->modifiers & DM_USED ||
9198 decl->storage_class != STORAGE_CLASS_STATIC)
9201 type_t *const type = decl->type;
9203 if (is_type_function(skip_typeref(type))) {
9204 if (!warning.unused_function || decl->is_inline)
9207 s = (decl->init.statement != NULL ? "defined" : "declared");
9209 if (!warning.unused_variable)
9215 warningf(&decl->source_position, "'%#T' %s but not used",
9216 type, decl->symbol, s);
9220 static void parse_global_asm(void)
9225 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9226 statement->base.source_position = token.source_position;
9227 statement->asms.asm_text = parse_string_literals();
9228 statement->base.next = unit->global_asm;
9229 unit->global_asm = statement;
9238 * Parse a translation unit.
9240 static void parse_translation_unit(void)
9242 for (;;) switch (token.type) {
9245 case T___extension__:
9246 parse_external_declaration();
9257 /* TODO error in strict mode */
9258 warningf(HERE, "stray ';' outside of function");
9263 errorf(HERE, "stray %K outside of function", &token);
9264 if (token.type == '(' || token.type == '{' || token.type == '[')
9265 eat_until_matching_token(token.type);
9274 * @return the translation unit or NULL if errors occurred.
9276 void start_parsing(void)
9278 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9279 label_stack = NEW_ARR_F(stack_entry_t, 0);
9280 diagnostic_count = 0;
9284 type_set_output(stderr);
9285 ast_set_output(stderr);
9287 assert(unit == NULL);
9288 unit = allocate_ast_zero(sizeof(unit[0]));
9290 assert(global_scope == NULL);
9291 global_scope = &unit->scope;
9293 assert(scope == NULL);
9294 set_scope(&unit->scope);
9296 initialize_builtin_types();
9299 translation_unit_t *finish_parsing(void)
9301 assert(scope == &unit->scope);
9303 last_declaration = NULL;
9305 assert(global_scope == &unit->scope);
9306 check_unused_globals();
9307 global_scope = NULL;
9309 DEL_ARR_F(environment_stack);
9310 DEL_ARR_F(label_stack);
9312 translation_unit_t *result = unit;
9319 lookahead_bufpos = 0;
9320 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9323 parse_translation_unit();
9327 * Initialize the parser.
9329 void init_parser(void)
9332 /* add predefined symbols for extended-decl-modifier */
9333 sym_align = symbol_table_insert("align");
9334 sym_allocate = symbol_table_insert("allocate");
9335 sym_dllimport = symbol_table_insert("dllimport");
9336 sym_dllexport = symbol_table_insert("dllexport");
9337 sym_naked = symbol_table_insert("naked");
9338 sym_noinline = symbol_table_insert("noinline");
9339 sym_noreturn = symbol_table_insert("noreturn");
9340 sym_nothrow = symbol_table_insert("nothrow");
9341 sym_novtable = symbol_table_insert("novtable");
9342 sym_property = symbol_table_insert("property");
9343 sym_get = symbol_table_insert("get");
9344 sym_put = symbol_table_insert("put");
9345 sym_selectany = symbol_table_insert("selectany");
9346 sym_thread = symbol_table_insert("thread");
9347 sym_uuid = symbol_table_insert("uuid");
9348 sym_deprecated = symbol_table_insert("deprecated");
9349 sym_restrict = symbol_table_insert("restrict");
9350 sym_noalias = symbol_table_insert("noalias");
9352 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9354 init_expression_parsers();
9355 obstack_init(&temp_obst);
9357 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9358 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9362 * Terminate the parser.
9364 void exit_parser(void)
9366 obstack_free(&temp_obst, NULL);