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 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
108 static token_t token;
109 static token_t lookahead_buffer[MAX_LOOKAHEAD];
110 static int lookahead_bufpos;
111 static stack_entry_t *environment_stack = NULL;
112 static stack_entry_t *label_stack = NULL;
113 static scope_t *global_scope = NULL;
114 static scope_t *scope = NULL;
115 static declaration_t *last_declaration = NULL;
116 static declaration_t *current_function = NULL;
117 static declaration_t *current_init_decl = NULL;
118 static switch_statement_t *current_switch = NULL;
119 static statement_t *current_loop = NULL;
120 static statement_t *current_parent = NULL;
121 static ms_try_statement_t *current_try = NULL;
122 static goto_statement_t *goto_first = NULL;
123 static goto_statement_t *goto_last = NULL;
124 static label_statement_t *label_first = NULL;
125 static label_statement_t *label_last = NULL;
126 static translation_unit_t *unit = NULL;
127 static struct obstack temp_obst;
129 #define PUSH_PARENT(stmt) \
130 statement_t *const prev_parent = current_parent; \
131 current_parent = (stmt);
132 #define POP_PARENT ((void)(current_parent = prev_parent))
134 static source_position_t null_position = { NULL, 0 };
136 /* symbols for Microsoft extended-decl-modifier */
137 static const symbol_t *sym_align = NULL;
138 static const symbol_t *sym_allocate = NULL;
139 static const symbol_t *sym_dllimport = NULL;
140 static const symbol_t *sym_dllexport = NULL;
141 static const symbol_t *sym_naked = NULL;
142 static const symbol_t *sym_noinline = NULL;
143 static const symbol_t *sym_noreturn = NULL;
144 static const symbol_t *sym_nothrow = NULL;
145 static const symbol_t *sym_novtable = NULL;
146 static const symbol_t *sym_property = NULL;
147 static const symbol_t *sym_get = NULL;
148 static const symbol_t *sym_put = NULL;
149 static const symbol_t *sym_selectany = NULL;
150 static const symbol_t *sym_thread = NULL;
151 static const symbol_t *sym_uuid = NULL;
152 static const symbol_t *sym_deprecated = NULL;
153 static const symbol_t *sym_restrict = NULL;
154 static const symbol_t *sym_noalias = NULL;
156 /** The token anchor set */
157 static unsigned char token_anchor_set[T_LAST_TOKEN];
159 /** The current source position. */
160 #define HERE (&token.source_position)
162 static type_t *type_valist;
164 static statement_t *parse_compound_statement(bool inside_expression_statement);
165 static statement_t *parse_statement(void);
167 static expression_t *parse_sub_expression(unsigned precedence);
168 static expression_t *parse_expression(void);
169 static type_t *parse_typename(void);
171 static void parse_compound_type_entries(declaration_t *compound_declaration);
172 static declaration_t *parse_declarator(
173 const declaration_specifiers_t *specifiers, bool may_be_abstract);
174 static declaration_t *record_declaration(declaration_t *declaration);
176 static void semantic_comparison(binary_expression_t *expression);
178 #define STORAGE_CLASSES \
186 #define TYPE_QUALIFIERS \
191 case T__forceinline: \
192 case T___attribute__:
194 #ifdef PROVIDE_COMPLEX
195 #define COMPLEX_SPECIFIERS \
197 #define IMAGINARY_SPECIFIERS \
200 #define COMPLEX_SPECIFIERS
201 #define IMAGINARY_SPECIFIERS
204 #define TYPE_SPECIFIERS \
219 case T___builtin_va_list: \
224 #define DECLARATION_START \
229 #define TYPENAME_START \
234 * Allocate an AST node with given size and
235 * initialize all fields with zero.
237 static void *allocate_ast_zero(size_t size)
239 void *res = allocate_ast(size);
240 memset(res, 0, size);
244 static declaration_t *allocate_declaration_zero(void)
246 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
247 declaration->type = type_error_type;
248 declaration->alignment = 0;
253 * Returns the size of a statement node.
255 * @param kind the statement kind
257 static size_t get_statement_struct_size(statement_kind_t kind)
259 static const size_t sizes[] = {
260 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
261 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
262 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
263 [STATEMENT_RETURN] = sizeof(return_statement_t),
264 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
265 [STATEMENT_IF] = sizeof(if_statement_t),
266 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
267 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
268 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
269 [STATEMENT_BREAK] = sizeof(statement_base_t),
270 [STATEMENT_GOTO] = sizeof(goto_statement_t),
271 [STATEMENT_LABEL] = sizeof(label_statement_t),
272 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
273 [STATEMENT_WHILE] = sizeof(while_statement_t),
274 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
275 [STATEMENT_FOR] = sizeof(for_statement_t),
276 [STATEMENT_ASM] = sizeof(asm_statement_t),
277 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
278 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
280 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
281 assert(sizes[kind] != 0);
286 * Returns the size of an expression node.
288 * @param kind the expression kind
290 static size_t get_expression_struct_size(expression_kind_t kind)
292 static const size_t sizes[] = {
293 [EXPR_INVALID] = sizeof(expression_base_t),
294 [EXPR_REFERENCE] = sizeof(reference_expression_t),
295 [EXPR_CONST] = sizeof(const_expression_t),
296 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
297 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
298 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
299 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
300 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
301 [EXPR_CALL] = sizeof(call_expression_t),
302 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
303 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
304 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
305 [EXPR_SELECT] = sizeof(select_expression_t),
306 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
307 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
308 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
309 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
310 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
311 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
312 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
313 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
314 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
315 [EXPR_VA_START] = sizeof(va_start_expression_t),
316 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
317 [EXPR_STATEMENT] = sizeof(statement_expression_t),
319 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
320 return sizes[EXPR_UNARY_FIRST];
322 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
323 return sizes[EXPR_BINARY_FIRST];
325 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
326 assert(sizes[kind] != 0);
331 * Allocate a statement node of given kind and initialize all
334 static statement_t *allocate_statement_zero(statement_kind_t kind)
336 size_t size = get_statement_struct_size(kind);
337 statement_t *res = allocate_ast_zero(size);
339 res->base.kind = kind;
340 res->base.parent = current_parent;
345 * Allocate an expression node of given kind and initialize all
348 static expression_t *allocate_expression_zero(expression_kind_t kind)
350 size_t size = get_expression_struct_size(kind);
351 expression_t *res = allocate_ast_zero(size);
353 res->base.kind = kind;
354 res->base.type = type_error_type;
359 * Creates a new invalid expression.
361 static expression_t *create_invalid_expression(void)
363 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
364 expression->base.source_position = token.source_position;
369 * Creates a new invalid statement.
371 static statement_t *create_invalid_statement(void)
373 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
374 statement->base.source_position = token.source_position;
379 * Allocate a new empty statement.
381 static statement_t *create_empty_statement(void)
383 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
384 statement->base.source_position = token.source_position;
389 * Returns the size of a type node.
391 * @param kind the type kind
393 static size_t get_type_struct_size(type_kind_t kind)
395 static const size_t sizes[] = {
396 [TYPE_ATOMIC] = sizeof(atomic_type_t),
397 [TYPE_COMPLEX] = sizeof(complex_type_t),
398 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
399 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
400 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
401 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
402 [TYPE_ENUM] = sizeof(enum_type_t),
403 [TYPE_FUNCTION] = sizeof(function_type_t),
404 [TYPE_POINTER] = sizeof(pointer_type_t),
405 [TYPE_ARRAY] = sizeof(array_type_t),
406 [TYPE_BUILTIN] = sizeof(builtin_type_t),
407 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
408 [TYPE_TYPEOF] = sizeof(typeof_type_t),
410 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
411 assert(kind <= TYPE_TYPEOF);
412 assert(sizes[kind] != 0);
417 * Allocate a type node of given kind and initialize all
420 * @param kind type kind to allocate
421 * @param source_position the source position of the type definition
423 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
425 size_t size = get_type_struct_size(kind);
426 type_t *res = obstack_alloc(type_obst, size);
427 memset(res, 0, size);
429 res->base.kind = kind;
430 res->base.source_position = *source_position;
435 * Returns the size of an initializer node.
437 * @param kind the initializer kind
439 static size_t get_initializer_size(initializer_kind_t kind)
441 static const size_t sizes[] = {
442 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
443 [INITIALIZER_STRING] = sizeof(initializer_string_t),
444 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
445 [INITIALIZER_LIST] = sizeof(initializer_list_t),
446 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
448 assert(kind < sizeof(sizes) / sizeof(*sizes));
449 assert(sizes[kind] != 0);
454 * Allocate an initializer node of given kind and initialize all
457 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
459 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
466 * Free a type from the type obstack.
468 static void free_type(void *type)
470 obstack_free(type_obst, type);
474 * Returns the index of the top element of the environment stack.
476 static size_t environment_top(void)
478 return ARR_LEN(environment_stack);
482 * Returns the index of the top element of the label stack.
484 static size_t label_top(void)
486 return ARR_LEN(label_stack);
490 * Return the next token.
492 static inline void next_token(void)
494 token = lookahead_buffer[lookahead_bufpos];
495 lookahead_buffer[lookahead_bufpos] = lexer_token;
498 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
501 print_token(stderr, &token);
502 fprintf(stderr, "\n");
507 * Return the next token with a given lookahead.
509 static inline const token_t *look_ahead(int num)
511 assert(num > 0 && num <= MAX_LOOKAHEAD);
512 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
513 return &lookahead_buffer[pos];
517 * Adds a token to the token anchor set (a multi-set).
519 static void add_anchor_token(int token_type)
521 assert(0 <= token_type && token_type < T_LAST_TOKEN);
522 ++token_anchor_set[token_type];
525 static int save_and_reset_anchor_state(int token_type)
527 assert(0 <= token_type && token_type < T_LAST_TOKEN);
528 int count = token_anchor_set[token_type];
529 token_anchor_set[token_type] = 0;
533 static void restore_anchor_state(int token_type, int count)
535 assert(0 <= token_type && token_type < T_LAST_TOKEN);
536 token_anchor_set[token_type] = count;
540 * Remove a token from the token anchor set (a multi-set).
542 static void rem_anchor_token(int token_type)
544 assert(0 <= token_type && token_type < T_LAST_TOKEN);
545 --token_anchor_set[token_type];
548 static bool at_anchor(void)
552 return token_anchor_set[token.type];
556 * Eat tokens until a matching token is found.
558 static void eat_until_matching_token(int type)
562 case '(': end_token = ')'; break;
563 case '{': end_token = '}'; break;
564 case '[': end_token = ']'; break;
565 default: end_token = type; break;
568 unsigned parenthesis_count = 0;
569 unsigned brace_count = 0;
570 unsigned bracket_count = 0;
571 while (token.type != end_token ||
572 parenthesis_count != 0 ||
574 bracket_count != 0) {
575 switch (token.type) {
577 case '(': ++parenthesis_count; break;
578 case '{': ++brace_count; break;
579 case '[': ++bracket_count; break;
582 if (parenthesis_count > 0)
592 if (bracket_count > 0)
595 if (token.type == end_token &&
596 parenthesis_count == 0 &&
610 * Eat input tokens until an anchor is found.
612 static void eat_until_anchor(void)
614 if (token.type == T_EOF)
616 while (token_anchor_set[token.type] == 0) {
617 if (token.type == '(' || token.type == '{' || token.type == '[')
618 eat_until_matching_token(token.type);
619 if (token.type == T_EOF)
625 static void eat_block(void)
627 eat_until_matching_token('{');
628 if (token.type == '}')
633 * eat all token until a ';' is reached or a stop token is found.
635 static void eat_statement(void)
637 eat_until_matching_token(';');
638 if (token.type == ';')
642 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
645 * Report a parse error because an expected token was not found.
648 #if defined __GNUC__ && __GNUC__ >= 4
649 __attribute__((sentinel))
651 void parse_error_expected(const char *message, ...)
653 if (message != NULL) {
654 errorf(HERE, "%s", message);
657 va_start(ap, message);
658 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
663 * Report a type error.
665 static void type_error(const char *msg, const source_position_t *source_position,
668 errorf(source_position, "%s, but found type '%T'", msg, type);
672 * Report an incompatible type.
674 static void type_error_incompatible(const char *msg,
675 const source_position_t *source_position, type_t *type1, type_t *type2)
677 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
682 * Expect the the current token is the expected token.
683 * If not, generate an error, eat the current statement,
684 * and goto the end_error label.
686 #define expect(expected) \
688 if (UNLIKELY(token.type != (expected))) { \
689 parse_error_expected(NULL, (expected), NULL); \
690 add_anchor_token(expected); \
691 eat_until_anchor(); \
692 if (token.type == expected) \
694 rem_anchor_token(expected); \
700 static void set_scope(scope_t *new_scope)
703 scope->last_declaration = last_declaration;
707 last_declaration = new_scope->last_declaration;
711 * Search a symbol in a given namespace and returns its declaration or
712 * NULL if this symbol was not found.
714 static declaration_t *get_declaration(const symbol_t *const symbol,
715 const namespace_t namespc)
717 declaration_t *declaration = symbol->declaration;
718 for( ; declaration != NULL; declaration = declaration->symbol_next) {
719 if (declaration->namespc == namespc)
727 * pushs an environment_entry on the environment stack and links the
728 * corresponding symbol to the new entry
730 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
732 symbol_t *symbol = declaration->symbol;
733 namespace_t namespc = (namespace_t) declaration->namespc;
735 /* replace/add declaration into declaration list of the symbol */
736 declaration_t *iter = symbol->declaration;
738 symbol->declaration = declaration;
740 declaration_t *iter_last = NULL;
741 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
742 /* replace an entry? */
743 if (iter->namespc == namespc) {
744 if (iter_last == NULL) {
745 symbol->declaration = declaration;
747 iter_last->symbol_next = declaration;
749 declaration->symbol_next = iter->symbol_next;
754 assert(iter_last->symbol_next == NULL);
755 iter_last->symbol_next = declaration;
759 /* remember old declaration */
761 entry.symbol = symbol;
762 entry.old_declaration = iter;
763 entry.namespc = (unsigned short) namespc;
764 ARR_APP1(stack_entry_t, *stack_ptr, entry);
767 static void environment_push(declaration_t *declaration)
769 assert(declaration->source_position.input_name != NULL);
770 assert(declaration->parent_scope != NULL);
771 stack_push(&environment_stack, declaration);
775 * Push a declaration of the label stack.
777 * @param declaration the declaration
779 static void label_push(declaration_t *declaration)
781 declaration->parent_scope = ¤t_function->scope;
782 stack_push(&label_stack, declaration);
786 * pops symbols from the environment stack until @p new_top is the top element
788 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
790 stack_entry_t *stack = *stack_ptr;
791 size_t top = ARR_LEN(stack);
794 assert(new_top <= top);
798 for(i = top; i > new_top; --i) {
799 stack_entry_t *entry = &stack[i - 1];
801 declaration_t *old_declaration = entry->old_declaration;
802 symbol_t *symbol = entry->symbol;
803 namespace_t namespc = (namespace_t)entry->namespc;
805 /* replace/remove declaration */
806 declaration_t *declaration = symbol->declaration;
807 assert(declaration != NULL);
808 if (declaration->namespc == namespc) {
809 if (old_declaration == NULL) {
810 symbol->declaration = declaration->symbol_next;
812 symbol->declaration = old_declaration;
815 declaration_t *iter_last = declaration;
816 declaration_t *iter = declaration->symbol_next;
817 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
818 /* replace an entry? */
819 if (iter->namespc == namespc) {
820 assert(iter_last != NULL);
821 iter_last->symbol_next = old_declaration;
822 if (old_declaration != NULL) {
823 old_declaration->symbol_next = iter->symbol_next;
828 assert(iter != NULL);
832 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
835 static void environment_pop_to(size_t new_top)
837 stack_pop_to(&environment_stack, new_top);
841 * Pop all entries on the label stack until the new_top
844 * @param new_top the new stack top
846 static void label_pop_to(size_t new_top)
848 stack_pop_to(&label_stack, new_top);
851 static int get_akind_rank(atomic_type_kind_t akind)
856 static int get_rank(const type_t *type)
858 assert(!is_typeref(type));
859 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
860 * and esp. footnote 108). However we can't fold constants (yet), so we
861 * can't decide whether unsigned int is possible, while int always works.
862 * (unsigned int would be preferable when possible... for stuff like
863 * struct { enum { ... } bla : 4; } ) */
864 if (type->kind == TYPE_ENUM)
865 return get_akind_rank(ATOMIC_TYPE_INT);
867 assert(type->kind == TYPE_ATOMIC);
868 return get_akind_rank(type->atomic.akind);
871 static type_t *promote_integer(type_t *type)
873 if (type->kind == TYPE_BITFIELD)
874 type = type->bitfield.base_type;
876 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
883 * Create a cast expression.
885 * @param expression the expression to cast
886 * @param dest_type the destination type
888 static expression_t *create_cast_expression(expression_t *expression,
891 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
893 cast->unary.value = expression;
894 cast->base.type = dest_type;
900 * Check if a given expression represents the 0 pointer constant.
902 static bool is_null_pointer_constant(const expression_t *expression)
904 /* skip void* cast */
905 if (expression->kind == EXPR_UNARY_CAST
906 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
907 expression = expression->unary.value;
910 /* TODO: not correct yet, should be any constant integer expression
911 * which evaluates to 0 */
912 if (expression->kind != EXPR_CONST)
915 type_t *const type = skip_typeref(expression->base.type);
916 if (!is_type_integer(type))
919 return expression->conste.v.int_value == 0;
923 * Create an implicit cast expression.
925 * @param expression the expression to cast
926 * @param dest_type the destination type
928 static expression_t *create_implicit_cast(expression_t *expression,
931 type_t *const source_type = expression->base.type;
933 if (source_type == dest_type)
936 return create_cast_expression(expression, dest_type);
939 typedef enum assign_error_t {
941 ASSIGN_ERROR_INCOMPATIBLE,
942 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
943 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
944 ASSIGN_WARNING_POINTER_FROM_INT,
945 ASSIGN_WARNING_INT_FROM_POINTER
948 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
949 const expression_t *const right,
951 const source_position_t *source_position)
953 type_t *const orig_type_right = right->base.type;
954 type_t *const type_left = skip_typeref(orig_type_left);
955 type_t *const type_right = skip_typeref(orig_type_right);
960 case ASSIGN_ERROR_INCOMPATIBLE:
961 errorf(source_position,
962 "destination type '%T' in %s is incompatible with type '%T'",
963 orig_type_left, context, orig_type_right);
966 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
967 type_t *points_to_left
968 = skip_typeref(type_left->pointer.points_to);
969 type_t *points_to_right
970 = skip_typeref(type_right->pointer.points_to);
972 /* the left type has all qualifiers from the right type */
973 unsigned missing_qualifiers
974 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
975 warningf(source_position,
976 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
977 orig_type_left, context, orig_type_right, missing_qualifiers);
981 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
982 warningf(source_position,
983 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
984 orig_type_left, context, right, orig_type_right);
987 case ASSIGN_WARNING_POINTER_FROM_INT:
988 warningf(source_position,
989 "%s makes integer '%T' from pointer '%T' without a cast",
990 context, orig_type_left, orig_type_right);
993 case ASSIGN_WARNING_INT_FROM_POINTER:
994 warningf(source_position,
995 "%s makes integer '%T' from pointer '%T' without a cast",
996 context, orig_type_left, orig_type_right);
1000 panic("invalid error value");
1004 /** Implements the rules from § 6.5.16.1 */
1005 static assign_error_t semantic_assign(type_t *orig_type_left,
1006 const expression_t *const right)
1008 type_t *const orig_type_right = right->base.type;
1009 type_t *const type_left = skip_typeref(orig_type_left);
1010 type_t *const type_right = skip_typeref(orig_type_right);
1012 if (is_type_pointer(type_left)) {
1013 if (is_null_pointer_constant(right)) {
1014 return ASSIGN_SUCCESS;
1015 } else if (is_type_pointer(type_right)) {
1016 type_t *points_to_left
1017 = skip_typeref(type_left->pointer.points_to);
1018 type_t *points_to_right
1019 = skip_typeref(type_right->pointer.points_to);
1020 assign_error_t res = ASSIGN_SUCCESS;
1022 /* the left type has all qualifiers from the right type */
1023 unsigned missing_qualifiers
1024 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1025 if (missing_qualifiers != 0) {
1026 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1029 points_to_left = get_unqualified_type(points_to_left);
1030 points_to_right = get_unqualified_type(points_to_right);
1032 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1033 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1037 if (!types_compatible(points_to_left, points_to_right)) {
1038 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1042 } else if (is_type_integer(type_right)) {
1043 return ASSIGN_WARNING_POINTER_FROM_INT;
1045 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1046 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1047 && is_type_pointer(type_right))) {
1048 return ASSIGN_SUCCESS;
1049 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1050 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1051 type_t *const unqual_type_left = get_unqualified_type(type_left);
1052 type_t *const unqual_type_right = get_unqualified_type(type_right);
1053 if (types_compatible(unqual_type_left, unqual_type_right)) {
1054 return ASSIGN_SUCCESS;
1056 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1057 return ASSIGN_WARNING_INT_FROM_POINTER;
1060 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1061 return ASSIGN_SUCCESS;
1063 return ASSIGN_ERROR_INCOMPATIBLE;
1066 static expression_t *parse_constant_expression(void)
1068 /* start parsing at precedence 7 (conditional expression) */
1069 expression_t *result = parse_sub_expression(7);
1071 if (!is_constant_expression(result)) {
1072 errorf(&result->base.source_position,
1073 "expression '%E' is not constant\n", result);
1079 static expression_t *parse_assignment_expression(void)
1081 /* start parsing at precedence 2 (assignment expression) */
1082 return parse_sub_expression(2);
1085 static type_t *make_global_typedef(const char *name, type_t *type)
1087 symbol_t *const symbol = symbol_table_insert(name);
1089 declaration_t *const declaration = allocate_declaration_zero();
1090 declaration->namespc = NAMESPACE_NORMAL;
1091 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1092 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1093 declaration->type = type;
1094 declaration->symbol = symbol;
1095 declaration->source_position = builtin_source_position;
1096 declaration->implicit = true;
1098 record_declaration(declaration);
1100 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1101 typedef_type->typedeft.declaration = declaration;
1103 return typedef_type;
1106 static string_t parse_string_literals(void)
1108 assert(token.type == T_STRING_LITERAL);
1109 string_t result = token.v.string;
1113 while (token.type == T_STRING_LITERAL) {
1114 result = concat_strings(&result, &token.v.string);
1121 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1122 [GNU_AK_CONST] = "const",
1123 [GNU_AK_VOLATILE] = "volatile",
1124 [GNU_AK_CDECL] = "cdecl",
1125 [GNU_AK_STDCALL] = "stdcall",
1126 [GNU_AK_FASTCALL] = "fastcall",
1127 [GNU_AK_DEPRECATED] = "deprecated",
1128 [GNU_AK_NOINLINE] = "noinline",
1129 [GNU_AK_NORETURN] = "noreturn",
1130 [GNU_AK_NAKED] = "naked",
1131 [GNU_AK_PURE] = "pure",
1132 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1133 [GNU_AK_MALLOC] = "malloc",
1134 [GNU_AK_WEAK] = "weak",
1135 [GNU_AK_CONSTRUCTOR] = "constructor",
1136 [GNU_AK_DESTRUCTOR] = "destructor",
1137 [GNU_AK_NOTHROW] = "nothrow",
1138 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1139 [GNU_AK_COMMON] = "common",
1140 [GNU_AK_NOCOMMON] = "nocommon",
1141 [GNU_AK_PACKED] = "packed",
1142 [GNU_AK_SHARED] = "shared",
1143 [GNU_AK_NOTSHARED] = "notshared",
1144 [GNU_AK_USED] = "used",
1145 [GNU_AK_UNUSED] = "unused",
1146 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1147 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1148 [GNU_AK_LONGCALL] = "longcall",
1149 [GNU_AK_SHORTCALL] = "shortcall",
1150 [GNU_AK_LONG_CALL] = "long_call",
1151 [GNU_AK_SHORT_CALL] = "short_call",
1152 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1153 [GNU_AK_INTERRUPT] = "interrupt",
1154 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1155 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1156 [GNU_AK_NESTING] = "nesting",
1157 [GNU_AK_NEAR] = "near",
1158 [GNU_AK_FAR] = "far",
1159 [GNU_AK_SIGNAL] = "signal",
1160 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1161 [GNU_AK_TINY_DATA] = "tiny_data",
1162 [GNU_AK_SAVEALL] = "saveall",
1163 [GNU_AK_FLATTEN] = "flatten",
1164 [GNU_AK_SSEREGPARM] = "sseregparm",
1165 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1166 [GNU_AK_RETURN_TWICE] = "return_twice",
1167 [GNU_AK_MAY_ALIAS] = "may_alias",
1168 [GNU_AK_MS_STRUCT] = "ms_struct",
1169 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1170 [GNU_AK_DLLIMPORT] = "dllimport",
1171 [GNU_AK_DLLEXPORT] = "dllexport",
1172 [GNU_AK_ALIGNED] = "aligned",
1173 [GNU_AK_ALIAS] = "alias",
1174 [GNU_AK_SECTION] = "section",
1175 [GNU_AK_FORMAT] = "format",
1176 [GNU_AK_FORMAT_ARG] = "format_arg",
1177 [GNU_AK_WEAKREF] = "weakref",
1178 [GNU_AK_NONNULL] = "nonnull",
1179 [GNU_AK_TLS_MODEL] = "tls_model",
1180 [GNU_AK_VISIBILITY] = "visibility",
1181 [GNU_AK_REGPARM] = "regparm",
1182 [GNU_AK_MODE] = "mode",
1183 [GNU_AK_MODEL] = "model",
1184 [GNU_AK_TRAP_EXIT] = "trap_exit",
1185 [GNU_AK_SP_SWITCH] = "sp_switch",
1186 [GNU_AK_SENTINEL] = "sentinel"
1190 * compare two string, ignoring double underscores on the second.
1192 static int strcmp_underscore(const char *s1, const char *s2)
1194 if (s2[0] == '_' && s2[1] == '_') {
1195 size_t len2 = strlen(s2);
1196 size_t len1 = strlen(s1);
1197 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1198 return strncmp(s1, s2+2, len2-4);
1202 return strcmp(s1, s2);
1206 * Allocate a new gnu temporal attribute.
1208 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1210 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1211 attribute->kind = kind;
1212 attribute->next = NULL;
1213 attribute->invalid = false;
1214 attribute->have_arguments = false;
1220 * parse one constant expression argument.
1222 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1224 expression_t *expression;
1225 add_anchor_token(')');
1226 expression = parse_constant_expression();
1227 rem_anchor_token(')');
1229 attribute->u.argument = fold_constant(expression);
1232 attribute->invalid = true;
1236 * parse a list of constant expressions arguments.
1238 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1240 argument_list_t **list = &attribute->u.arguments;
1241 argument_list_t *entry;
1242 expression_t *expression;
1243 add_anchor_token(')');
1244 add_anchor_token(',');
1246 expression = parse_constant_expression();
1247 entry = obstack_alloc(&temp_obst, sizeof(entry));
1248 entry->argument = fold_constant(expression);
1251 list = &entry->next;
1252 if (token.type != ',')
1256 rem_anchor_token(',');
1257 rem_anchor_token(')');
1261 attribute->invalid = true;
1265 * parse one string literal argument.
1267 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1270 add_anchor_token('(');
1271 if (token.type != T_STRING_LITERAL) {
1272 parse_error_expected("while parsing attribute directive",
1273 T_STRING_LITERAL, NULL);
1276 *string = parse_string_literals();
1277 rem_anchor_token('(');
1281 attribute->invalid = true;
1285 * parse one tls model.
1287 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1289 static const char *const tls_models[] = {
1295 string_t string = { NULL, 0 };
1296 parse_gnu_attribute_string_arg(attribute, &string);
1297 if (string.begin != NULL) {
1298 for(size_t i = 0; i < 4; ++i) {
1299 if (strcmp(tls_models[i], string.begin) == 0) {
1300 attribute->u.value = i;
1304 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1306 attribute->invalid = true;
1310 * parse one tls model.
1312 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1314 static const char *const visibilities[] = {
1320 string_t string = { NULL, 0 };
1321 parse_gnu_attribute_string_arg(attribute, &string);
1322 if (string.begin != NULL) {
1323 for(size_t i = 0; i < 4; ++i) {
1324 if (strcmp(visibilities[i], string.begin) == 0) {
1325 attribute->u.value = i;
1329 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1331 attribute->invalid = true;
1335 * parse one (code) model.
1337 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1339 static const char *const visibilities[] = {
1344 string_t string = { NULL, 0 };
1345 parse_gnu_attribute_string_arg(attribute, &string);
1346 if (string.begin != NULL) {
1347 for(int i = 0; i < 3; ++i) {
1348 if (strcmp(visibilities[i], string.begin) == 0) {
1349 attribute->u.value = i;
1353 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1355 attribute->invalid = true;
1358 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1360 /* TODO: find out what is allowed here... */
1362 /* at least: byte, word, pointer, list of machine modes
1363 * __XXX___ is interpreted as XXX */
1364 add_anchor_token(')');
1366 if (token.type != T_IDENTIFIER) {
1367 expect(T_IDENTIFIER);
1370 /* This isn't really correct, the backend should provide a list of machine
1371 * specific modes (according to gcc philosophy that is...) */
1372 const char *symbol_str = token.v.symbol->string;
1373 if (strcmp_underscore("QI", symbol_str) == 0 ||
1374 strcmp_underscore("byte", symbol_str) == 0) {
1375 attribute->u.akind = ATOMIC_TYPE_CHAR;
1376 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1377 attribute->u.akind = ATOMIC_TYPE_SHORT;
1378 } else if (strcmp_underscore("SI", symbol_str) == 0
1379 || strcmp_underscore("word", symbol_str) == 0
1380 || strcmp_underscore("pointer", symbol_str) == 0) {
1381 attribute->u.akind = ATOMIC_TYPE_INT;
1382 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1383 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1385 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1386 attribute->invalid = true;
1390 rem_anchor_token(')');
1394 attribute->invalid = true;
1398 * parse one interrupt argument.
1400 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1402 static const char *const interrupts[] = {
1409 string_t string = { NULL, 0 };
1410 parse_gnu_attribute_string_arg(attribute, &string);
1411 if (string.begin != NULL) {
1412 for(size_t i = 0; i < 5; ++i) {
1413 if (strcmp(interrupts[i], string.begin) == 0) {
1414 attribute->u.value = i;
1418 errorf(HERE, "'%s' is not an interrupt", string.begin);
1420 attribute->invalid = true;
1424 * parse ( identifier, const expression, const expression )
1426 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1428 static const char *const format_names[] = {
1436 if (token.type != T_IDENTIFIER) {
1437 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1440 const char *name = token.v.symbol->string;
1441 for(i = 0; i < 4; ++i) {
1442 if (strcmp_underscore(format_names[i], name) == 0)
1446 if (warning.attribute)
1447 warningf(HERE, "'%s' is an unrecognized format function type", name);
1452 add_anchor_token(')');
1453 add_anchor_token(',');
1454 parse_constant_expression();
1455 rem_anchor_token(',');
1456 rem_anchor_token('(');
1459 add_anchor_token(')');
1460 parse_constant_expression();
1461 rem_anchor_token('(');
1465 attribute->u.value = true;
1468 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1470 if (!attribute->have_arguments)
1473 /* should have no arguments */
1474 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1475 eat_until_matching_token('(');
1476 /* we have already consumed '(', so we stop before ')', eat it */
1478 attribute->invalid = true;
1482 * Parse one GNU attribute.
1484 * Note that attribute names can be specified WITH or WITHOUT
1485 * double underscores, ie const or __const__.
1487 * The following attributes are parsed without arguments
1512 * no_instrument_function
1513 * warn_unused_result
1530 * externally_visible
1538 * The following attributes are parsed with arguments
1539 * aligned( const expression )
1540 * alias( string literal )
1541 * section( string literal )
1542 * format( identifier, const expression, const expression )
1543 * format_arg( const expression )
1544 * tls_model( string literal )
1545 * visibility( string literal )
1546 * regparm( const expression )
1547 * model( string leteral )
1548 * trap_exit( const expression )
1549 * sp_switch( string literal )
1551 * The following attributes might have arguments
1552 * weak_ref( string literal )
1553 * non_null( const expression // ',' )
1554 * interrupt( string literal )
1555 * sentinel( constant expression )
1557 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1559 gnu_attribute_t *head = *attributes;
1560 gnu_attribute_t *last = *attributes;
1561 decl_modifiers_t modifiers = 0;
1562 gnu_attribute_t *attribute;
1564 eat(T___attribute__);
1568 if (token.type != ')') {
1569 /* find the end of the list */
1571 while (last->next != NULL)
1575 /* non-empty attribute list */
1578 if (token.type == T_const) {
1580 } else if (token.type == T_volatile) {
1582 } else if (token.type == T_cdecl) {
1583 /* __attribute__((cdecl)), WITH ms mode */
1585 } else if (token.type == T_IDENTIFIER) {
1586 const symbol_t *sym = token.v.symbol;
1589 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1596 for(i = 0; i < GNU_AK_LAST; ++i) {
1597 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1600 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1603 if (kind == GNU_AK_LAST) {
1604 if (warning.attribute)
1605 warningf(HERE, "'%s' attribute directive ignored", name);
1607 /* skip possible arguments */
1608 if (token.type == '(') {
1609 eat_until_matching_token(')');
1612 /* check for arguments */
1613 attribute = allocate_gnu_attribute(kind);
1614 if (token.type == '(') {
1616 if (token.type == ')') {
1617 /* empty args are allowed */
1620 attribute->have_arguments = true;
1625 case GNU_AK_VOLATILE:
1630 case GNU_AK_NOCOMMON:
1632 case GNU_AK_NOTSHARED:
1633 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1634 case GNU_AK_WARN_UNUSED_RESULT:
1635 case GNU_AK_LONGCALL:
1636 case GNU_AK_SHORTCALL:
1637 case GNU_AK_LONG_CALL:
1638 case GNU_AK_SHORT_CALL:
1639 case GNU_AK_FUNCTION_VECTOR:
1640 case GNU_AK_INTERRUPT_HANDLER:
1641 case GNU_AK_NMI_HANDLER:
1642 case GNU_AK_NESTING:
1646 case GNU_AK_EIGTHBIT_DATA:
1647 case GNU_AK_TINY_DATA:
1648 case GNU_AK_SAVEALL:
1649 case GNU_AK_FLATTEN:
1650 case GNU_AK_SSEREGPARM:
1651 case GNU_AK_EXTERNALLY_VISIBLE:
1652 case GNU_AK_RETURN_TWICE:
1653 case GNU_AK_MAY_ALIAS:
1654 case GNU_AK_MS_STRUCT:
1655 case GNU_AK_GCC_STRUCT:
1658 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1659 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1660 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1661 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1662 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1663 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1664 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1665 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1666 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1667 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1668 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1669 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1670 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1671 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1672 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1673 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1674 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1676 case GNU_AK_ALIGNED:
1677 /* __align__ may be used without an argument */
1678 if (attribute->have_arguments) {
1679 parse_gnu_attribute_const_arg(attribute);
1683 case GNU_AK_FORMAT_ARG:
1684 case GNU_AK_REGPARM:
1685 case GNU_AK_TRAP_EXIT:
1686 if (!attribute->have_arguments) {
1687 /* should have arguments */
1688 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1689 attribute->invalid = true;
1691 parse_gnu_attribute_const_arg(attribute);
1694 case GNU_AK_SECTION:
1695 case GNU_AK_SP_SWITCH:
1696 if (!attribute->have_arguments) {
1697 /* should have arguments */
1698 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1699 attribute->invalid = true;
1701 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1704 if (!attribute->have_arguments) {
1705 /* should have arguments */
1706 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1707 attribute->invalid = true;
1709 parse_gnu_attribute_format_args(attribute);
1711 case GNU_AK_WEAKREF:
1712 /* may have one string argument */
1713 if (attribute->have_arguments)
1714 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1716 case GNU_AK_NONNULL:
1717 if (attribute->have_arguments)
1718 parse_gnu_attribute_const_arg_list(attribute);
1720 case GNU_AK_TLS_MODEL:
1721 if (!attribute->have_arguments) {
1722 /* should have arguments */
1723 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1725 parse_gnu_attribute_tls_model_arg(attribute);
1727 case GNU_AK_VISIBILITY:
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_visibility_arg(attribute);
1735 if (!attribute->have_arguments) {
1736 /* should have arguments */
1737 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1739 parse_gnu_attribute_model_arg(attribute);
1743 if (!attribute->have_arguments) {
1744 /* should have arguments */
1745 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1747 parse_gnu_attribute_mode_arg(attribute);
1750 case GNU_AK_INTERRUPT:
1751 /* may have one string argument */
1752 if (attribute->have_arguments)
1753 parse_gnu_attribute_interrupt_arg(attribute);
1755 case GNU_AK_SENTINEL:
1756 /* may have one string argument */
1757 if (attribute->have_arguments)
1758 parse_gnu_attribute_const_arg(attribute);
1761 /* already handled */
1765 check_no_argument(attribute, name);
1768 if (attribute != NULL) {
1770 last->next = attribute;
1773 head = last = attribute;
1777 if (token.type != ',')
1791 * Parse GNU attributes.
1793 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1795 decl_modifiers_t modifiers = 0;
1798 switch(token.type) {
1799 case T___attribute__:
1800 modifiers |= parse_gnu_attribute(attributes);
1806 if (token.type != T_STRING_LITERAL) {
1807 parse_error_expected("while parsing assembler attribute",
1808 T_STRING_LITERAL, NULL);
1809 eat_until_matching_token('(');
1812 parse_string_literals();
1817 case T_cdecl: modifiers |= DM_CDECL; break;
1818 case T__fastcall: modifiers |= DM_FASTCALL; break;
1819 case T__stdcall: modifiers |= DM_STDCALL; break;
1822 /* TODO record modifier */
1823 warningf(HERE, "Ignoring declaration modifier %K", &token);
1827 default: return modifiers;
1834 static designator_t *parse_designation(void)
1836 designator_t *result = NULL;
1837 designator_t *last = NULL;
1840 designator_t *designator;
1841 switch(token.type) {
1843 designator = allocate_ast_zero(sizeof(designator[0]));
1844 designator->source_position = token.source_position;
1846 add_anchor_token(']');
1847 designator->array_index = parse_constant_expression();
1848 rem_anchor_token(']');
1852 designator = allocate_ast_zero(sizeof(designator[0]));
1853 designator->source_position = token.source_position;
1855 if (token.type != T_IDENTIFIER) {
1856 parse_error_expected("while parsing designator",
1857 T_IDENTIFIER, NULL);
1860 designator->symbol = token.v.symbol;
1868 assert(designator != NULL);
1870 last->next = designator;
1872 result = designator;
1880 static initializer_t *initializer_from_string(array_type_t *type,
1881 const string_t *const string)
1883 /* TODO: check len vs. size of array type */
1886 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1887 initializer->string.string = *string;
1892 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1893 wide_string_t *const string)
1895 /* TODO: check len vs. size of array type */
1898 initializer_t *const initializer =
1899 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1900 initializer->wide_string.string = *string;
1906 * Build an initializer from a given expression.
1908 static initializer_t *initializer_from_expression(type_t *orig_type,
1909 expression_t *expression)
1911 /* TODO check that expression is a constant expression */
1913 /* § 6.7.8.14/15 char array may be initialized by string literals */
1914 type_t *type = skip_typeref(orig_type);
1915 type_t *expr_type_orig = expression->base.type;
1916 type_t *expr_type = skip_typeref(expr_type_orig);
1917 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1918 array_type_t *const array_type = &type->array;
1919 type_t *const element_type = skip_typeref(array_type->element_type);
1921 if (element_type->kind == TYPE_ATOMIC) {
1922 atomic_type_kind_t akind = element_type->atomic.akind;
1923 switch (expression->kind) {
1924 case EXPR_STRING_LITERAL:
1925 if (akind == ATOMIC_TYPE_CHAR
1926 || akind == ATOMIC_TYPE_SCHAR
1927 || akind == ATOMIC_TYPE_UCHAR) {
1928 return initializer_from_string(array_type,
1929 &expression->string.value);
1932 case EXPR_WIDE_STRING_LITERAL: {
1933 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1934 if (get_unqualified_type(element_type) == bare_wchar_type) {
1935 return initializer_from_wide_string(array_type,
1936 &expression->wide_string.value);
1946 assign_error_t error = semantic_assign(type, expression);
1947 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1949 report_assign_error(error, type, expression, "initializer",
1950 &expression->base.source_position);
1952 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1953 result->value.value = create_implicit_cast(expression, type);
1959 * Checks if a given expression can be used as an constant initializer.
1961 static bool is_initializer_constant(const expression_t *expression)
1963 return is_constant_expression(expression)
1964 || is_address_constant(expression);
1968 * Parses an scalar initializer.
1970 * § 6.7.8.11; eat {} without warning
1972 static initializer_t *parse_scalar_initializer(type_t *type,
1973 bool must_be_constant)
1975 /* there might be extra {} hierarchies */
1977 if (token.type == '{') {
1978 warningf(HERE, "extra curly braces around scalar initializer");
1982 } while (token.type == '{');
1985 expression_t *expression = parse_assignment_expression();
1986 if (must_be_constant && !is_initializer_constant(expression)) {
1987 errorf(&expression->base.source_position,
1988 "Initialisation expression '%E' is not constant\n",
1992 initializer_t *initializer = initializer_from_expression(type, expression);
1994 if (initializer == NULL) {
1995 errorf(&expression->base.source_position,
1996 "expression '%E' (type '%T') doesn't match expected type '%T'",
1997 expression, expression->base.type, type);
2002 bool additional_warning_displayed = false;
2003 while (braces > 0) {
2004 if (token.type == ',') {
2007 if (token.type != '}') {
2008 if (!additional_warning_displayed) {
2009 warningf(HERE, "additional elements in scalar initializer");
2010 additional_warning_displayed = true;
2021 * An entry in the type path.
2023 typedef struct type_path_entry_t type_path_entry_t;
2024 struct type_path_entry_t {
2025 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2027 size_t index; /**< For array types: the current index. */
2028 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2033 * A type path expression a position inside compound or array types.
2035 typedef struct type_path_t type_path_t;
2036 struct type_path_t {
2037 type_path_entry_t *path; /**< An flexible array containing the current path. */
2038 type_t *top_type; /**< type of the element the path points */
2039 size_t max_index; /**< largest index in outermost array */
2043 * Prints a type path for debugging.
2045 static __attribute__((unused)) void debug_print_type_path(
2046 const type_path_t *path)
2048 size_t len = ARR_LEN(path->path);
2050 for(size_t i = 0; i < len; ++i) {
2051 const type_path_entry_t *entry = & path->path[i];
2053 type_t *type = skip_typeref(entry->type);
2054 if (is_type_compound(type)) {
2055 /* in gcc mode structs can have no members */
2056 if (entry->v.compound_entry == NULL) {
2060 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2061 } else if (is_type_array(type)) {
2062 fprintf(stderr, "[%zu]", entry->v.index);
2064 fprintf(stderr, "-INVALID-");
2067 if (path->top_type != NULL) {
2068 fprintf(stderr, " (");
2069 print_type(path->top_type);
2070 fprintf(stderr, ")");
2075 * Return the top type path entry, ie. in a path
2076 * (type).a.b returns the b.
2078 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2080 size_t len = ARR_LEN(path->path);
2082 return &path->path[len-1];
2086 * Enlarge the type path by an (empty) element.
2088 static type_path_entry_t *append_to_type_path(type_path_t *path)
2090 size_t len = ARR_LEN(path->path);
2091 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2093 type_path_entry_t *result = & path->path[len];
2094 memset(result, 0, sizeof(result[0]));
2099 * Descending into a sub-type. Enter the scope of the current
2102 static void descend_into_subtype(type_path_t *path)
2104 type_t *orig_top_type = path->top_type;
2105 type_t *top_type = skip_typeref(orig_top_type);
2107 assert(is_type_compound(top_type) || is_type_array(top_type));
2109 type_path_entry_t *top = append_to_type_path(path);
2110 top->type = top_type;
2112 if (is_type_compound(top_type)) {
2113 declaration_t *declaration = top_type->compound.declaration;
2114 declaration_t *entry = declaration->scope.declarations;
2115 top->v.compound_entry = entry;
2117 if (entry != NULL) {
2118 path->top_type = entry->type;
2120 path->top_type = NULL;
2123 assert(is_type_array(top_type));
2126 path->top_type = top_type->array.element_type;
2131 * Pop an entry from the given type path, ie. returning from
2132 * (type).a.b to (type).a
2134 static void ascend_from_subtype(type_path_t *path)
2136 type_path_entry_t *top = get_type_path_top(path);
2138 path->top_type = top->type;
2140 size_t len = ARR_LEN(path->path);
2141 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2145 * Pop entries from the given type path until the given
2146 * path level is reached.
2148 static void ascend_to(type_path_t *path, size_t top_path_level)
2150 size_t len = ARR_LEN(path->path);
2152 while (len > top_path_level) {
2153 ascend_from_subtype(path);
2154 len = ARR_LEN(path->path);
2158 static bool walk_designator(type_path_t *path, const designator_t *designator,
2159 bool used_in_offsetof)
2161 for( ; designator != NULL; designator = designator->next) {
2162 type_path_entry_t *top = get_type_path_top(path);
2163 type_t *orig_type = top->type;
2165 type_t *type = skip_typeref(orig_type);
2167 if (designator->symbol != NULL) {
2168 symbol_t *symbol = designator->symbol;
2169 if (!is_type_compound(type)) {
2170 if (is_type_valid(type)) {
2171 errorf(&designator->source_position,
2172 "'.%Y' designator used for non-compound type '%T'",
2178 declaration_t *declaration = type->compound.declaration;
2179 declaration_t *iter = declaration->scope.declarations;
2180 for( ; iter != NULL; iter = iter->next) {
2181 if (iter->symbol == symbol) {
2186 errorf(&designator->source_position,
2187 "'%T' has no member named '%Y'", orig_type, symbol);
2190 if (used_in_offsetof) {
2191 type_t *real_type = skip_typeref(iter->type);
2192 if (real_type->kind == TYPE_BITFIELD) {
2193 errorf(&designator->source_position,
2194 "offsetof designator '%Y' may not specify bitfield",
2200 top->type = orig_type;
2201 top->v.compound_entry = iter;
2202 orig_type = iter->type;
2204 expression_t *array_index = designator->array_index;
2205 assert(designator->array_index != NULL);
2207 if (!is_type_array(type)) {
2208 if (is_type_valid(type)) {
2209 errorf(&designator->source_position,
2210 "[%E] designator used for non-array type '%T'",
2211 array_index, orig_type);
2215 if (!is_type_valid(array_index->base.type)) {
2219 long index = fold_constant(array_index);
2220 if (!used_in_offsetof) {
2222 errorf(&designator->source_position,
2223 "array index [%E] must be positive", array_index);
2226 if (type->array.size_constant == true) {
2227 long array_size = type->array.size;
2228 if (index >= array_size) {
2229 errorf(&designator->source_position,
2230 "designator [%E] (%d) exceeds array size %d",
2231 array_index, index, array_size);
2237 top->type = orig_type;
2238 top->v.index = (size_t) index;
2239 orig_type = type->array.element_type;
2241 path->top_type = orig_type;
2243 if (designator->next != NULL) {
2244 descend_into_subtype(path);
2253 static void advance_current_object(type_path_t *path, size_t top_path_level)
2255 type_path_entry_t *top = get_type_path_top(path);
2257 type_t *type = skip_typeref(top->type);
2258 if (is_type_union(type)) {
2259 /* in unions only the first element is initialized */
2260 top->v.compound_entry = NULL;
2261 } else if (is_type_struct(type)) {
2262 declaration_t *entry = top->v.compound_entry;
2264 entry = entry->next;
2265 top->v.compound_entry = entry;
2266 if (entry != NULL) {
2267 path->top_type = entry->type;
2271 assert(is_type_array(type));
2275 if (!type->array.size_constant || top->v.index < type->array.size) {
2280 /* we're past the last member of the current sub-aggregate, try if we
2281 * can ascend in the type hierarchy and continue with another subobject */
2282 size_t len = ARR_LEN(path->path);
2284 if (len > top_path_level) {
2285 ascend_from_subtype(path);
2286 advance_current_object(path, top_path_level);
2288 path->top_type = NULL;
2293 * skip until token is found.
2295 static void skip_until(int type)
2297 while (token.type != type) {
2298 if (token.type == T_EOF)
2305 * skip any {...} blocks until a closing bracket is reached.
2307 static void skip_initializers(void)
2309 if (token.type == '{')
2312 while (token.type != '}') {
2313 if (token.type == T_EOF)
2315 if (token.type == '{') {
2323 static initializer_t *create_empty_initializer(void)
2325 static initializer_t empty_initializer
2326 = { .list = { { INITIALIZER_LIST }, 0 } };
2327 return &empty_initializer;
2331 * Parse a part of an initialiser for a struct or union,
2333 static initializer_t *parse_sub_initializer(type_path_t *path,
2334 type_t *outer_type, size_t top_path_level,
2335 parse_initializer_env_t *env)
2337 if (token.type == '}') {
2338 /* empty initializer */
2339 return create_empty_initializer();
2342 type_t *orig_type = path->top_type;
2343 type_t *type = NULL;
2345 if (orig_type == NULL) {
2346 /* We are initializing an empty compound. */
2348 type = skip_typeref(orig_type);
2350 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2351 * initializers in this case. */
2352 if (!is_type_valid(type)) {
2353 skip_initializers();
2354 return create_empty_initializer();
2358 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2361 designator_t *designator = NULL;
2362 if (token.type == '.' || token.type == '[') {
2363 designator = parse_designation();
2364 goto finish_designator;
2365 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2366 /* GNU-style designator ("identifier: value") */
2367 designator = allocate_ast_zero(sizeof(designator[0]));
2368 designator->source_position = token.source_position;
2369 designator->symbol = token.v.symbol;
2374 /* reset path to toplevel, evaluate designator from there */
2375 ascend_to(path, top_path_level);
2376 if (!walk_designator(path, designator, false)) {
2377 /* can't continue after designation error */
2381 initializer_t *designator_initializer
2382 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2383 designator_initializer->designator.designator = designator;
2384 ARR_APP1(initializer_t*, initializers, designator_initializer);
2386 orig_type = path->top_type;
2387 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2392 if (token.type == '{') {
2393 if (type != NULL && is_type_scalar(type)) {
2394 sub = parse_scalar_initializer(type, env->must_be_constant);
2398 if (env->declaration != NULL) {
2399 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2400 env->declaration->symbol);
2402 errorf(HERE, "extra brace group at end of initializer");
2405 descend_into_subtype(path);
2407 add_anchor_token('}');
2408 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2410 rem_anchor_token('}');
2413 ascend_from_subtype(path);
2417 goto error_parse_next;
2421 /* must be an expression */
2422 expression_t *expression = parse_assignment_expression();
2424 if (env->must_be_constant && !is_initializer_constant(expression)) {
2425 errorf(&expression->base.source_position,
2426 "Initialisation expression '%E' is not constant\n",
2431 /* we are already outside, ... */
2435 /* handle { "string" } special case */
2436 if ((expression->kind == EXPR_STRING_LITERAL
2437 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2438 && outer_type != NULL) {
2439 sub = initializer_from_expression(outer_type, expression);
2441 if (token.type == ',') {
2444 if (token.type != '}') {
2445 warningf(HERE, "excessive elements in initializer for type '%T'",
2448 /* TODO: eat , ... */
2453 /* descend into subtypes until expression matches type */
2455 orig_type = path->top_type;
2456 type = skip_typeref(orig_type);
2458 sub = initializer_from_expression(orig_type, expression);
2462 if (!is_type_valid(type)) {
2465 if (is_type_scalar(type)) {
2466 errorf(&expression->base.source_position,
2467 "expression '%E' doesn't match expected type '%T'",
2468 expression, orig_type);
2472 descend_into_subtype(path);
2476 /* update largest index of top array */
2477 const type_path_entry_t *first = &path->path[0];
2478 type_t *first_type = first->type;
2479 first_type = skip_typeref(first_type);
2480 if (is_type_array(first_type)) {
2481 size_t index = first->v.index;
2482 if (index > path->max_index)
2483 path->max_index = index;
2487 /* append to initializers list */
2488 ARR_APP1(initializer_t*, initializers, sub);
2491 if (env->declaration != NULL)
2492 warningf(HERE, "excess elements in struct initializer for '%Y'",
2493 env->declaration->symbol);
2495 warningf(HERE, "excess elements in struct initializer");
2499 if (token.type == '}') {
2503 if (token.type == '}') {
2508 /* advance to the next declaration if we are not at the end */
2509 advance_current_object(path, top_path_level);
2510 orig_type = path->top_type;
2511 if (orig_type != NULL)
2512 type = skip_typeref(orig_type);
2518 size_t len = ARR_LEN(initializers);
2519 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2520 initializer_t *result = allocate_ast_zero(size);
2521 result->kind = INITIALIZER_LIST;
2522 result->list.len = len;
2523 memcpy(&result->list.initializers, initializers,
2524 len * sizeof(initializers[0]));
2526 DEL_ARR_F(initializers);
2527 ascend_to(path, top_path_level+1);
2532 skip_initializers();
2533 DEL_ARR_F(initializers);
2534 ascend_to(path, top_path_level+1);
2539 * Parses an initializer. Parsers either a compound literal
2540 * (env->declaration == NULL) or an initializer of a declaration.
2542 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2544 type_t *type = skip_typeref(env->type);
2545 initializer_t *result = NULL;
2548 if (is_type_scalar(type)) {
2549 result = parse_scalar_initializer(type, env->must_be_constant);
2550 } else if (token.type == '{') {
2554 memset(&path, 0, sizeof(path));
2555 path.top_type = env->type;
2556 path.path = NEW_ARR_F(type_path_entry_t, 0);
2558 descend_into_subtype(&path);
2560 add_anchor_token('}');
2561 result = parse_sub_initializer(&path, env->type, 1, env);
2562 rem_anchor_token('}');
2564 max_index = path.max_index;
2565 DEL_ARR_F(path.path);
2569 /* parse_scalar_initializer() also works in this case: we simply
2570 * have an expression without {} around it */
2571 result = parse_scalar_initializer(type, env->must_be_constant);
2574 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2575 * the array type size */
2576 if (is_type_array(type) && type->array.size_expression == NULL
2577 && result != NULL) {
2579 switch (result->kind) {
2580 case INITIALIZER_LIST:
2581 size = max_index + 1;
2584 case INITIALIZER_STRING:
2585 size = result->string.string.size;
2588 case INITIALIZER_WIDE_STRING:
2589 size = result->wide_string.string.size;
2592 case INITIALIZER_DESIGNATOR:
2593 case INITIALIZER_VALUE:
2594 /* can happen for parse errors */
2599 internal_errorf(HERE, "invalid initializer type");
2602 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2603 cnst->base.type = type_size_t;
2604 cnst->conste.v.int_value = size;
2606 type_t *new_type = duplicate_type(type);
2608 new_type->array.size_expression = cnst;
2609 new_type->array.size_constant = true;
2610 new_type->array.size = size;
2611 env->type = new_type;
2619 static declaration_t *append_declaration(declaration_t *declaration);
2621 static declaration_t *parse_compound_type_specifier(bool is_struct)
2623 gnu_attribute_t *attributes = NULL;
2624 decl_modifiers_t modifiers = 0;
2631 symbol_t *symbol = NULL;
2632 declaration_t *declaration = NULL;
2634 if (token.type == T___attribute__) {
2635 modifiers |= parse_attributes(&attributes);
2638 if (token.type == T_IDENTIFIER) {
2639 symbol = token.v.symbol;
2642 namespace_t const namespc =
2643 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2644 declaration = get_declaration(symbol, namespc);
2645 if (declaration != NULL) {
2646 if (declaration->parent_scope != scope &&
2647 (token.type == '{' || token.type == ';')) {
2649 } else if (declaration->init.complete &&
2650 token.type == '{') {
2651 assert(symbol != NULL);
2652 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2653 is_struct ? "struct" : "union", symbol,
2654 &declaration->source_position);
2655 declaration->scope.declarations = NULL;
2658 } else if (token.type != '{') {
2660 parse_error_expected("while parsing struct type specifier",
2661 T_IDENTIFIER, '{', NULL);
2663 parse_error_expected("while parsing union type specifier",
2664 T_IDENTIFIER, '{', NULL);
2670 if (declaration == NULL) {
2671 declaration = allocate_declaration_zero();
2672 declaration->namespc =
2673 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2674 declaration->source_position = token.source_position;
2675 declaration->symbol = symbol;
2676 declaration->parent_scope = scope;
2677 if (symbol != NULL) {
2678 environment_push(declaration);
2680 append_declaration(declaration);
2683 if (token.type == '{') {
2684 declaration->init.complete = true;
2686 parse_compound_type_entries(declaration);
2687 modifiers |= parse_attributes(&attributes);
2690 declaration->modifiers |= modifiers;
2694 static void parse_enum_entries(type_t *const enum_type)
2698 if (token.type == '}') {
2700 errorf(HERE, "empty enum not allowed");
2704 add_anchor_token('}');
2706 if (token.type != T_IDENTIFIER) {
2707 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2709 rem_anchor_token('}');
2713 declaration_t *const entry = allocate_declaration_zero();
2714 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2715 entry->type = enum_type;
2716 entry->symbol = token.v.symbol;
2717 entry->source_position = token.source_position;
2720 if (token.type == '=') {
2722 expression_t *value = parse_constant_expression();
2724 value = create_implicit_cast(value, enum_type);
2725 entry->init.enum_value = value;
2730 record_declaration(entry);
2732 if (token.type != ',')
2735 } while (token.type != '}');
2736 rem_anchor_token('}');
2744 static type_t *parse_enum_specifier(void)
2746 gnu_attribute_t *attributes = NULL;
2747 declaration_t *declaration;
2751 if (token.type == T_IDENTIFIER) {
2752 symbol = token.v.symbol;
2755 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2756 } else if (token.type != '{') {
2757 parse_error_expected("while parsing enum type specifier",
2758 T_IDENTIFIER, '{', NULL);
2765 if (declaration == NULL) {
2766 declaration = allocate_declaration_zero();
2767 declaration->namespc = NAMESPACE_ENUM;
2768 declaration->source_position = token.source_position;
2769 declaration->symbol = symbol;
2770 declaration->parent_scope = scope;
2773 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2774 type->enumt.declaration = declaration;
2776 if (token.type == '{') {
2777 if (declaration->init.complete) {
2778 errorf(HERE, "multiple definitions of enum %Y", symbol);
2780 if (symbol != NULL) {
2781 environment_push(declaration);
2783 append_declaration(declaration);
2784 declaration->init.complete = true;
2786 parse_enum_entries(type);
2787 parse_attributes(&attributes);
2794 * if a symbol is a typedef to another type, return true
2796 static bool is_typedef_symbol(symbol_t *symbol)
2798 const declaration_t *const declaration =
2799 get_declaration(symbol, NAMESPACE_NORMAL);
2801 declaration != NULL &&
2802 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2805 static type_t *parse_typeof(void)
2812 add_anchor_token(')');
2814 expression_t *expression = NULL;
2817 switch(token.type) {
2818 case T___extension__:
2819 /* This can be a prefix to a typename or an expression. We simply eat
2823 } while (token.type == T___extension__);
2827 if (is_typedef_symbol(token.v.symbol)) {
2828 type = parse_typename();
2830 expression = parse_expression();
2831 type = expression->base.type;
2836 type = parse_typename();
2840 expression = parse_expression();
2841 type = expression->base.type;
2845 rem_anchor_token(')');
2848 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2849 typeof_type->typeoft.expression = expression;
2850 typeof_type->typeoft.typeof_type = type;
2857 typedef enum specifiers_t {
2858 SPECIFIER_SIGNED = 1 << 0,
2859 SPECIFIER_UNSIGNED = 1 << 1,
2860 SPECIFIER_LONG = 1 << 2,
2861 SPECIFIER_INT = 1 << 3,
2862 SPECIFIER_DOUBLE = 1 << 4,
2863 SPECIFIER_CHAR = 1 << 5,
2864 SPECIFIER_SHORT = 1 << 6,
2865 SPECIFIER_LONG_LONG = 1 << 7,
2866 SPECIFIER_FLOAT = 1 << 8,
2867 SPECIFIER_BOOL = 1 << 9,
2868 SPECIFIER_VOID = 1 << 10,
2869 SPECIFIER_INT8 = 1 << 11,
2870 SPECIFIER_INT16 = 1 << 12,
2871 SPECIFIER_INT32 = 1 << 13,
2872 SPECIFIER_INT64 = 1 << 14,
2873 SPECIFIER_INT128 = 1 << 15,
2874 SPECIFIER_COMPLEX = 1 << 16,
2875 SPECIFIER_IMAGINARY = 1 << 17,
2878 static type_t *create_builtin_type(symbol_t *const symbol,
2879 type_t *const real_type)
2881 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2882 type->builtin.symbol = symbol;
2883 type->builtin.real_type = real_type;
2885 type_t *result = typehash_insert(type);
2886 if (type != result) {
2893 static type_t *get_typedef_type(symbol_t *symbol)
2895 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2896 if (declaration == NULL ||
2897 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2900 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2901 type->typedeft.declaration = declaration;
2907 * check for the allowed MS alignment values.
2909 static bool check_alignment_value(long long intvalue)
2911 if (intvalue < 1 || intvalue > 8192) {
2912 errorf(HERE, "illegal alignment value");
2915 unsigned v = (unsigned)intvalue;
2916 for(unsigned i = 1; i <= 8192; i += i) {
2920 errorf(HERE, "alignment must be power of two");
2924 #define DET_MOD(name, tag) do { \
2925 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2926 *modifiers |= tag; \
2929 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2931 decl_modifiers_t *modifiers = &specifiers->modifiers;
2934 if (token.type == T_restrict) {
2936 DET_MOD(restrict, DM_RESTRICT);
2938 } else if (token.type != T_IDENTIFIER)
2940 symbol_t *symbol = token.v.symbol;
2941 if (symbol == sym_align) {
2944 if (token.type != T_INTEGER)
2946 if (check_alignment_value(token.v.intvalue)) {
2947 if (specifiers->alignment != 0)
2948 warningf(HERE, "align used more than once");
2949 specifiers->alignment = (unsigned char)token.v.intvalue;
2953 } else if (symbol == sym_allocate) {
2956 if (token.type != T_IDENTIFIER)
2958 (void)token.v.symbol;
2960 } else if (symbol == sym_dllimport) {
2962 DET_MOD(dllimport, DM_DLLIMPORT);
2963 } else if (symbol == sym_dllexport) {
2965 DET_MOD(dllexport, DM_DLLEXPORT);
2966 } else if (symbol == sym_thread) {
2968 DET_MOD(thread, DM_THREAD);
2969 } else if (symbol == sym_naked) {
2971 DET_MOD(naked, DM_NAKED);
2972 } else if (symbol == sym_noinline) {
2974 DET_MOD(noinline, DM_NOINLINE);
2975 } else if (symbol == sym_noreturn) {
2977 DET_MOD(noreturn, DM_NORETURN);
2978 } else if (symbol == sym_nothrow) {
2980 DET_MOD(nothrow, DM_NOTHROW);
2981 } else if (symbol == sym_novtable) {
2983 DET_MOD(novtable, DM_NOVTABLE);
2984 } else if (symbol == sym_property) {
2988 bool is_get = false;
2989 if (token.type != T_IDENTIFIER)
2991 if (token.v.symbol == sym_get) {
2993 } else if (token.v.symbol == sym_put) {
2995 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3000 if (token.type != T_IDENTIFIER)
3003 if (specifiers->get_property_sym != NULL) {
3004 errorf(HERE, "get property name already specified");
3006 specifiers->get_property_sym = token.v.symbol;
3009 if (specifiers->put_property_sym != NULL) {
3010 errorf(HERE, "put property name already specified");
3012 specifiers->put_property_sym = token.v.symbol;
3016 if (token.type == ',') {
3023 } else if (symbol == sym_selectany) {
3025 DET_MOD(selectany, DM_SELECTANY);
3026 } else if (symbol == sym_uuid) {
3029 if (token.type != T_STRING_LITERAL)
3033 } else if (symbol == sym_deprecated) {
3035 if (specifiers->deprecated != 0)
3036 warningf(HERE, "deprecated used more than once");
3037 specifiers->deprecated = 1;
3038 if (token.type == '(') {
3040 if (token.type == T_STRING_LITERAL) {
3041 specifiers->deprecated_string = token.v.string.begin;
3044 errorf(HERE, "string literal expected");
3048 } else if (symbol == sym_noalias) {
3050 DET_MOD(noalias, DM_NOALIAS);
3052 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3054 if (token.type == '(')
3058 if (token.type == ',')
3065 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3067 declaration_t *const decl = allocate_declaration_zero();
3068 decl->source_position = *HERE;
3069 decl->declared_storage_class = storage_class;
3070 decl->storage_class =
3071 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3072 storage_class : STORAGE_CLASS_AUTO;
3073 decl->symbol = symbol;
3074 decl->implicit = true;
3075 record_declaration(decl);
3079 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3081 type_t *type = NULL;
3082 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3083 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3084 unsigned type_specifiers = 0;
3085 bool newtype = false;
3086 bool saw_error = false;
3088 specifiers->source_position = token.source_position;
3091 specifiers->modifiers
3092 |= parse_attributes(&specifiers->gnu_attributes);
3093 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3094 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3096 switch(token.type) {
3099 #define MATCH_STORAGE_CLASS(token, class) \
3101 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3102 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3104 specifiers->declared_storage_class = class; \
3108 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3109 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3110 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3111 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3112 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3117 add_anchor_token(')');
3118 parse_microsoft_extended_decl_modifier(specifiers);
3119 rem_anchor_token(')');
3124 switch (specifiers->declared_storage_class) {
3125 case STORAGE_CLASS_NONE:
3126 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3129 case STORAGE_CLASS_EXTERN:
3130 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3133 case STORAGE_CLASS_STATIC:
3134 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3138 errorf(HERE, "multiple storage classes in declaration specifiers");
3144 /* type qualifiers */
3145 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3147 qualifiers |= qualifier; \
3151 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3152 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3153 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3154 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3155 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3156 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3157 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3158 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3160 case T___extension__:
3165 /* type specifiers */
3166 #define MATCH_SPECIFIER(token, specifier, name) \
3169 if (type_specifiers & specifier) { \
3170 errorf(HERE, "multiple " name " type specifiers given"); \
3172 type_specifiers |= specifier; \
3176 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3177 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3178 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3179 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3180 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3181 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3182 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3183 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3184 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3185 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3186 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3187 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3188 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3189 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3190 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3191 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3193 case T__forceinline:
3194 /* only in microsoft mode */
3195 specifiers->modifiers |= DM_FORCEINLINE;
3200 specifiers->is_inline = true;
3205 if (type_specifiers & SPECIFIER_LONG_LONG) {
3206 errorf(HERE, "multiple type specifiers given");
3207 } else if (type_specifiers & SPECIFIER_LONG) {
3208 type_specifiers |= SPECIFIER_LONG_LONG;
3210 type_specifiers |= SPECIFIER_LONG;
3215 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3217 type->compound.declaration = parse_compound_type_specifier(true);
3221 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3222 type->compound.declaration = parse_compound_type_specifier(false);
3223 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3224 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3228 type = parse_enum_specifier();
3231 type = parse_typeof();
3233 case T___builtin_va_list:
3234 type = duplicate_type(type_valist);
3238 case T_IDENTIFIER: {
3239 /* only parse identifier if we haven't found a type yet */
3240 if (type != NULL || type_specifiers != 0) {
3241 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3242 * declaration, so it doesn't generate errors about expecting '(' or
3244 switch (look_ahead(1)->type) {
3251 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3254 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3259 goto finish_specifiers;
3263 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3264 if (typedef_type == NULL) {
3265 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3266 * declaration, so it doesn't generate 'implicit int' followed by more
3267 * errors later on. */
3268 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3273 errorf(HERE, "%K does not name a type", &token);
3275 declaration_t *const decl =
3276 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3278 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3279 type->typedeft.declaration = decl;
3283 if (la1_type == '*')
3284 goto finish_specifiers;
3289 goto finish_specifiers;
3294 type = typedef_type;
3298 /* function specifier */
3300 goto finish_specifiers;
3305 if (type == NULL || (saw_error && type_specifiers != 0)) {
3306 atomic_type_kind_t atomic_type;
3308 /* match valid basic types */
3309 switch(type_specifiers) {
3310 case SPECIFIER_VOID:
3311 atomic_type = ATOMIC_TYPE_VOID;
3313 case SPECIFIER_CHAR:
3314 atomic_type = ATOMIC_TYPE_CHAR;
3316 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3317 atomic_type = ATOMIC_TYPE_SCHAR;
3319 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3320 atomic_type = ATOMIC_TYPE_UCHAR;
3322 case SPECIFIER_SHORT:
3323 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3324 case SPECIFIER_SHORT | SPECIFIER_INT:
3325 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3326 atomic_type = ATOMIC_TYPE_SHORT;
3328 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3329 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3330 atomic_type = ATOMIC_TYPE_USHORT;
3333 case SPECIFIER_SIGNED:
3334 case SPECIFIER_SIGNED | SPECIFIER_INT:
3335 atomic_type = ATOMIC_TYPE_INT;
3337 case SPECIFIER_UNSIGNED:
3338 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3339 atomic_type = ATOMIC_TYPE_UINT;
3341 case SPECIFIER_LONG:
3342 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3343 case SPECIFIER_LONG | SPECIFIER_INT:
3344 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3345 atomic_type = ATOMIC_TYPE_LONG;
3347 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3348 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3349 atomic_type = ATOMIC_TYPE_ULONG;
3352 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3353 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3354 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3355 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3357 atomic_type = ATOMIC_TYPE_LONGLONG;
3358 goto warn_about_long_long;
3360 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3361 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3363 atomic_type = ATOMIC_TYPE_ULONGLONG;
3364 warn_about_long_long:
3365 if (warning.long_long) {
3366 warningf(&specifiers->source_position,
3367 "ISO C90 does not support 'long long'");
3371 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3372 atomic_type = unsigned_int8_type_kind;
3375 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3376 atomic_type = unsigned_int16_type_kind;
3379 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3380 atomic_type = unsigned_int32_type_kind;
3383 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3384 atomic_type = unsigned_int64_type_kind;
3387 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3388 atomic_type = unsigned_int128_type_kind;
3391 case SPECIFIER_INT8:
3392 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3393 atomic_type = int8_type_kind;
3396 case SPECIFIER_INT16:
3397 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3398 atomic_type = int16_type_kind;
3401 case SPECIFIER_INT32:
3402 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3403 atomic_type = int32_type_kind;
3406 case SPECIFIER_INT64:
3407 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3408 atomic_type = int64_type_kind;
3411 case SPECIFIER_INT128:
3412 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3413 atomic_type = int128_type_kind;
3416 case SPECIFIER_FLOAT:
3417 atomic_type = ATOMIC_TYPE_FLOAT;
3419 case SPECIFIER_DOUBLE:
3420 atomic_type = ATOMIC_TYPE_DOUBLE;
3422 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3423 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3425 case SPECIFIER_BOOL:
3426 atomic_type = ATOMIC_TYPE_BOOL;
3428 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3429 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3430 atomic_type = ATOMIC_TYPE_FLOAT;
3432 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3433 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3434 atomic_type = ATOMIC_TYPE_DOUBLE;
3436 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3437 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3438 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3441 /* invalid specifier combination, give an error message */
3442 if (type_specifiers == 0) {
3444 specifiers->type = type_error_type;
3449 if (warning.implicit_int) {
3450 warningf(HERE, "no type specifiers in declaration, using 'int'");
3452 atomic_type = ATOMIC_TYPE_INT;
3455 errorf(HERE, "no type specifiers given in declaration");
3457 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3458 (type_specifiers & SPECIFIER_UNSIGNED)) {
3459 errorf(HERE, "signed and unsigned specifiers given");
3460 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3461 errorf(HERE, "only integer types can be signed or unsigned");
3463 errorf(HERE, "multiple datatypes in declaration");
3465 atomic_type = ATOMIC_TYPE_INVALID;
3468 if (type_specifiers & SPECIFIER_COMPLEX &&
3469 atomic_type != ATOMIC_TYPE_INVALID) {
3470 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3471 type->complex.akind = atomic_type;
3472 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3473 atomic_type != ATOMIC_TYPE_INVALID) {
3474 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3475 type->imaginary.akind = atomic_type;
3477 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3478 type->atomic.akind = atomic_type;
3481 } else if (type_specifiers != 0) {
3482 errorf(HERE, "multiple datatypes in declaration");
3485 /* FIXME: check type qualifiers here */
3487 type->base.qualifiers = qualifiers;
3488 type->base.modifiers = modifiers;
3490 type_t *result = typehash_insert(type);
3491 if (newtype && result != type) {
3495 specifiers->type = result;
3500 static type_qualifiers_t parse_type_qualifiers(void)
3502 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3505 switch(token.type) {
3506 /* type qualifiers */
3507 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3508 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3509 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3510 /* microsoft extended type modifiers */
3511 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3512 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3513 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3514 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3515 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3523 static declaration_t *parse_identifier_list(void)
3525 declaration_t *declarations = NULL;
3526 declaration_t *last_declaration = NULL;
3528 declaration_t *const declaration = allocate_declaration_zero();
3529 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3530 declaration->source_position = token.source_position;
3531 declaration->symbol = token.v.symbol;
3534 if (last_declaration != NULL) {
3535 last_declaration->next = declaration;
3537 declarations = declaration;
3539 last_declaration = declaration;
3541 if (token.type != ',') {
3545 } while (token.type == T_IDENTIFIER);
3547 return declarations;
3550 static type_t *automatic_type_conversion(type_t *orig_type);
3552 static void semantic_parameter(declaration_t *declaration)
3554 /* TODO: improve error messages */
3555 source_position_t const* const pos = &declaration->source_position;
3557 switch (declaration->declared_storage_class) {
3558 case STORAGE_CLASS_TYPEDEF:
3559 errorf(pos, "typedef not allowed in parameter list");
3562 /* Allowed storage classes */
3563 case STORAGE_CLASS_NONE:
3564 case STORAGE_CLASS_REGISTER:
3568 errorf(pos, "parameter may only have none or register storage class");
3572 type_t *const orig_type = declaration->type;
3573 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3574 * sugar. Turn it into a pointer.
3575 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3576 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3578 type_t *const type = automatic_type_conversion(orig_type);
3579 declaration->type = type;
3581 if (is_type_incomplete(skip_typeref(type))) {
3582 errorf(pos, "incomplete type '%T' not allowed for parameter '%Y'",
3583 orig_type, declaration->symbol);
3587 static declaration_t *parse_parameter(void)
3589 declaration_specifiers_t specifiers;
3590 memset(&specifiers, 0, sizeof(specifiers));
3592 parse_declaration_specifiers(&specifiers);
3594 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3599 static declaration_t *parse_parameters(function_type_t *type)
3601 declaration_t *declarations = NULL;
3604 add_anchor_token(')');
3605 int saved_comma_state = save_and_reset_anchor_state(',');
3607 if (token.type == T_IDENTIFIER &&
3608 !is_typedef_symbol(token.v.symbol)) {
3609 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3610 if (la1_type == ',' || la1_type == ')') {
3611 type->kr_style_parameters = true;
3612 declarations = parse_identifier_list();
3613 goto parameters_finished;
3617 if (token.type == ')') {
3618 type->unspecified_parameters = 1;
3619 goto parameters_finished;
3622 declaration_t *declaration;
3623 declaration_t *last_declaration = NULL;
3624 function_parameter_t *parameter;
3625 function_parameter_t *last_parameter = NULL;
3628 switch(token.type) {
3632 goto parameters_finished;
3635 case T___extension__:
3637 declaration = parse_parameter();
3639 /* func(void) is not a parameter */
3640 if (last_parameter == NULL
3641 && token.type == ')'
3642 && declaration->symbol == NULL
3643 && skip_typeref(declaration->type) == type_void) {
3644 goto parameters_finished;
3646 semantic_parameter(declaration);
3648 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3649 memset(parameter, 0, sizeof(parameter[0]));
3650 parameter->type = declaration->type;
3652 if (last_parameter != NULL) {
3653 last_declaration->next = declaration;
3654 last_parameter->next = parameter;
3656 type->parameters = parameter;
3657 declarations = declaration;
3659 last_parameter = parameter;
3660 last_declaration = declaration;
3664 goto parameters_finished;
3666 if (token.type != ',') {
3667 goto parameters_finished;
3673 parameters_finished:
3674 rem_anchor_token(')');
3677 restore_anchor_state(',', saved_comma_state);
3678 return declarations;
3681 restore_anchor_state(',', saved_comma_state);
3685 typedef enum construct_type_kind_t {
3690 } construct_type_kind_t;
3692 typedef struct construct_type_t construct_type_t;
3693 struct construct_type_t {
3694 construct_type_kind_t kind;
3695 construct_type_t *next;
3698 typedef struct parsed_pointer_t parsed_pointer_t;
3699 struct parsed_pointer_t {
3700 construct_type_t construct_type;
3701 type_qualifiers_t type_qualifiers;
3704 typedef struct construct_function_type_t construct_function_type_t;
3705 struct construct_function_type_t {
3706 construct_type_t construct_type;
3707 type_t *function_type;
3710 typedef struct parsed_array_t parsed_array_t;
3711 struct parsed_array_t {
3712 construct_type_t construct_type;
3713 type_qualifiers_t type_qualifiers;
3719 typedef struct construct_base_type_t construct_base_type_t;
3720 struct construct_base_type_t {
3721 construct_type_t construct_type;
3725 static construct_type_t *parse_pointer_declarator(void)
3729 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3730 memset(pointer, 0, sizeof(pointer[0]));
3731 pointer->construct_type.kind = CONSTRUCT_POINTER;
3732 pointer->type_qualifiers = parse_type_qualifiers();
3734 return (construct_type_t*) pointer;
3737 static construct_type_t *parse_array_declarator(void)
3740 add_anchor_token(']');
3742 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3743 memset(array, 0, sizeof(array[0]));
3744 array->construct_type.kind = CONSTRUCT_ARRAY;
3746 if (token.type == T_static) {
3747 array->is_static = true;
3751 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3752 if (type_qualifiers != 0) {
3753 if (token.type == T_static) {
3754 array->is_static = true;
3758 array->type_qualifiers = type_qualifiers;
3760 if (token.type == '*' && look_ahead(1)->type == ']') {
3761 array->is_variable = true;
3763 } else if (token.type != ']') {
3764 array->size = parse_assignment_expression();
3767 rem_anchor_token(']');
3770 return (construct_type_t*) array;
3775 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3778 if (declaration != NULL) {
3779 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3781 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3783 if (mask & (mask-1)) {
3784 const char *first = NULL, *second = NULL;
3786 /* more than one calling convention set */
3787 if (declaration->modifiers & DM_CDECL) {
3788 if (first == NULL) first = "cdecl";
3789 else if (second == NULL) second = "cdecl";
3791 if (declaration->modifiers & DM_STDCALL) {
3792 if (first == NULL) first = "stdcall";
3793 else if (second == NULL) second = "stdcall";
3795 if (declaration->modifiers & DM_FASTCALL) {
3796 if (first == NULL) first = "fastcall";
3797 else if (second == NULL) second = "fastcall";
3799 if (declaration->modifiers & DM_THISCALL) {
3800 if (first == NULL) first = "thiscall";
3801 else if (second == NULL) second = "thiscall";
3803 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3806 if (declaration->modifiers & DM_CDECL)
3807 type->function.calling_convention = CC_CDECL;
3808 else if (declaration->modifiers & DM_STDCALL)
3809 type->function.calling_convention = CC_STDCALL;
3810 else if (declaration->modifiers & DM_FASTCALL)
3811 type->function.calling_convention = CC_FASTCALL;
3812 else if (declaration->modifiers & DM_THISCALL)
3813 type->function.calling_convention = CC_THISCALL;
3815 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3818 declaration_t *parameters = parse_parameters(&type->function);
3819 if (declaration != NULL) {
3820 declaration->scope.declarations = parameters;
3823 construct_function_type_t *construct_function_type =
3824 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3825 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3826 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3827 construct_function_type->function_type = type;
3829 return &construct_function_type->construct_type;
3832 static void fix_declaration_type(declaration_t *declaration)
3834 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3835 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3837 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3838 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3840 if (declaration->type->base.modifiers == type_modifiers)
3843 type_t *copy = duplicate_type(declaration->type);
3844 copy->base.modifiers = type_modifiers;
3846 type_t *result = typehash_insert(copy);
3847 if (result != copy) {
3848 obstack_free(type_obst, copy);
3851 declaration->type = result;
3854 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3855 bool may_be_abstract)
3857 /* construct a single linked list of construct_type_t's which describe
3858 * how to construct the final declarator type */
3859 construct_type_t *first = NULL;
3860 construct_type_t *last = NULL;
3861 gnu_attribute_t *attributes = NULL;
3863 decl_modifiers_t modifiers = parse_attributes(&attributes);
3866 while (token.type == '*') {
3867 construct_type_t *type = parse_pointer_declarator();
3877 /* TODO: find out if this is correct */
3878 modifiers |= parse_attributes(&attributes);
3881 if (declaration != NULL)
3882 declaration->modifiers |= modifiers;
3884 construct_type_t *inner_types = NULL;
3886 switch(token.type) {
3888 if (declaration == NULL) {
3889 errorf(HERE, "no identifier expected in typename");
3891 declaration->symbol = token.v.symbol;
3892 declaration->source_position = token.source_position;
3898 add_anchor_token(')');
3899 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3900 /* All later declarators only modify the return type, not declaration */
3902 rem_anchor_token(')');
3906 if (may_be_abstract)
3908 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3909 /* avoid a loop in the outermost scope, because eat_statement doesn't
3911 if (token.type == '}' && current_function == NULL) {
3919 construct_type_t *p = last;
3922 construct_type_t *type;
3923 switch(token.type) {
3925 type = parse_function_declarator(declaration);
3928 type = parse_array_declarator();
3931 goto declarator_finished;
3934 /* insert in the middle of the list (behind p) */
3936 type->next = p->next;
3947 declarator_finished:
3948 /* append inner_types at the end of the list, we don't to set last anymore
3949 * as it's not needed anymore */
3951 assert(first == NULL);
3952 first = inner_types;
3954 last->next = inner_types;
3962 static void parse_declaration_attributes(declaration_t *declaration)
3964 gnu_attribute_t *attributes = NULL;
3965 decl_modifiers_t modifiers = parse_attributes(&attributes);
3967 if (declaration == NULL)
3970 declaration->modifiers |= modifiers;
3971 /* check if we have these stupid mode attributes... */
3972 type_t *old_type = declaration->type;
3973 if (old_type == NULL)
3976 gnu_attribute_t *attribute = attributes;
3977 for ( ; attribute != NULL; attribute = attribute->next) {
3978 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3981 atomic_type_kind_t akind = attribute->u.akind;
3982 if (!is_type_signed(old_type)) {
3984 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3985 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3986 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3987 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3989 panic("invalid akind in mode attribute");
3993 = make_atomic_type(akind, old_type->base.qualifiers);
3997 static type_t *construct_declarator_type(construct_type_t *construct_list,
4000 construct_type_t *iter = construct_list;
4001 for( ; iter != NULL; iter = iter->next) {
4002 switch(iter->kind) {
4003 case CONSTRUCT_INVALID:
4004 internal_errorf(HERE, "invalid type construction found");
4005 case CONSTRUCT_FUNCTION: {
4006 construct_function_type_t *construct_function_type
4007 = (construct_function_type_t*) iter;
4009 type_t *function_type = construct_function_type->function_type;
4011 function_type->function.return_type = type;
4013 type_t *skipped_return_type = skip_typeref(type);
4014 if (is_type_function(skipped_return_type)) {
4015 errorf(HERE, "function returning function is not allowed");
4016 type = type_error_type;
4017 } else if (is_type_array(skipped_return_type)) {
4018 errorf(HERE, "function returning array is not allowed");
4019 type = type_error_type;
4021 type = function_type;
4026 case CONSTRUCT_POINTER: {
4027 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4028 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4029 pointer_type->pointer.points_to = type;
4030 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4032 type = pointer_type;
4036 case CONSTRUCT_ARRAY: {
4037 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4038 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4040 expression_t *size_expression = parsed_array->size;
4041 if (size_expression != NULL) {
4043 = create_implicit_cast(size_expression, type_size_t);
4046 array_type->base.qualifiers = parsed_array->type_qualifiers;
4047 array_type->array.element_type = type;
4048 array_type->array.is_static = parsed_array->is_static;
4049 array_type->array.is_variable = parsed_array->is_variable;
4050 array_type->array.size_expression = size_expression;
4052 if (size_expression != NULL) {
4053 if (is_constant_expression(size_expression)) {
4054 array_type->array.size_constant = true;
4055 array_type->array.size
4056 = fold_constant(size_expression);
4058 array_type->array.is_vla = true;
4062 type_t *skipped_type = skip_typeref(type);
4063 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4064 errorf(HERE, "array of void is not allowed");
4065 type = type_error_type;
4073 type_t *hashed_type = typehash_insert(type);
4074 if (hashed_type != type) {
4075 /* the function type was constructed earlier freeing it here will
4076 * destroy other types... */
4077 if (iter->kind != CONSTRUCT_FUNCTION) {
4087 static declaration_t *parse_declarator(
4088 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4090 declaration_t *const declaration = allocate_declaration_zero();
4091 declaration->source_position = specifiers->source_position;
4092 declaration->declared_storage_class = specifiers->declared_storage_class;
4093 declaration->modifiers = specifiers->modifiers;
4094 declaration->deprecated_string = specifiers->deprecated_string;
4095 declaration->get_property_sym = specifiers->get_property_sym;
4096 declaration->put_property_sym = specifiers->put_property_sym;
4097 declaration->is_inline = specifiers->is_inline;
4099 declaration->storage_class = specifiers->declared_storage_class;
4100 if (declaration->storage_class == STORAGE_CLASS_NONE
4101 && scope != global_scope) {
4102 declaration->storage_class = STORAGE_CLASS_AUTO;
4105 if (specifiers->alignment != 0) {
4106 /* TODO: add checks here */
4107 declaration->alignment = specifiers->alignment;
4110 construct_type_t *construct_type
4111 = parse_inner_declarator(declaration, may_be_abstract);
4112 type_t *const type = specifiers->type;
4113 declaration->type = construct_declarator_type(construct_type, type);
4115 parse_declaration_attributes(declaration);
4117 fix_declaration_type(declaration);
4119 if (construct_type != NULL) {
4120 obstack_free(&temp_obst, construct_type);
4126 static type_t *parse_abstract_declarator(type_t *base_type)
4128 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4130 type_t *result = construct_declarator_type(construct_type, base_type);
4131 if (construct_type != NULL) {
4132 obstack_free(&temp_obst, construct_type);
4138 static declaration_t *append_declaration(declaration_t* const declaration)
4140 if (last_declaration != NULL) {
4141 last_declaration->next = declaration;
4143 scope->declarations = declaration;
4145 last_declaration = declaration;
4150 * Check if the declaration of main is suspicious. main should be a
4151 * function with external linkage, returning int, taking either zero
4152 * arguments, two, or three arguments of appropriate types, ie.
4154 * int main([ int argc, char **argv [, char **env ] ]).
4156 * @param decl the declaration to check
4157 * @param type the function type of the declaration
4159 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4161 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4162 warningf(&decl->source_position,
4163 "'main' is normally a non-static function");
4165 if (skip_typeref(func_type->return_type) != type_int) {
4166 warningf(&decl->source_position,
4167 "return type of 'main' should be 'int', but is '%T'",
4168 func_type->return_type);
4170 const function_parameter_t *parm = func_type->parameters;
4172 type_t *const first_type = parm->type;
4173 if (!types_compatible(skip_typeref(first_type), type_int)) {
4174 warningf(&decl->source_position,
4175 "first argument of 'main' should be 'int', but is '%T'", first_type);
4179 type_t *const second_type = parm->type;
4180 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4181 warningf(&decl->source_position,
4182 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4186 type_t *const third_type = parm->type;
4187 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4188 warningf(&decl->source_position,
4189 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4193 goto warn_arg_count;
4197 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4203 * Check if a symbol is the equal to "main".
4205 static bool is_sym_main(const symbol_t *const sym)
4207 return strcmp(sym->string, "main") == 0;
4210 static declaration_t *internal_record_declaration(
4211 declaration_t *const declaration,
4212 const bool is_definition)
4214 const symbol_t *const symbol = declaration->symbol;
4215 const namespace_t namespc = (namespace_t)declaration->namespc;
4217 assert(symbol != NULL);
4218 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4220 type_t *const orig_type = declaration->type;
4221 type_t *const type = skip_typeref(orig_type);
4222 if (is_type_function(type) &&
4223 type->function.unspecified_parameters &&
4224 warning.strict_prototypes &&
4225 previous_declaration == NULL) {
4226 warningf(&declaration->source_position,
4227 "function declaration '%#T' is not a prototype",
4228 orig_type, declaration->symbol);
4231 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4232 check_type_of_main(declaration, &type->function);
4235 if (warning.nested_externs &&
4236 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4237 scope != global_scope) {
4238 warningf(&declaration->source_position,
4239 "nested extern declaration of '%#T'", declaration->type, symbol);
4242 assert(declaration != previous_declaration);
4243 if (previous_declaration != NULL
4244 && previous_declaration->parent_scope == scope) {
4245 /* can happen for K&R style declarations */
4246 if (previous_declaration->type == NULL) {
4247 previous_declaration->type = declaration->type;
4250 const type_t *prev_type = skip_typeref(previous_declaration->type);
4251 if (!types_compatible(type, prev_type)) {
4252 errorf(&declaration->source_position,
4253 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4254 orig_type, symbol, previous_declaration->type, symbol,
4255 &previous_declaration->source_position);
4257 unsigned old_storage_class = previous_declaration->storage_class;
4258 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4259 errorf(&declaration->source_position,
4260 "redeclaration of enum entry '%Y' (declared %P)",
4261 symbol, &previous_declaration->source_position);
4262 return previous_declaration;
4265 if (warning.redundant_decls &&
4267 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4268 !(previous_declaration->modifiers & DM_USED) &&
4269 !previous_declaration->used) {
4270 warningf(&previous_declaration->source_position,
4271 "unnecessary static forward declaration for '%#T'",
4272 previous_declaration->type, symbol);
4275 unsigned new_storage_class = declaration->storage_class;
4277 if (is_type_incomplete(prev_type)) {
4278 previous_declaration->type = type;
4282 /* pretend no storage class means extern for function
4283 * declarations (except if the previous declaration is neither
4284 * none nor extern) */
4285 if (is_type_function(type)) {
4286 if (prev_type->function.unspecified_parameters) {
4287 previous_declaration->type = type;
4291 switch (old_storage_class) {
4292 case STORAGE_CLASS_NONE:
4293 old_storage_class = STORAGE_CLASS_EXTERN;
4296 case STORAGE_CLASS_EXTERN:
4297 if (is_definition) {
4298 if (warning.missing_prototypes &&
4299 prev_type->function.unspecified_parameters &&
4300 !is_sym_main(symbol)) {
4301 warningf(&declaration->source_position,
4302 "no previous prototype for '%#T'",
4305 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4306 new_storage_class = STORAGE_CLASS_EXTERN;
4315 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4316 new_storage_class == STORAGE_CLASS_EXTERN) {
4317 warn_redundant_declaration:
4318 if (!is_definition &&
4319 warning.redundant_decls &&
4320 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4321 warningf(&declaration->source_position,
4322 "redundant declaration for '%Y' (declared %P)",
4323 symbol, &previous_declaration->source_position);
4325 } else if (current_function == NULL) {
4326 if (old_storage_class != STORAGE_CLASS_STATIC &&
4327 new_storage_class == STORAGE_CLASS_STATIC) {
4328 errorf(&declaration->source_position,
4329 "static declaration of '%Y' follows non-static declaration (declared %P)",
4330 symbol, &previous_declaration->source_position);
4331 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4332 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4333 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4335 goto warn_redundant_declaration;
4337 } else if (old_storage_class == new_storage_class) {
4338 errorf(&declaration->source_position,
4339 "redeclaration of '%Y' (declared %P)",
4340 symbol, &previous_declaration->source_position);
4342 errorf(&declaration->source_position,
4343 "redeclaration of '%Y' with different linkage (declared %P)",
4344 symbol, &previous_declaration->source_position);
4348 previous_declaration->modifiers |= declaration->modifiers;
4349 previous_declaration->is_inline |= declaration->is_inline;
4350 return previous_declaration;
4351 } else if (is_type_function(type)) {
4352 if (is_definition &&
4353 declaration->storage_class != STORAGE_CLASS_STATIC) {
4354 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4355 warningf(&declaration->source_position,
4356 "no previous prototype for '%#T'", orig_type, symbol);
4357 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4358 warningf(&declaration->source_position,
4359 "no previous declaration for '%#T'", orig_type,
4364 if (warning.missing_declarations &&
4365 scope == global_scope && (
4366 declaration->storage_class == STORAGE_CLASS_NONE ||
4367 declaration->storage_class == STORAGE_CLASS_THREAD
4369 warningf(&declaration->source_position,
4370 "no previous declaration for '%#T'", orig_type, symbol);
4374 assert(declaration->parent_scope == NULL);
4375 assert(scope != NULL);
4377 declaration->parent_scope = scope;
4379 environment_push(declaration);
4380 return append_declaration(declaration);
4383 static declaration_t *record_declaration(declaration_t *declaration)
4385 return internal_record_declaration(declaration, false);
4388 static declaration_t *record_definition(declaration_t *declaration)
4390 return internal_record_declaration(declaration, true);
4393 static void parser_error_multiple_definition(declaration_t *declaration,
4394 const source_position_t *source_position)
4396 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4397 declaration->symbol, &declaration->source_position);
4400 static bool is_declaration_specifier(const token_t *token,
4401 bool only_specifiers_qualifiers)
4403 switch(token->type) {
4408 return is_typedef_symbol(token->v.symbol);
4410 case T___extension__:
4412 return !only_specifiers_qualifiers;
4419 static void parse_init_declarator_rest(declaration_t *declaration)
4423 type_t *orig_type = declaration->type;
4424 type_t *type = skip_typeref(orig_type);
4426 if (declaration->init.initializer != NULL) {
4427 parser_error_multiple_definition(declaration, HERE);
4430 bool must_be_constant = false;
4431 if (declaration->storage_class == STORAGE_CLASS_STATIC
4432 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4433 || declaration->parent_scope == global_scope) {
4434 must_be_constant = true;
4437 parse_initializer_env_t env;
4438 env.type = orig_type;
4439 env.must_be_constant = must_be_constant;
4440 env.declaration = current_init_decl = declaration;
4442 initializer_t *initializer = parse_initializer(&env);
4443 current_init_decl = NULL;
4445 if (env.type != orig_type) {
4446 orig_type = env.type;
4447 type = skip_typeref(orig_type);
4448 declaration->type = env.type;
4451 if (is_type_function(type)) {
4452 errorf(&declaration->source_position,
4453 "initializers not allowed for function types at declarator '%Y' (type '%T')",
4454 declaration->symbol, orig_type);
4456 declaration->init.initializer = initializer;
4460 /* parse rest of a declaration without any declarator */
4461 static void parse_anonymous_declaration_rest(
4462 const declaration_specifiers_t *specifiers)
4466 declaration_t *const declaration = allocate_declaration_zero();
4467 declaration->type = specifiers->type;
4468 declaration->declared_storage_class = specifiers->declared_storage_class;
4469 declaration->source_position = specifiers->source_position;
4470 declaration->modifiers = specifiers->modifiers;
4472 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4473 warningf(&declaration->source_position,
4474 "useless storage class in empty declaration");
4476 declaration->storage_class = STORAGE_CLASS_NONE;
4478 type_t *type = declaration->type;
4479 switch (type->kind) {
4480 case TYPE_COMPOUND_STRUCT:
4481 case TYPE_COMPOUND_UNION: {
4482 if (type->compound.declaration->symbol == NULL) {
4483 warningf(&declaration->source_position,
4484 "unnamed struct/union that defines no instances");
4493 warningf(&declaration->source_position, "empty declaration");
4497 append_declaration(declaration);
4500 static void parse_declaration_rest(declaration_t *ndeclaration,
4501 const declaration_specifiers_t *specifiers,
4502 parsed_declaration_func finished_declaration)
4504 add_anchor_token(';');
4505 add_anchor_token('=');
4506 add_anchor_token(',');
4508 declaration_t *declaration = finished_declaration(ndeclaration);
4510 type_t *orig_type = declaration->type;
4511 type_t *type = skip_typeref(orig_type);
4513 if (type->kind != TYPE_FUNCTION &&
4514 declaration->is_inline &&
4515 is_type_valid(type)) {
4516 warningf(&declaration->source_position,
4517 "variable '%Y' declared 'inline'\n", declaration->symbol);
4520 if (token.type == '=') {
4521 parse_init_declarator_rest(declaration);
4524 if (token.type != ',')
4528 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4533 rem_anchor_token(';');
4534 rem_anchor_token('=');
4535 rem_anchor_token(',');
4538 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4540 symbol_t *symbol = declaration->symbol;
4541 if (symbol == NULL) {
4542 errorf(HERE, "anonymous declaration not valid as function parameter");
4545 namespace_t namespc = (namespace_t) declaration->namespc;
4546 if (namespc != NAMESPACE_NORMAL) {
4547 return record_declaration(declaration);
4550 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4551 if (previous_declaration == NULL ||
4552 previous_declaration->parent_scope != scope) {
4553 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4558 if (previous_declaration->type == NULL) {
4559 previous_declaration->type = declaration->type;
4560 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4561 previous_declaration->storage_class = declaration->storage_class;
4562 previous_declaration->parent_scope = scope;
4563 return previous_declaration;
4565 return record_declaration(declaration);
4569 static void parse_declaration(parsed_declaration_func finished_declaration)
4571 declaration_specifiers_t specifiers;
4572 memset(&specifiers, 0, sizeof(specifiers));
4573 parse_declaration_specifiers(&specifiers);
4575 if (token.type == ';') {
4576 parse_anonymous_declaration_rest(&specifiers);
4578 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4579 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4583 static type_t *get_default_promoted_type(type_t *orig_type)
4585 type_t *result = orig_type;
4587 type_t *type = skip_typeref(orig_type);
4588 if (is_type_integer(type)) {
4589 result = promote_integer(type);
4590 } else if (type == type_float) {
4591 result = type_double;
4597 static void parse_kr_declaration_list(declaration_t *declaration)
4599 type_t *type = skip_typeref(declaration->type);
4600 if (!is_type_function(type))
4603 if (!type->function.kr_style_parameters)
4606 /* push function parameters */
4607 int top = environment_top();
4608 scope_t *last_scope = scope;
4609 set_scope(&declaration->scope);
4611 declaration_t *parameter = declaration->scope.declarations;
4612 for ( ; parameter != NULL; parameter = parameter->next) {
4613 assert(parameter->parent_scope == NULL);
4614 parameter->parent_scope = scope;
4615 environment_push(parameter);
4618 /* parse declaration list */
4619 while (is_declaration_specifier(&token, false)) {
4620 parse_declaration(finished_kr_declaration);
4623 /* pop function parameters */
4624 assert(scope == &declaration->scope);
4625 set_scope(last_scope);
4626 environment_pop_to(top);
4628 /* update function type */
4629 type_t *new_type = duplicate_type(type);
4631 function_parameter_t *parameters = NULL;
4632 function_parameter_t *last_parameter = NULL;
4634 declaration_t *parameter_declaration = declaration->scope.declarations;
4635 for( ; parameter_declaration != NULL;
4636 parameter_declaration = parameter_declaration->next) {
4637 type_t *parameter_type = parameter_declaration->type;
4638 if (parameter_type == NULL) {
4640 errorf(HERE, "no type specified for function parameter '%Y'",
4641 parameter_declaration->symbol);
4643 if (warning.implicit_int) {
4644 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4645 parameter_declaration->symbol);
4647 parameter_type = type_int;
4648 parameter_declaration->type = parameter_type;
4652 semantic_parameter(parameter_declaration);
4653 parameter_type = parameter_declaration->type;
4656 * we need the default promoted types for the function type
4658 parameter_type = get_default_promoted_type(parameter_type);
4660 function_parameter_t *function_parameter
4661 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4662 memset(function_parameter, 0, sizeof(function_parameter[0]));
4664 function_parameter->type = parameter_type;
4665 if (last_parameter != NULL) {
4666 last_parameter->next = function_parameter;
4668 parameters = function_parameter;
4670 last_parameter = function_parameter;
4673 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4675 new_type->function.parameters = parameters;
4676 new_type->function.unspecified_parameters = true;
4678 type = typehash_insert(new_type);
4679 if (type != new_type) {
4680 obstack_free(type_obst, new_type);
4683 declaration->type = type;
4686 static bool first_err = true;
4689 * When called with first_err set, prints the name of the current function,
4692 static void print_in_function(void)
4696 diagnosticf("%s: In function '%Y':\n",
4697 current_function->source_position.input_name,
4698 current_function->symbol);
4703 * Check if all labels are defined in the current function.
4704 * Check if all labels are used in the current function.
4706 static void check_labels(void)
4708 for (const goto_statement_t *goto_statement = goto_first;
4709 goto_statement != NULL;
4710 goto_statement = goto_statement->next) {
4711 declaration_t *label = goto_statement->label;
4714 if (label->source_position.input_name == NULL) {
4715 print_in_function();
4716 errorf(&goto_statement->base.source_position,
4717 "label '%Y' used but not defined", label->symbol);
4720 goto_first = goto_last = NULL;
4722 if (warning.unused_label) {
4723 for (const label_statement_t *label_statement = label_first;
4724 label_statement != NULL;
4725 label_statement = label_statement->next) {
4726 const declaration_t *label = label_statement->label;
4728 if (! label->used) {
4729 print_in_function();
4730 warningf(&label_statement->base.source_position,
4731 "label '%Y' defined but not used", label->symbol);
4735 label_first = label_last = NULL;
4739 * Check declarations of current_function for unused entities.
4741 static void check_declarations(void)
4743 if (warning.unused_parameter) {
4744 const scope_t *scope = ¤t_function->scope;
4746 if (is_sym_main(current_function->symbol)) {
4747 /* do not issue unused warnings for main */
4750 const declaration_t *parameter = scope->declarations;
4751 for (; parameter != NULL; parameter = parameter->next) {
4752 if (! parameter->used) {
4753 print_in_function();
4754 warningf(¶meter->source_position,
4755 "unused parameter '%Y'", parameter->symbol);
4759 if (warning.unused_variable) {
4763 static int determine_truth(expression_t const* const cond)
4766 !is_constant_expression(cond) ? 0 :
4767 fold_constant(cond) != 0 ? 1 :
4771 static bool noreturn_candidate;
4773 static void check_reachable(statement_t *const stmt)
4775 if (stmt->base.reachable)
4777 if (stmt->kind != STATEMENT_DO_WHILE)
4778 stmt->base.reachable = true;
4780 statement_t *last = stmt;
4782 switch (stmt->kind) {
4783 case STATEMENT_INVALID:
4784 case STATEMENT_EMPTY:
4785 case STATEMENT_DECLARATION:
4787 next = stmt->base.next;
4790 case STATEMENT_COMPOUND:
4791 next = stmt->compound.statements;
4794 case STATEMENT_RETURN:
4795 noreturn_candidate = false;
4798 case STATEMENT_IF: {
4799 if_statement_t const* const ifs = &stmt->ifs;
4800 int const val = determine_truth(ifs->condition);
4803 check_reachable(ifs->true_statement);
4808 if (ifs->false_statement != NULL) {
4809 check_reachable(ifs->false_statement);
4813 next = stmt->base.next;
4817 case STATEMENT_SWITCH: {
4818 switch_statement_t const *const switchs = &stmt->switchs;
4819 expression_t const *const expr = switchs->expression;
4821 if (is_constant_expression(expr)) {
4822 long const val = fold_constant(expr);
4823 case_label_statement_t * defaults = NULL;
4824 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4825 if (i->expression == NULL) {
4830 if (i->first_case <= val && val <= i->last_case) {
4831 check_reachable((statement_t*)i);
4836 if (defaults != NULL) {
4837 check_reachable((statement_t*)defaults);
4841 bool has_default = false;
4842 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4843 if (i->expression == NULL)
4846 check_reachable((statement_t*)i);
4853 next = stmt->base.next;
4857 case STATEMENT_EXPRESSION: {
4858 /* Check for noreturn function call */
4859 expression_t const *const expr = stmt->expression.expression;
4860 if (expr->kind == EXPR_CALL) {
4861 expression_t const *const func = expr->call.function;
4862 if (func->kind == EXPR_REFERENCE) {
4863 declaration_t const *const decl = func->reference.declaration;
4864 if (decl != NULL && decl->modifiers & DM_NORETURN) {
4870 next = stmt->base.next;
4874 case STATEMENT_CONTINUE: {
4875 statement_t *parent = stmt;
4877 parent = parent->base.parent;
4878 if (parent == NULL) /* continue not within loop */
4882 switch (parent->kind) {
4883 case STATEMENT_WHILE: goto continue_while;
4884 case STATEMENT_DO_WHILE: goto continue_do_while;
4885 case STATEMENT_FOR: goto continue_for;
4892 case STATEMENT_BREAK: {
4893 statement_t *parent = stmt;
4895 parent = parent->base.parent;
4896 if (parent == NULL) /* break not within loop/switch */
4899 switch (parent->kind) {
4900 case STATEMENT_SWITCH:
4901 case STATEMENT_WHILE:
4902 case STATEMENT_DO_WHILE:
4905 next = parent->base.next;
4906 goto found_break_parent;
4915 case STATEMENT_GOTO:
4916 next = stmt->gotos.label->init.statement;
4917 if (next == NULL) /* missing label */
4921 case STATEMENT_LABEL:
4922 next = stmt->label.statement;
4925 case STATEMENT_CASE_LABEL:
4926 next = stmt->case_label.statement;
4929 case STATEMENT_WHILE: {
4930 while_statement_t const *const whiles = &stmt->whiles;
4931 int const val = determine_truth(whiles->condition);
4934 check_reachable(whiles->body);
4939 next = stmt->base.next;
4943 case STATEMENT_DO_WHILE:
4944 next = stmt->do_while.body;
4947 case STATEMENT_FOR: {
4948 for_statement_t *const fors = &stmt->fors;
4950 if (fors->condition_reachable)
4952 fors->condition_reachable = true;
4954 expression_t const *const cond = fors->condition;
4956 cond == NULL ? 1 : determine_truth(cond);
4959 check_reachable(fors->body);
4964 next = stmt->base.next;
4968 case STATEMENT_MS_TRY: {
4969 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4970 check_reachable(ms_try->try_statement);
4971 next = ms_try->final_statement;
4975 case STATEMENT_LEAVE: {
4976 statement_t *parent = stmt;
4978 parent = parent->base.parent;
4979 if (parent == NULL) /* __leave not within __try */
4982 if (parent->kind == STATEMENT_MS_TRY) {
4984 next = parent->ms_try.final_statement;
4992 while (next == NULL) {
4993 next = last->base.parent;
4995 noreturn_candidate = false;
4997 type_t *const type = current_function->type;
4998 assert(is_type_function(type));
4999 type_t *const ret = skip_typeref(type->function.return_type);
5000 if (warning.return_type &&
5001 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5002 is_type_valid(ret) &&
5003 !is_sym_main(current_function->symbol)) {
5004 warningf(&stmt->base.source_position,
5005 "control reaches end of non-void function");
5010 switch (next->kind) {
5011 case STATEMENT_INVALID:
5012 case STATEMENT_EMPTY:
5013 case STATEMENT_DECLARATION:
5014 case STATEMENT_EXPRESSION:
5016 case STATEMENT_RETURN:
5017 case STATEMENT_CONTINUE:
5018 case STATEMENT_BREAK:
5019 case STATEMENT_GOTO:
5020 case STATEMENT_LEAVE:
5021 panic("invalid control flow in function");
5023 case STATEMENT_COMPOUND:
5025 case STATEMENT_SWITCH:
5026 case STATEMENT_LABEL:
5027 case STATEMENT_CASE_LABEL:
5029 next = next->base.next;
5032 case STATEMENT_WHILE: {
5034 if (next->base.reachable)
5036 next->base.reachable = true;
5038 while_statement_t const *const whiles = &next->whiles;
5039 int const val = determine_truth(whiles->condition);
5042 check_reachable(whiles->body);
5048 next = next->base.next;
5052 case STATEMENT_DO_WHILE: {
5054 if (next->base.reachable)
5056 next->base.reachable = true;
5058 do_while_statement_t const *const dw = &next->do_while;
5059 int const val = determine_truth(dw->condition);
5062 check_reachable(dw->body);
5068 next = next->base.next;
5072 case STATEMENT_FOR: {
5074 for_statement_t *const fors = &next->fors;
5076 fors->step_reachable = true;
5078 if (fors->condition_reachable)
5080 fors->condition_reachable = true;
5082 expression_t const *const cond = fors->condition;
5084 cond == NULL ? 1 : determine_truth(cond);
5087 check_reachable(fors->body);
5093 next = next->base.next;
5097 case STATEMENT_MS_TRY:
5099 next = next->ms_try.final_statement;
5105 next = stmt->base.parent;
5107 warningf(&stmt->base.source_position,
5108 "control reaches end of non-void function");
5112 check_reachable(next);
5115 static void check_unreachable(statement_t const* const stmt)
5117 if (!stmt->base.reachable &&
5118 stmt->kind != STATEMENT_DO_WHILE &&
5119 stmt->kind != STATEMENT_FOR &&
5120 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5121 warningf(&stmt->base.source_position, "statement is unreachable");
5124 switch (stmt->kind) {
5125 case STATEMENT_INVALID:
5126 case STATEMENT_EMPTY:
5127 case STATEMENT_RETURN:
5128 case STATEMENT_DECLARATION:
5129 case STATEMENT_EXPRESSION:
5130 case STATEMENT_CONTINUE:
5131 case STATEMENT_BREAK:
5132 case STATEMENT_GOTO:
5134 case STATEMENT_LEAVE:
5137 case STATEMENT_COMPOUND:
5138 if (stmt->compound.statements)
5139 check_unreachable(stmt->compound.statements);
5143 check_unreachable(stmt->ifs.true_statement);
5144 if (stmt->ifs.false_statement != NULL)
5145 check_unreachable(stmt->ifs.false_statement);
5148 case STATEMENT_SWITCH:
5149 check_unreachable(stmt->switchs.body);
5152 case STATEMENT_LABEL:
5153 check_unreachable(stmt->label.statement);
5156 case STATEMENT_CASE_LABEL:
5157 check_unreachable(stmt->case_label.statement);
5160 case STATEMENT_WHILE:
5161 check_unreachable(stmt->whiles.body);
5164 case STATEMENT_DO_WHILE:
5165 check_unreachable(stmt->do_while.body);
5166 if (!stmt->base.reachable) {
5167 expression_t const *const cond = stmt->do_while.condition;
5168 if (determine_truth(cond) >= 0) {
5169 warningf(&cond->base.source_position,
5170 "condition of do-while-loop is unreachable");
5175 case STATEMENT_FOR: {
5176 for_statement_t const* const fors = &stmt->fors;
5178 // if init and step are unreachable, cond is unreachable, too
5179 if (!stmt->base.reachable && !fors->step_reachable) {
5180 warningf(&stmt->base.source_position, "statement is unreachable");
5182 if (!stmt->base.reachable && fors->initialisation != NULL) {
5183 warningf(&fors->initialisation->base.source_position,
5184 "initialisation of for-statement is unreachable");
5187 if (!fors->condition_reachable && fors->condition != NULL) {
5188 warningf(&fors->condition->base.source_position,
5189 "condition of for-statement is unreachable");
5192 if (!fors->step_reachable && fors->step != NULL) {
5193 warningf(&fors->step->base.source_position,
5194 "step of for-statement is unreachable");
5198 check_unreachable(fors->body);
5202 case STATEMENT_MS_TRY: {
5203 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5204 check_unreachable(ms_try->try_statement);
5205 check_unreachable(ms_try->final_statement);
5209 if (stmt->base.next)
5210 check_unreachable(stmt->base.next);
5213 static void parse_external_declaration(void)
5215 /* function-definitions and declarations both start with declaration
5217 declaration_specifiers_t specifiers;
5218 memset(&specifiers, 0, sizeof(specifiers));
5220 add_anchor_token(';');
5221 parse_declaration_specifiers(&specifiers);
5222 rem_anchor_token(';');
5224 /* must be a declaration */
5225 if (token.type == ';') {
5226 parse_anonymous_declaration_rest(&specifiers);
5230 add_anchor_token(',');
5231 add_anchor_token('=');
5232 rem_anchor_token(';');
5234 /* declarator is common to both function-definitions and declarations */
5235 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5237 rem_anchor_token(',');
5238 rem_anchor_token('=');
5239 rem_anchor_token(';');
5241 /* must be a declaration */
5242 switch (token.type) {
5245 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5249 parse_declaration_rest(ndeclaration, &specifiers, record_definition);
5253 /* must be a function definition */
5254 parse_kr_declaration_list(ndeclaration);
5256 if (token.type != '{') {
5257 parse_error_expected("while parsing function definition", '{', NULL);
5258 eat_until_matching_token(';');
5262 type_t *type = ndeclaration->type;
5264 /* note that we don't skip typerefs: the standard doesn't allow them here
5265 * (so we can't use is_type_function here) */
5266 if (type->kind != TYPE_FUNCTION) {
5267 if (is_type_valid(type)) {
5268 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5269 type, ndeclaration->symbol);
5275 if (warning.aggregate_return &&
5276 is_type_compound(skip_typeref(type->function.return_type))) {
5277 warningf(HERE, "function '%Y' returns an aggregate",
5278 ndeclaration->symbol);
5280 if (warning.traditional && !type->function.unspecified_parameters) {
5281 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5282 ndeclaration->symbol);
5284 if (warning.old_style_definition && type->function.unspecified_parameters) {
5285 warningf(HERE, "old-style function definition '%Y'",
5286 ndeclaration->symbol);
5289 /* § 6.7.5.3 (14) a function definition with () means no
5290 * parameters (and not unspecified parameters) */
5291 if (type->function.unspecified_parameters
5292 && type->function.parameters == NULL
5293 && !type->function.kr_style_parameters) {
5294 type_t *duplicate = duplicate_type(type);
5295 duplicate->function.unspecified_parameters = false;
5297 type = typehash_insert(duplicate);
5298 if (type != duplicate) {
5299 obstack_free(type_obst, duplicate);
5301 ndeclaration->type = type;
5304 declaration_t *const declaration = record_definition(ndeclaration);
5305 if (ndeclaration != declaration) {
5306 declaration->scope = ndeclaration->scope;
5308 type = skip_typeref(declaration->type);
5310 /* push function parameters and switch scope */
5311 int top = environment_top();
5312 scope_t *last_scope = scope;
5313 set_scope(&declaration->scope);
5315 declaration_t *parameter = declaration->scope.declarations;
5316 for( ; parameter != NULL; parameter = parameter->next) {
5317 if (parameter->parent_scope == &ndeclaration->scope) {
5318 parameter->parent_scope = scope;
5320 assert(parameter->parent_scope == NULL
5321 || parameter->parent_scope == scope);
5322 parameter->parent_scope = scope;
5323 if (parameter->symbol == NULL) {
5324 errorf(¶meter->source_position, "parameter name omitted");
5327 environment_push(parameter);
5330 if (declaration->init.statement != NULL) {
5331 parser_error_multiple_definition(declaration, HERE);
5334 /* parse function body */
5335 int label_stack_top = label_top();
5336 declaration_t *old_current_function = current_function;
5337 current_function = declaration;
5338 current_parent = NULL;
5340 statement_t *const body = parse_compound_statement(false);
5341 declaration->init.statement = body;
5344 check_declarations();
5345 if (warning.return_type ||
5346 warning.unreachable_code ||
5347 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5348 noreturn_candidate = true;
5349 check_reachable(body);
5350 if (warning.unreachable_code)
5351 check_unreachable(body);
5352 if (warning.missing_noreturn &&
5353 noreturn_candidate &&
5354 !(declaration->modifiers & DM_NORETURN)) {
5355 warningf(&body->base.source_position,
5356 "function '%#T' is candidate for attribute 'noreturn'",
5357 type, declaration->symbol);
5361 assert(current_parent == NULL);
5362 assert(current_function == declaration);
5363 current_function = old_current_function;
5364 label_pop_to(label_stack_top);
5367 assert(scope == &declaration->scope);
5368 set_scope(last_scope);
5369 environment_pop_to(top);
5372 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5373 source_position_t *source_position)
5375 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5377 type->bitfield.base_type = base_type;
5378 type->bitfield.size = size;
5383 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5386 declaration_t *iter = compound_declaration->scope.declarations;
5387 for( ; iter != NULL; iter = iter->next) {
5388 if (iter->namespc != NAMESPACE_NORMAL)
5391 if (iter->symbol == NULL) {
5392 type_t *type = skip_typeref(iter->type);
5393 if (is_type_compound(type)) {
5394 declaration_t *result
5395 = find_compound_entry(type->compound.declaration, symbol);
5402 if (iter->symbol == symbol) {
5410 static void parse_compound_declarators(declaration_t *struct_declaration,
5411 const declaration_specifiers_t *specifiers)
5413 declaration_t *last_declaration = struct_declaration->scope.declarations;
5414 if (last_declaration != NULL) {
5415 while(last_declaration->next != NULL) {
5416 last_declaration = last_declaration->next;
5421 declaration_t *declaration;
5423 if (token.type == ':') {
5424 source_position_t source_position = *HERE;
5427 type_t *base_type = specifiers->type;
5428 expression_t *size = parse_constant_expression();
5430 if (!is_type_integer(skip_typeref(base_type))) {
5431 errorf(HERE, "bitfield base type '%T' is not an integer type",
5435 type_t *type = make_bitfield_type(base_type, size, &source_position);
5437 declaration = allocate_declaration_zero();
5438 declaration->namespc = NAMESPACE_NORMAL;
5439 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5440 declaration->storage_class = STORAGE_CLASS_NONE;
5441 declaration->source_position = source_position;
5442 declaration->modifiers = specifiers->modifiers;
5443 declaration->type = type;
5445 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5447 type_t *orig_type = declaration->type;
5448 type_t *type = skip_typeref(orig_type);
5450 if (token.type == ':') {
5451 source_position_t source_position = *HERE;
5453 expression_t *size = parse_constant_expression();
5455 if (!is_type_integer(type)) {
5456 errorf(HERE, "bitfield base type '%T' is not an integer type",
5460 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5461 declaration->type = bitfield_type;
5463 /* TODO we ignore arrays for now... what is missing is a check
5464 * that they're at the end of the struct */
5465 if (is_type_incomplete(type) && !is_type_array(type)) {
5467 "compound member '%Y' has incomplete type '%T'",
5468 declaration->symbol, orig_type);
5469 } else if (is_type_function(type)) {
5470 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5471 declaration->symbol, orig_type);
5476 /* make sure we don't define a symbol multiple times */
5477 symbol_t *symbol = declaration->symbol;
5478 if (symbol != NULL) {
5479 declaration_t *prev_decl
5480 = find_compound_entry(struct_declaration, symbol);
5482 if (prev_decl != NULL) {
5483 assert(prev_decl->symbol == symbol);
5484 errorf(&declaration->source_position,
5485 "multiple declarations of symbol '%Y' (declared %P)",
5486 symbol, &prev_decl->source_position);
5490 /* append declaration */
5491 if (last_declaration != NULL) {
5492 last_declaration->next = declaration;
5494 struct_declaration->scope.declarations = declaration;
5496 last_declaration = declaration;
5498 if (token.type != ',')
5508 static void parse_compound_type_entries(declaration_t *compound_declaration)
5511 add_anchor_token('}');
5513 while(token.type != '}' && token.type != T_EOF) {
5514 declaration_specifiers_t specifiers;
5515 memset(&specifiers, 0, sizeof(specifiers));
5516 parse_declaration_specifiers(&specifiers);
5518 parse_compound_declarators(compound_declaration, &specifiers);
5520 rem_anchor_token('}');
5522 if (token.type == T_EOF) {
5523 errorf(HERE, "EOF while parsing struct");
5528 static type_t *parse_typename(void)
5530 declaration_specifiers_t specifiers;
5531 memset(&specifiers, 0, sizeof(specifiers));
5532 parse_declaration_specifiers(&specifiers);
5533 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5534 /* TODO: improve error message, user does probably not know what a
5535 * storage class is...
5537 errorf(HERE, "typename may not have a storage class");
5540 type_t *result = parse_abstract_declarator(specifiers.type);
5548 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5549 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5550 expression_t *left);
5552 typedef struct expression_parser_function_t expression_parser_function_t;
5553 struct expression_parser_function_t {
5554 unsigned precedence;
5555 parse_expression_function parser;
5556 unsigned infix_precedence;
5557 parse_expression_infix_function infix_parser;
5560 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5563 * Prints an error message if an expression was expected but not read
5565 static expression_t *expected_expression_error(void)
5567 /* skip the error message if the error token was read */
5568 if (token.type != T_ERROR) {
5569 errorf(HERE, "expected expression, got token '%K'", &token);
5573 return create_invalid_expression();
5577 * Parse a string constant.
5579 static expression_t *parse_string_const(void)
5582 if (token.type == T_STRING_LITERAL) {
5583 string_t res = token.v.string;
5585 while (token.type == T_STRING_LITERAL) {
5586 res = concat_strings(&res, &token.v.string);
5589 if (token.type != T_WIDE_STRING_LITERAL) {
5590 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5591 /* note: that we use type_char_ptr here, which is already the
5592 * automatic converted type. revert_automatic_type_conversion
5593 * will construct the array type */
5594 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5595 cnst->string.value = res;
5599 wres = concat_string_wide_string(&res, &token.v.wide_string);
5601 wres = token.v.wide_string;
5606 switch (token.type) {
5607 case T_WIDE_STRING_LITERAL:
5608 wres = concat_wide_strings(&wres, &token.v.wide_string);
5611 case T_STRING_LITERAL:
5612 wres = concat_wide_string_string(&wres, &token.v.string);
5616 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5617 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5618 cnst->wide_string.value = wres;
5627 * Parse an integer constant.
5629 static expression_t *parse_int_const(void)
5631 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5632 cnst->base.source_position = *HERE;
5633 cnst->base.type = token.datatype;
5634 cnst->conste.v.int_value = token.v.intvalue;
5642 * Parse a character constant.
5644 static expression_t *parse_character_constant(void)
5646 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5648 cnst->base.source_position = *HERE;
5649 cnst->base.type = token.datatype;
5650 cnst->conste.v.character = token.v.string;
5652 if (cnst->conste.v.character.size != 1) {
5653 if (warning.multichar && (c_mode & _GNUC)) {
5655 warningf(HERE, "multi-character character constant");
5657 errorf(HERE, "more than 1 characters in character constant");
5666 * Parse a wide character constant.
5668 static expression_t *parse_wide_character_constant(void)
5670 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5672 cnst->base.source_position = *HERE;
5673 cnst->base.type = token.datatype;
5674 cnst->conste.v.wide_character = token.v.wide_string;
5676 if (cnst->conste.v.wide_character.size != 1) {
5677 if (warning.multichar && (c_mode & _GNUC)) {
5679 warningf(HERE, "multi-character character constant");
5681 errorf(HERE, "more than 1 characters in character constant");
5690 * Parse a float constant.
5692 static expression_t *parse_float_const(void)
5694 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5695 cnst->base.type = token.datatype;
5696 cnst->conste.v.float_value = token.v.floatvalue;
5703 static declaration_t *create_implicit_function(symbol_t *symbol,
5704 const source_position_t *source_position)
5706 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5707 ntype->function.return_type = type_int;
5708 ntype->function.unspecified_parameters = true;
5710 type_t *type = typehash_insert(ntype);
5711 if (type != ntype) {
5715 declaration_t *const declaration = allocate_declaration_zero();
5716 declaration->storage_class = STORAGE_CLASS_EXTERN;
5717 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5718 declaration->type = type;
5719 declaration->symbol = symbol;
5720 declaration->source_position = *source_position;
5721 declaration->implicit = true;
5723 bool strict_prototypes_old = warning.strict_prototypes;
5724 warning.strict_prototypes = false;
5725 record_declaration(declaration);
5726 warning.strict_prototypes = strict_prototypes_old;
5732 * Creates a return_type (func)(argument_type) function type if not
5735 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5736 type_t *argument_type2)
5738 function_parameter_t *parameter2
5739 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5740 memset(parameter2, 0, sizeof(parameter2[0]));
5741 parameter2->type = argument_type2;
5743 function_parameter_t *parameter1
5744 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5745 memset(parameter1, 0, sizeof(parameter1[0]));
5746 parameter1->type = argument_type1;
5747 parameter1->next = parameter2;
5749 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5750 type->function.return_type = return_type;
5751 type->function.parameters = parameter1;
5753 type_t *result = typehash_insert(type);
5754 if (result != type) {
5762 * Creates a return_type (func)(argument_type) function type if not
5765 * @param return_type the return type
5766 * @param argument_type the argument type
5768 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5770 function_parameter_t *parameter
5771 = obstack_alloc(type_obst, sizeof(parameter[0]));
5772 memset(parameter, 0, sizeof(parameter[0]));
5773 parameter->type = argument_type;
5775 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5776 type->function.return_type = return_type;
5777 type->function.parameters = parameter;
5779 type_t *result = typehash_insert(type);
5780 if (result != type) {
5787 static type_t *make_function_0_type(type_t *return_type)
5789 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5790 type->function.return_type = return_type;
5791 type->function.parameters = NULL;
5793 type_t *result = typehash_insert(type);
5794 if (result != type) {
5802 * Creates a function type for some function like builtins.
5804 * @param symbol the symbol describing the builtin
5806 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5808 switch(symbol->ID) {
5809 case T___builtin_alloca:
5810 return make_function_1_type(type_void_ptr, type_size_t);
5811 case T___builtin_huge_val:
5812 return make_function_0_type(type_double);
5813 case T___builtin_nan:
5814 return make_function_1_type(type_double, type_char_ptr);
5815 case T___builtin_nanf:
5816 return make_function_1_type(type_float, type_char_ptr);
5817 case T___builtin_nand:
5818 return make_function_1_type(type_long_double, type_char_ptr);
5819 case T___builtin_va_end:
5820 return make_function_1_type(type_void, type_valist);
5821 case T___builtin_expect:
5822 return make_function_2_type(type_long, type_long, type_long);
5824 internal_errorf(HERE, "not implemented builtin symbol found");
5829 * Performs automatic type cast as described in § 6.3.2.1.
5831 * @param orig_type the original type
5833 static type_t *automatic_type_conversion(type_t *orig_type)
5835 type_t *type = skip_typeref(orig_type);
5836 if (is_type_array(type)) {
5837 array_type_t *array_type = &type->array;
5838 type_t *element_type = array_type->element_type;
5839 unsigned qualifiers = array_type->base.qualifiers;
5841 return make_pointer_type(element_type, qualifiers);
5844 if (is_type_function(type)) {
5845 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5852 * reverts the automatic casts of array to pointer types and function
5853 * to function-pointer types as defined § 6.3.2.1
5855 type_t *revert_automatic_type_conversion(const expression_t *expression)
5857 switch (expression->kind) {
5858 case EXPR_REFERENCE: return expression->reference.declaration->type;
5859 case EXPR_SELECT: return expression->select.compound_entry->type;
5861 case EXPR_UNARY_DEREFERENCE: {
5862 const expression_t *const value = expression->unary.value;
5863 type_t *const type = skip_typeref(value->base.type);
5864 assert(is_type_pointer(type));
5865 return type->pointer.points_to;
5868 case EXPR_BUILTIN_SYMBOL:
5869 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5871 case EXPR_ARRAY_ACCESS: {
5872 const expression_t *array_ref = expression->array_access.array_ref;
5873 type_t *type_left = skip_typeref(array_ref->base.type);
5874 if (!is_type_valid(type_left))
5876 assert(is_type_pointer(type_left));
5877 return type_left->pointer.points_to;
5880 case EXPR_STRING_LITERAL: {
5881 size_t size = expression->string.value.size;
5882 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5885 case EXPR_WIDE_STRING_LITERAL: {
5886 size_t size = expression->wide_string.value.size;
5887 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5890 case EXPR_COMPOUND_LITERAL:
5891 return expression->compound_literal.type;
5896 return expression->base.type;
5899 static expression_t *parse_reference(void)
5901 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5903 reference_expression_t *ref = &expression->reference;
5904 symbol_t *const symbol = token.v.symbol;
5906 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5908 source_position_t source_position = token.source_position;
5911 if (declaration == NULL) {
5912 if (token.type == '(') {
5913 /* an implicitly declared function */
5915 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5916 } else if (warning.implicit_function_declaration) {
5917 warningf(HERE, "implicit declaration of function '%Y'",
5921 declaration = create_implicit_function(symbol,
5924 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5925 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
5929 type_t *type = declaration->type;
5931 /* we always do the auto-type conversions; the & and sizeof parser contains
5932 * code to revert this! */
5933 type = automatic_type_conversion(type);
5935 ref->declaration = declaration;
5936 ref->base.type = type;
5938 /* this declaration is used */
5939 declaration->used = true;
5941 /* check for deprecated functions */
5942 if (warning.deprecated_declarations &&
5943 declaration->modifiers & DM_DEPRECATED) {
5944 char const *const prefix = is_type_function(declaration->type) ?
5945 "function" : "variable";
5947 if (declaration->deprecated_string != NULL) {
5948 warningf(&source_position,
5949 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
5950 declaration->symbol, &declaration->source_position,
5951 declaration->deprecated_string);
5953 warningf(&source_position,
5954 "%s '%Y' is deprecated (declared %P)", prefix,
5955 declaration->symbol, &declaration->source_position);
5958 if (warning.init_self && declaration == current_init_decl) {
5959 current_init_decl = NULL;
5960 warningf(&source_position,
5961 "variable '%#T' is initialized by itself",
5962 declaration->type, declaration->symbol);
5968 static bool semantic_cast(expression_t *cast)
5970 expression_t *expression = cast->unary.value;
5971 type_t *orig_dest_type = cast->base.type;
5972 type_t *orig_type_right = expression->base.type;
5973 type_t const *dst_type = skip_typeref(orig_dest_type);
5974 type_t const *src_type = skip_typeref(orig_type_right);
5975 source_position_t const *pos = &cast->base.source_position;
5977 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
5978 if (dst_type == type_void)
5981 /* only integer and pointer can be casted to pointer */
5982 if (is_type_pointer(dst_type) &&
5983 !is_type_pointer(src_type) &&
5984 !is_type_integer(src_type) &&
5985 is_type_valid(src_type)) {
5986 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
5990 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
5991 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
5995 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
5996 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6000 if (warning.cast_qual &&
6001 is_type_pointer(src_type) &&
6002 is_type_pointer(dst_type)) {
6003 type_t *src = skip_typeref(src_type->pointer.points_to);
6004 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6005 unsigned missing_qualifiers =
6006 src->base.qualifiers & ~dst->base.qualifiers;
6007 if (missing_qualifiers != 0) {
6009 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6010 missing_qualifiers, orig_type_right);
6016 static expression_t *parse_compound_literal(type_t *type)
6018 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6020 parse_initializer_env_t env;
6022 env.declaration = NULL;
6023 env.must_be_constant = false;
6024 initializer_t *initializer = parse_initializer(&env);
6027 expression->compound_literal.initializer = initializer;
6028 expression->compound_literal.type = type;
6029 expression->base.type = automatic_type_conversion(type);
6035 * Parse a cast expression.
6037 static expression_t *parse_cast(void)
6039 source_position_t source_position = token.source_position;
6041 type_t *type = parse_typename();
6043 /* matching add_anchor_token() is at call site */
6044 rem_anchor_token(')');
6047 if (token.type == '{') {
6048 return parse_compound_literal(type);
6051 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6052 cast->base.source_position = source_position;
6054 expression_t *value = parse_sub_expression(20);
6055 cast->base.type = type;
6056 cast->unary.value = value;
6058 if (! semantic_cast(cast)) {
6059 /* TODO: record the error in the AST. else it is impossible to detect it */
6064 return create_invalid_expression();
6068 * Parse a statement expression.
6070 static expression_t *parse_statement_expression(void)
6072 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6074 statement_t *statement = parse_compound_statement(true);
6075 expression->statement.statement = statement;
6076 expression->base.source_position = statement->base.source_position;
6078 /* find last statement and use its type */
6079 type_t *type = type_void;
6080 const statement_t *stmt = statement->compound.statements;
6082 while (stmt->base.next != NULL)
6083 stmt = stmt->base.next;
6085 if (stmt->kind == STATEMENT_EXPRESSION) {
6086 type = stmt->expression.expression->base.type;
6089 warningf(&expression->base.source_position, "empty statement expression ({})");
6091 expression->base.type = type;
6097 return create_invalid_expression();
6101 * Parse a parenthesized expression.
6103 static expression_t *parse_parenthesized_expression(void)
6106 add_anchor_token(')');
6108 switch(token.type) {
6110 /* gcc extension: a statement expression */
6111 return parse_statement_expression();
6115 return parse_cast();
6117 if (is_typedef_symbol(token.v.symbol)) {
6118 return parse_cast();
6122 expression_t *result = parse_expression();
6123 rem_anchor_token(')');
6128 return create_invalid_expression();
6131 static expression_t *parse_function_keyword(void)
6136 if (current_function == NULL) {
6137 errorf(HERE, "'__func__' used outside of a function");
6140 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6141 expression->base.type = type_char_ptr;
6142 expression->funcname.kind = FUNCNAME_FUNCTION;
6147 static expression_t *parse_pretty_function_keyword(void)
6149 eat(T___PRETTY_FUNCTION__);
6151 if (current_function == NULL) {
6152 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6155 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6156 expression->base.type = type_char_ptr;
6157 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6162 static expression_t *parse_funcsig_keyword(void)
6166 if (current_function == NULL) {
6167 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6170 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6171 expression->base.type = type_char_ptr;
6172 expression->funcname.kind = FUNCNAME_FUNCSIG;
6177 static expression_t *parse_funcdname_keyword(void)
6179 eat(T___FUNCDNAME__);
6181 if (current_function == NULL) {
6182 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6185 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6186 expression->base.type = type_char_ptr;
6187 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6192 static designator_t *parse_designator(void)
6194 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6195 result->source_position = *HERE;
6197 if (token.type != T_IDENTIFIER) {
6198 parse_error_expected("while parsing member designator",
6199 T_IDENTIFIER, NULL);
6202 result->symbol = token.v.symbol;
6205 designator_t *last_designator = result;
6207 if (token.type == '.') {
6209 if (token.type != T_IDENTIFIER) {
6210 parse_error_expected("while parsing member designator",
6211 T_IDENTIFIER, NULL);
6214 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6215 designator->source_position = *HERE;
6216 designator->symbol = token.v.symbol;
6219 last_designator->next = designator;
6220 last_designator = designator;
6223 if (token.type == '[') {
6225 add_anchor_token(']');
6226 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6227 designator->source_position = *HERE;
6228 designator->array_index = parse_expression();
6229 rem_anchor_token(']');
6231 if (designator->array_index == NULL) {
6235 last_designator->next = designator;
6236 last_designator = designator;
6248 * Parse the __builtin_offsetof() expression.
6250 static expression_t *parse_offsetof(void)
6252 eat(T___builtin_offsetof);
6254 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6255 expression->base.type = type_size_t;
6258 add_anchor_token(',');
6259 type_t *type = parse_typename();
6260 rem_anchor_token(',');
6262 add_anchor_token(')');
6263 designator_t *designator = parse_designator();
6264 rem_anchor_token(')');
6267 expression->offsetofe.type = type;
6268 expression->offsetofe.designator = designator;
6271 memset(&path, 0, sizeof(path));
6272 path.top_type = type;
6273 path.path = NEW_ARR_F(type_path_entry_t, 0);
6275 descend_into_subtype(&path);
6277 if (!walk_designator(&path, designator, true)) {
6278 return create_invalid_expression();
6281 DEL_ARR_F(path.path);
6285 return create_invalid_expression();
6289 * Parses a _builtin_va_start() expression.
6291 static expression_t *parse_va_start(void)
6293 eat(T___builtin_va_start);
6295 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6298 add_anchor_token(',');
6299 expression->va_starte.ap = parse_assignment_expression();
6300 rem_anchor_token(',');
6302 expression_t *const expr = parse_assignment_expression();
6303 if (expr->kind == EXPR_REFERENCE) {
6304 declaration_t *const decl = expr->reference.declaration;
6306 return create_invalid_expression();
6307 if (decl->parent_scope == ¤t_function->scope &&
6308 decl->next == NULL) {
6309 expression->va_starte.parameter = decl;
6314 errorf(&expr->base.source_position,
6315 "second argument of 'va_start' must be last parameter of the current function");
6317 return create_invalid_expression();
6321 * Parses a _builtin_va_arg() expression.
6323 static expression_t *parse_va_arg(void)
6325 eat(T___builtin_va_arg);
6327 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6330 expression->va_arge.ap = parse_assignment_expression();
6332 expression->base.type = parse_typename();
6337 return create_invalid_expression();
6340 static expression_t *parse_builtin_symbol(void)
6342 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6344 symbol_t *symbol = token.v.symbol;
6346 expression->builtin_symbol.symbol = symbol;
6349 type_t *type = get_builtin_symbol_type(symbol);
6350 type = automatic_type_conversion(type);
6352 expression->base.type = type;
6357 * Parses a __builtin_constant() expression.
6359 static expression_t *parse_builtin_constant(void)
6361 eat(T___builtin_constant_p);
6363 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6366 add_anchor_token(')');
6367 expression->builtin_constant.value = parse_assignment_expression();
6368 rem_anchor_token(')');
6370 expression->base.type = type_int;
6374 return create_invalid_expression();
6378 * Parses a __builtin_prefetch() expression.
6380 static expression_t *parse_builtin_prefetch(void)
6382 eat(T___builtin_prefetch);
6384 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6387 add_anchor_token(')');
6388 expression->builtin_prefetch.adr = parse_assignment_expression();
6389 if (token.type == ',') {
6391 expression->builtin_prefetch.rw = parse_assignment_expression();
6393 if (token.type == ',') {
6395 expression->builtin_prefetch.locality = parse_assignment_expression();
6397 rem_anchor_token(')');
6399 expression->base.type = type_void;
6403 return create_invalid_expression();
6407 * Parses a __builtin_is_*() compare expression.
6409 static expression_t *parse_compare_builtin(void)
6411 expression_t *expression;
6413 switch(token.type) {
6414 case T___builtin_isgreater:
6415 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6417 case T___builtin_isgreaterequal:
6418 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6420 case T___builtin_isless:
6421 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6423 case T___builtin_islessequal:
6424 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6426 case T___builtin_islessgreater:
6427 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6429 case T___builtin_isunordered:
6430 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6433 internal_errorf(HERE, "invalid compare builtin found");
6436 expression->base.source_position = *HERE;
6440 expression->binary.left = parse_assignment_expression();
6442 expression->binary.right = parse_assignment_expression();
6445 type_t *const orig_type_left = expression->binary.left->base.type;
6446 type_t *const orig_type_right = expression->binary.right->base.type;
6448 type_t *const type_left = skip_typeref(orig_type_left);
6449 type_t *const type_right = skip_typeref(orig_type_right);
6450 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6451 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6452 type_error_incompatible("invalid operands in comparison",
6453 &expression->base.source_position, orig_type_left, orig_type_right);
6456 semantic_comparison(&expression->binary);
6461 return create_invalid_expression();
6466 * Parses a __builtin_expect() expression.
6468 static expression_t *parse_builtin_expect(void)
6470 eat(T___builtin_expect);
6472 expression_t *expression
6473 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6476 expression->binary.left = parse_assignment_expression();
6478 expression->binary.right = parse_constant_expression();
6481 expression->base.type = expression->binary.left->base.type;
6485 return create_invalid_expression();
6490 * Parses a MS assume() expression.
6492 static expression_t *parse_assume(void)
6496 expression_t *expression
6497 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6500 add_anchor_token(')');
6501 expression->unary.value = parse_assignment_expression();
6502 rem_anchor_token(')');
6505 expression->base.type = type_void;
6508 return create_invalid_expression();
6512 * Parse a microsoft __noop expression.
6514 static expression_t *parse_noop_expression(void)
6516 source_position_t source_position = *HERE;
6519 if (token.type == '(') {
6520 /* parse arguments */
6522 add_anchor_token(')');
6523 add_anchor_token(',');
6525 if (token.type != ')') {
6527 (void)parse_assignment_expression();
6528 if (token.type != ',')
6534 rem_anchor_token(',');
6535 rem_anchor_token(')');
6538 /* the result is a (int)0 */
6539 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6540 cnst->base.source_position = source_position;
6541 cnst->base.type = type_int;
6542 cnst->conste.v.int_value = 0;
6543 cnst->conste.is_ms_noop = true;
6548 return create_invalid_expression();
6552 * Parses a primary expression.
6554 static expression_t *parse_primary_expression(void)
6556 switch (token.type) {
6557 case T_INTEGER: return parse_int_const();
6558 case T_CHARACTER_CONSTANT: return parse_character_constant();
6559 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6560 case T_FLOATINGPOINT: return parse_float_const();
6561 case T_STRING_LITERAL:
6562 case T_WIDE_STRING_LITERAL: return parse_string_const();
6563 case T_IDENTIFIER: return parse_reference();
6564 case T___FUNCTION__:
6565 case T___func__: return parse_function_keyword();
6566 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6567 case T___FUNCSIG__: return parse_funcsig_keyword();
6568 case T___FUNCDNAME__: return parse_funcdname_keyword();
6569 case T___builtin_offsetof: return parse_offsetof();
6570 case T___builtin_va_start: return parse_va_start();
6571 case T___builtin_va_arg: return parse_va_arg();
6572 case T___builtin_expect:
6573 case T___builtin_alloca:
6574 case T___builtin_nan:
6575 case T___builtin_nand:
6576 case T___builtin_nanf:
6577 case T___builtin_huge_val:
6578 case T___builtin_va_end: return parse_builtin_symbol();
6579 case T___builtin_isgreater:
6580 case T___builtin_isgreaterequal:
6581 case T___builtin_isless:
6582 case T___builtin_islessequal:
6583 case T___builtin_islessgreater:
6584 case T___builtin_isunordered: return parse_compare_builtin();
6585 case T___builtin_constant_p: return parse_builtin_constant();
6586 case T___builtin_prefetch: return parse_builtin_prefetch();
6587 case T__assume: return parse_assume();
6589 case '(': return parse_parenthesized_expression();
6590 case T___noop: return parse_noop_expression();
6593 errorf(HERE, "unexpected token %K, expected an expression", &token);
6594 return create_invalid_expression();
6598 * Check if the expression has the character type and issue a warning then.
6600 static void check_for_char_index_type(const expression_t *expression)
6602 type_t *const type = expression->base.type;
6603 const type_t *const base_type = skip_typeref(type);
6605 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6606 warning.char_subscripts) {
6607 warningf(&expression->base.source_position,
6608 "array subscript has type '%T'", type);
6612 static expression_t *parse_array_expression(unsigned precedence,
6618 add_anchor_token(']');
6620 expression_t *inside = parse_expression();
6622 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6624 array_access_expression_t *array_access = &expression->array_access;
6626 type_t *const orig_type_left = left->base.type;
6627 type_t *const orig_type_inside = inside->base.type;
6629 type_t *const type_left = skip_typeref(orig_type_left);
6630 type_t *const type_inside = skip_typeref(orig_type_inside);
6632 type_t *return_type;
6633 if (is_type_pointer(type_left)) {
6634 return_type = type_left->pointer.points_to;
6635 array_access->array_ref = left;
6636 array_access->index = inside;
6637 check_for_char_index_type(inside);
6638 } else if (is_type_pointer(type_inside)) {
6639 return_type = type_inside->pointer.points_to;
6640 array_access->array_ref = inside;
6641 array_access->index = left;
6642 array_access->flipped = true;
6643 check_for_char_index_type(left);
6645 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6647 "array access on object with non-pointer types '%T', '%T'",
6648 orig_type_left, orig_type_inside);
6650 return_type = type_error_type;
6651 array_access->array_ref = create_invalid_expression();
6654 rem_anchor_token(']');
6655 if (token.type != ']') {
6656 parse_error_expected("Problem while parsing array access", ']', NULL);
6661 return_type = automatic_type_conversion(return_type);
6662 expression->base.type = return_type;
6667 static expression_t *parse_typeprop(expression_kind_t const kind,
6668 source_position_t const pos,
6669 unsigned const precedence)
6671 expression_t *tp_expression = allocate_expression_zero(kind);
6672 tp_expression->base.type = type_size_t;
6673 tp_expression->base.source_position = pos;
6675 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6677 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6679 add_anchor_token(')');
6680 type_t* const orig_type = parse_typename();
6681 tp_expression->typeprop.type = orig_type;
6683 type_t const* const type = skip_typeref(orig_type);
6684 char const* const wrong_type =
6685 is_type_incomplete(type) ? "incomplete" :
6686 type->kind == TYPE_FUNCTION ? "function designator" :
6687 type->kind == TYPE_BITFIELD ? "bitfield" :
6689 if (wrong_type != NULL) {
6690 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6691 what, wrong_type, type);
6694 rem_anchor_token(')');
6697 expression_t *expression = parse_sub_expression(precedence);
6699 type_t* const orig_type = revert_automatic_type_conversion(expression);
6700 expression->base.type = orig_type;
6702 type_t const* const type = skip_typeref(orig_type);
6703 char const* const wrong_type =
6704 is_type_incomplete(type) ? "incomplete" :
6705 type->kind == TYPE_FUNCTION ? "function designator" :
6706 type->kind == TYPE_BITFIELD ? "bitfield" :
6708 if (wrong_type != NULL) {
6709 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6712 tp_expression->typeprop.type = expression->base.type;
6713 tp_expression->typeprop.tp_expression = expression;
6716 return tp_expression;
6718 return create_invalid_expression();
6721 static expression_t *parse_sizeof(unsigned precedence)
6723 source_position_t pos = *HERE;
6725 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6728 static expression_t *parse_alignof(unsigned precedence)
6730 source_position_t pos = *HERE;
6732 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6735 static expression_t *parse_select_expression(unsigned precedence,
6736 expression_t *compound)
6739 assert(token.type == '.' || token.type == T_MINUSGREATER);
6741 bool is_pointer = (token.type == T_MINUSGREATER);
6744 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6745 select->select.compound = compound;
6747 if (token.type != T_IDENTIFIER) {
6748 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6751 symbol_t *symbol = token.v.symbol;
6754 type_t *const orig_type = compound->base.type;
6755 type_t *const type = skip_typeref(orig_type);
6757 type_t *type_left = type;
6758 bool saw_error = false;
6759 if (is_type_pointer(type)) {
6762 "request for member '%Y' in something not a struct or union, but '%T'",
6766 type_left = type->pointer.points_to;
6767 } else if (is_pointer) {
6768 if (is_type_valid(type)) {
6769 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6774 type_left = skip_typeref(type_left);
6776 declaration_t *entry;
6777 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
6778 type_left->kind == TYPE_COMPOUND_UNION) {
6779 declaration_t *const declaration = type_left->compound.declaration;
6781 if (!declaration->init.complete) {
6782 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6784 return create_invalid_expression();
6787 entry = find_compound_entry(declaration, symbol);
6788 if (entry == NULL) {
6789 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6790 goto create_error_entry;
6793 if (is_type_valid(type_left) && !saw_error) {
6795 "request for member '%Y' in something not a struct or union, but '%T'",
6799 entry = allocate_declaration_zero();
6800 entry->symbol = symbol;
6803 select->select.compound_entry = entry;
6804 /* we always do the auto-type conversions; the & and sizeof parser contains
6805 * code to revert this! */
6806 select->base.type = automatic_type_conversion(entry->type);
6808 type_t *skipped = skip_typeref(entry->type);
6809 if (skipped->kind == TYPE_BITFIELD) {
6810 select->base.type = skipped->bitfield.base_type;
6816 static void check_call_argument(const function_parameter_t *parameter,
6817 call_argument_t *argument, unsigned pos)
6819 type_t *expected_type = parameter->type;
6820 type_t *expected_type_skip = skip_typeref(expected_type);
6821 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6822 expression_t *arg_expr = argument->expression;
6823 type_t *arg_type = skip_typeref(arg_expr->base.type);
6825 /* handle transparent union gnu extension */
6826 if (is_type_union(expected_type_skip)
6827 && (expected_type_skip->base.modifiers
6828 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6829 declaration_t *union_decl = expected_type_skip->compound.declaration;
6831 declaration_t *declaration = union_decl->scope.declarations;
6832 type_t *best_type = NULL;
6833 for ( ; declaration != NULL; declaration = declaration->next) {
6834 type_t *decl_type = declaration->type;
6835 error = semantic_assign(decl_type, arg_expr);
6836 if (error == ASSIGN_ERROR_INCOMPATIBLE
6837 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6840 if (error == ASSIGN_SUCCESS) {
6841 best_type = decl_type;
6842 } else if (best_type == NULL) {
6843 best_type = decl_type;
6847 if (best_type != NULL) {
6848 expected_type = best_type;
6852 error = semantic_assign(expected_type, arg_expr);
6853 argument->expression = create_implicit_cast(argument->expression,
6856 if (error != ASSIGN_SUCCESS) {
6857 /* report exact scope in error messages (like "in argument 3") */
6859 snprintf(buf, sizeof(buf), "call argument %u", pos);
6860 report_assign_error(error, expected_type, arg_expr, buf,
6861 &arg_expr->base.source_position);
6862 } else if (warning.traditional | warning.conversion) {
6864 /* passing as integer instead of float or complex */
6865 (is_type_integer(expected_type) &&
6866 (is_type_float(arg_type) || is_type_complex(arg_type))) ||
6867 /* passing as complex instead of integer or float */
6868 (is_type_complex(expected_type) &&
6869 (is_type_integer(arg_type) || is_type_float(arg_type))) ||
6870 /* passing as float instead of integer or complex */
6871 (is_type_float(expected_type) &&
6872 (is_type_integer(arg_type) || is_type_complex(arg_type))) ||
6873 /* passing as float instead of double */
6874 (is_type_float(expected_type) && expected_type != type_double &&
6875 is_type_float(arg_type))) {
6876 warningf(&arg_expr->base.source_position,
6877 "passing call argument %u as '%T' rather than '%T' due to prototype",
6878 pos, expected_type, arg_type);
6880 if (is_type_integer(expected_type) && is_type_integer(arg_type)) {
6881 /* TODO check for size HERE */
6887 * Parse a call expression, ie. expression '( ... )'.
6889 * @param expression the function address
6891 static expression_t *parse_call_expression(unsigned precedence,
6892 expression_t *expression)
6895 expression_t *result = allocate_expression_zero(EXPR_CALL);
6896 result->base.source_position = expression->base.source_position;
6898 call_expression_t *call = &result->call;
6899 call->function = expression;
6901 type_t *const orig_type = expression->base.type;
6902 type_t *const type = skip_typeref(orig_type);
6904 function_type_t *function_type = NULL;
6905 if (is_type_pointer(type)) {
6906 type_t *const to_type = skip_typeref(type->pointer.points_to);
6908 if (is_type_function(to_type)) {
6909 function_type = &to_type->function;
6910 call->base.type = function_type->return_type;
6914 if (function_type == NULL && is_type_valid(type)) {
6915 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6918 /* parse arguments */
6920 add_anchor_token(')');
6921 add_anchor_token(',');
6923 if (token.type != ')') {
6924 call_argument_t *last_argument = NULL;
6927 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6929 argument->expression = parse_assignment_expression();
6930 if (last_argument == NULL) {
6931 call->arguments = argument;
6933 last_argument->next = argument;
6935 last_argument = argument;
6937 if (token.type != ',')
6942 rem_anchor_token(',');
6943 rem_anchor_token(')');
6946 if (function_type == NULL)
6949 function_parameter_t *parameter = function_type->parameters;
6950 call_argument_t *argument = call->arguments;
6951 if (!function_type->unspecified_parameters) {
6952 for (unsigned pos = 0; parameter != NULL && argument != NULL;
6953 parameter = parameter->next, argument = argument->next) {
6954 check_call_argument(parameter, argument, ++pos);
6957 if (parameter != NULL) {
6958 errorf(HERE, "too few arguments to function '%E'", expression);
6959 } else if (argument != NULL && !function_type->variadic) {
6960 errorf(HERE, "too many arguments to function '%E'", expression);
6964 /* do default promotion */
6965 for( ; argument != NULL; argument = argument->next) {
6966 type_t *type = argument->expression->base.type;
6968 type = get_default_promoted_type(type);
6970 argument->expression
6971 = create_implicit_cast(argument->expression, type);
6974 check_format(&result->call);
6976 if (warning.aggregate_return &&
6977 is_type_compound(skip_typeref(function_type->return_type))) {
6978 warningf(&result->base.source_position,
6979 "function call has aggregate value");
6984 return create_invalid_expression();
6987 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6989 static bool same_compound_type(const type_t *type1, const type_t *type2)
6992 is_type_compound(type1) &&
6993 type1->kind == type2->kind &&
6994 type1->compound.declaration == type2->compound.declaration;
6998 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7000 * @param expression the conditional expression
7002 static expression_t *parse_conditional_expression(unsigned precedence,
7003 expression_t *expression)
7005 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7007 conditional_expression_t *conditional = &result->conditional;
7008 conditional->base.source_position = *HERE;
7009 conditional->condition = expression;
7012 add_anchor_token(':');
7015 type_t *const condition_type_orig = expression->base.type;
7016 type_t *const condition_type = skip_typeref(condition_type_orig);
7017 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7018 type_error("expected a scalar type in conditional condition",
7019 &expression->base.source_position, condition_type_orig);
7022 expression_t *true_expression = expression;
7023 bool gnu_cond = false;
7024 if ((c_mode & _GNUC) && token.type == ':') {
7027 true_expression = parse_expression();
7028 rem_anchor_token(':');
7030 expression_t *false_expression = parse_sub_expression(precedence);
7032 type_t *const orig_true_type = true_expression->base.type;
7033 type_t *const orig_false_type = false_expression->base.type;
7034 type_t *const true_type = skip_typeref(orig_true_type);
7035 type_t *const false_type = skip_typeref(orig_false_type);
7038 type_t *result_type;
7039 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7040 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7041 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7042 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7043 warningf(&conditional->base.source_position,
7044 "ISO C forbids conditional expression with only one void side");
7046 result_type = type_void;
7047 } else if (is_type_arithmetic(true_type)
7048 && is_type_arithmetic(false_type)) {
7049 result_type = semantic_arithmetic(true_type, false_type);
7051 true_expression = create_implicit_cast(true_expression, result_type);
7052 false_expression = create_implicit_cast(false_expression, result_type);
7054 conditional->true_expression = true_expression;
7055 conditional->false_expression = false_expression;
7056 conditional->base.type = result_type;
7057 } else if (same_compound_type(true_type, false_type)) {
7058 /* just take 1 of the 2 types */
7059 result_type = true_type;
7060 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7061 type_t *pointer_type;
7063 expression_t *other_expression;
7064 if (is_type_pointer(true_type) &&
7065 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7066 pointer_type = true_type;
7067 other_type = false_type;
7068 other_expression = false_expression;
7070 pointer_type = false_type;
7071 other_type = true_type;
7072 other_expression = true_expression;
7075 if (is_null_pointer_constant(other_expression)) {
7076 result_type = pointer_type;
7077 } else if (is_type_pointer(other_type)) {
7078 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7079 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7082 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7083 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7085 } else if (types_compatible(get_unqualified_type(to1),
7086 get_unqualified_type(to2))) {
7089 warningf(&conditional->base.source_position,
7090 "pointer types '%T' and '%T' in conditional expression are incompatible",
7091 true_type, false_type);
7095 type_t *const copy = duplicate_type(to);
7096 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
7098 type_t *const type = typehash_insert(copy);
7102 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7103 } else if (is_type_integer(other_type)) {
7104 warningf(&conditional->base.source_position,
7105 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7106 result_type = pointer_type;
7108 type_error_incompatible("while parsing conditional",
7109 &expression->base.source_position, true_type, false_type);
7110 result_type = type_error_type;
7113 /* TODO: one pointer to void*, other some pointer */
7115 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7116 type_error_incompatible("while parsing conditional",
7117 &conditional->base.source_position, true_type,
7120 result_type = type_error_type;
7123 conditional->true_expression
7124 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7125 conditional->false_expression
7126 = create_implicit_cast(false_expression, result_type);
7127 conditional->base.type = result_type;
7130 return create_invalid_expression();
7134 * Parse an extension expression.
7136 static expression_t *parse_extension(unsigned precedence)
7138 eat(T___extension__);
7140 /* TODO enable extensions */
7141 expression_t *expression = parse_sub_expression(precedence);
7142 /* TODO disable extensions */
7147 * Parse a __builtin_classify_type() expression.
7149 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7151 eat(T___builtin_classify_type);
7153 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7154 result->base.type = type_int;
7157 add_anchor_token(')');
7158 expression_t *expression = parse_sub_expression(precedence);
7159 rem_anchor_token(')');
7161 result->classify_type.type_expression = expression;
7165 return create_invalid_expression();
7168 static bool check_pointer_arithmetic(const source_position_t *source_position,
7169 type_t *pointer_type,
7170 type_t *orig_pointer_type)
7172 type_t *points_to = pointer_type->pointer.points_to;
7173 points_to = skip_typeref(points_to);
7175 if (is_type_incomplete(points_to)) {
7176 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7177 errorf(source_position,
7178 "arithmetic with pointer to incomplete type '%T' not allowed",
7181 } else if (warning.pointer_arith) {
7182 warningf(source_position,
7183 "pointer of type '%T' used in arithmetic",
7186 } else if (is_type_function(points_to)) {
7187 if (!(c_mode && _GNUC)) {
7188 errorf(source_position,
7189 "arithmetic with pointer to function type '%T' not allowed",
7192 } else if (warning.pointer_arith) {
7193 warningf(source_position,
7194 "pointer to a function '%T' used in arithmetic",
7201 static bool is_lvalue(const expression_t *expression)
7203 switch (expression->kind) {
7204 case EXPR_REFERENCE:
7205 case EXPR_ARRAY_ACCESS:
7207 case EXPR_UNARY_DEREFERENCE:
7215 static void semantic_incdec(unary_expression_t *expression)
7217 type_t *const orig_type = expression->value->base.type;
7218 type_t *const type = skip_typeref(orig_type);
7219 if (is_type_pointer(type)) {
7220 if (!check_pointer_arithmetic(&expression->base.source_position,
7224 } else if (!is_type_real(type) && is_type_valid(type)) {
7225 /* TODO: improve error message */
7226 errorf(&expression->base.source_position,
7227 "operation needs an arithmetic or pointer type");
7230 if (!is_lvalue(expression->value)) {
7231 /* TODO: improve error message */
7232 errorf(&expression->base.source_position, "lvalue required as operand");
7234 expression->base.type = orig_type;
7237 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7239 type_t *const orig_type = expression->value->base.type;
7240 type_t *const type = skip_typeref(orig_type);
7241 if (!is_type_arithmetic(type)) {
7242 if (is_type_valid(type)) {
7243 /* TODO: improve error message */
7244 errorf(&expression->base.source_position,
7245 "operation needs an arithmetic type");
7250 expression->base.type = orig_type;
7253 static void semantic_unexpr_plus(unary_expression_t *expression)
7255 semantic_unexpr_arithmetic(expression);
7256 if (warning.traditional)
7257 warningf(&expression->base.source_position,
7258 "traditional C rejects the unary plus operator");
7261 static void semantic_not(unary_expression_t *expression)
7263 type_t *const orig_type = expression->value->base.type;
7264 type_t *const type = skip_typeref(orig_type);
7265 if (!is_type_scalar(type) && is_type_valid(type)) {
7266 errorf(&expression->base.source_position,
7267 "operand of ! must be of scalar type");
7270 expression->base.type = type_int;
7273 static void semantic_unexpr_integer(unary_expression_t *expression)
7275 type_t *const orig_type = expression->value->base.type;
7276 type_t *const type = skip_typeref(orig_type);
7277 if (!is_type_integer(type)) {
7278 if (is_type_valid(type)) {
7279 errorf(&expression->base.source_position,
7280 "operand of ~ must be of integer type");
7285 expression->base.type = orig_type;
7288 static void semantic_dereference(unary_expression_t *expression)
7290 type_t *const orig_type = expression->value->base.type;
7291 type_t *const type = skip_typeref(orig_type);
7292 if (!is_type_pointer(type)) {
7293 if (is_type_valid(type)) {
7294 errorf(&expression->base.source_position,
7295 "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
7300 type_t *result_type = type->pointer.points_to;
7301 result_type = automatic_type_conversion(result_type);
7302 expression->base.type = result_type;
7306 * Record that an address is taken (expression represents an lvalue).
7308 * @param expression the expression
7309 * @param may_be_register if true, the expression might be an register
7311 static void set_address_taken(expression_t *expression, bool may_be_register)
7313 if (expression->kind != EXPR_REFERENCE)
7316 declaration_t *const declaration = expression->reference.declaration;
7317 /* happens for parse errors */
7318 if (declaration == NULL)
7321 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7322 errorf(&expression->base.source_position,
7323 "address of register variable '%Y' requested",
7324 declaration->symbol);
7326 declaration->address_taken = 1;
7331 * Check the semantic of the address taken expression.
7333 static void semantic_take_addr(unary_expression_t *expression)
7335 expression_t *value = expression->value;
7336 value->base.type = revert_automatic_type_conversion(value);
7338 type_t *orig_type = value->base.type;
7339 if (!is_type_valid(orig_type))
7342 set_address_taken(value, false);
7344 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7347 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7348 static expression_t *parse_##unexpression_type(unsigned precedence) \
7350 expression_t *unary_expression \
7351 = allocate_expression_zero(unexpression_type); \
7352 unary_expression->base.source_position = *HERE; \
7354 unary_expression->unary.value = parse_sub_expression(precedence); \
7356 sfunc(&unary_expression->unary); \
7358 return unary_expression; \
7361 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7362 semantic_unexpr_arithmetic)
7363 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7364 semantic_unexpr_plus)
7365 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7367 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7368 semantic_dereference)
7369 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7371 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7372 semantic_unexpr_integer)
7373 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7375 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7378 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7380 static expression_t *parse_##unexpression_type(unsigned precedence, \
7381 expression_t *left) \
7383 (void) precedence; \
7385 expression_t *unary_expression \
7386 = allocate_expression_zero(unexpression_type); \
7387 unary_expression->base.source_position = *HERE; \
7389 unary_expression->unary.value = left; \
7391 sfunc(&unary_expression->unary); \
7393 return unary_expression; \
7396 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7397 EXPR_UNARY_POSTFIX_INCREMENT,
7399 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7400 EXPR_UNARY_POSTFIX_DECREMENT,
7403 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7405 /* TODO: handle complex + imaginary types */
7407 /* § 6.3.1.8 Usual arithmetic conversions */
7408 if (type_left == type_long_double || type_right == type_long_double) {
7409 return type_long_double;
7410 } else if (type_left == type_double || type_right == type_double) {
7412 } else if (type_left == type_float || type_right == type_float) {
7416 type_left = promote_integer(type_left);
7417 type_right = promote_integer(type_right);
7419 if (type_left == type_right)
7422 bool const signed_left = is_type_signed(type_left);
7423 bool const signed_right = is_type_signed(type_right);
7424 int const rank_left = get_rank(type_left);
7425 int const rank_right = get_rank(type_right);
7427 if (signed_left == signed_right)
7428 return rank_left >= rank_right ? type_left : type_right;
7437 u_rank = rank_right;
7438 u_type = type_right;
7440 s_rank = rank_right;
7441 s_type = type_right;
7446 if (u_rank >= s_rank)
7449 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7451 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7452 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7456 case ATOMIC_TYPE_INT: return type_unsigned_int;
7457 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7458 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7460 default: panic("invalid atomic type");
7465 * Check the semantic restrictions for a binary expression.
7467 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7469 expression_t *const left = expression->left;
7470 expression_t *const right = expression->right;
7471 type_t *const orig_type_left = left->base.type;
7472 type_t *const orig_type_right = right->base.type;
7473 type_t *const type_left = skip_typeref(orig_type_left);
7474 type_t *const type_right = skip_typeref(orig_type_right);
7476 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7477 /* TODO: improve error message */
7478 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7479 errorf(&expression->base.source_position,
7480 "operation needs arithmetic types");
7485 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7486 expression->left = create_implicit_cast(left, arithmetic_type);
7487 expression->right = create_implicit_cast(right, arithmetic_type);
7488 expression->base.type = arithmetic_type;
7491 static void warn_div_by_zero(binary_expression_t const *const expression)
7493 if (warning.div_by_zero &&
7494 is_type_integer(expression->base.type) &&
7495 is_constant_expression(expression->right) &&
7496 fold_constant(expression->right) == 0) {
7497 warningf(&expression->base.source_position, "division by zero");
7502 * Check the semantic restrictions for a div/mod expression.
7504 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7505 semantic_binexpr_arithmetic(expression);
7506 warn_div_by_zero(expression);
7509 static void semantic_shift_op(binary_expression_t *expression)
7511 expression_t *const left = expression->left;
7512 expression_t *const right = expression->right;
7513 type_t *const orig_type_left = left->base.type;
7514 type_t *const orig_type_right = right->base.type;
7515 type_t * type_left = skip_typeref(orig_type_left);
7516 type_t * type_right = skip_typeref(orig_type_right);
7518 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7519 /* TODO: improve error message */
7520 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7521 errorf(&expression->base.source_position,
7522 "operands of shift operation must have integer types");
7527 type_left = promote_integer(type_left);
7528 type_right = promote_integer(type_right);
7530 expression->left = create_implicit_cast(left, type_left);
7531 expression->right = create_implicit_cast(right, type_right);
7532 expression->base.type = type_left;
7535 static void semantic_add(binary_expression_t *expression)
7537 expression_t *const left = expression->left;
7538 expression_t *const right = expression->right;
7539 type_t *const orig_type_left = left->base.type;
7540 type_t *const orig_type_right = right->base.type;
7541 type_t *const type_left = skip_typeref(orig_type_left);
7542 type_t *const type_right = skip_typeref(orig_type_right);
7545 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7546 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7547 expression->left = create_implicit_cast(left, arithmetic_type);
7548 expression->right = create_implicit_cast(right, arithmetic_type);
7549 expression->base.type = arithmetic_type;
7551 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7552 check_pointer_arithmetic(&expression->base.source_position,
7553 type_left, orig_type_left);
7554 expression->base.type = type_left;
7555 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7556 check_pointer_arithmetic(&expression->base.source_position,
7557 type_right, orig_type_right);
7558 expression->base.type = type_right;
7559 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7560 errorf(&expression->base.source_position,
7561 "invalid operands to binary + ('%T', '%T')",
7562 orig_type_left, orig_type_right);
7566 static void semantic_sub(binary_expression_t *expression)
7568 expression_t *const left = expression->left;
7569 expression_t *const right = expression->right;
7570 type_t *const orig_type_left = left->base.type;
7571 type_t *const orig_type_right = right->base.type;
7572 type_t *const type_left = skip_typeref(orig_type_left);
7573 type_t *const type_right = skip_typeref(orig_type_right);
7574 source_position_t const *const pos = &expression->base.source_position;
7577 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7578 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7579 expression->left = create_implicit_cast(left, arithmetic_type);
7580 expression->right = create_implicit_cast(right, arithmetic_type);
7581 expression->base.type = arithmetic_type;
7583 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7584 check_pointer_arithmetic(&expression->base.source_position,
7585 type_left, orig_type_left);
7586 expression->base.type = type_left;
7587 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7588 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7589 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7590 if (!types_compatible(unqual_left, unqual_right)) {
7592 "subtracting pointers to incompatible types '%T' and '%T'",
7593 orig_type_left, orig_type_right);
7594 } else if (!is_type_object(unqual_left)) {
7595 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7596 warningf(pos, "subtracting pointers to void");
7598 errorf(pos, "subtracting pointers to non-object types '%T'",
7602 expression->base.type = type_ptrdiff_t;
7603 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7604 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7605 orig_type_left, orig_type_right);
7610 * Check the semantics of comparison expressions.
7612 * @param expression The expression to check.
7614 static void semantic_comparison(binary_expression_t *expression)
7616 expression_t *left = expression->left;
7617 expression_t *right = expression->right;
7618 type_t *orig_type_left = left->base.type;
7619 type_t *orig_type_right = right->base.type;
7621 type_t *type_left = skip_typeref(orig_type_left);
7622 type_t *type_right = skip_typeref(orig_type_right);
7624 /* TODO non-arithmetic types */
7625 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7626 /* test for signed vs unsigned compares */
7627 if (warning.sign_compare &&
7628 (expression->base.kind != EXPR_BINARY_EQUAL &&
7629 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7630 (is_type_signed(type_left) != is_type_signed(type_right))) {
7632 /* check if 1 of the operands is a constant, in this case we just
7633 * check wether we can safely represent the resulting constant in
7634 * the type of the other operand. */
7635 expression_t *const_expr = NULL;
7636 expression_t *other_expr = NULL;
7638 if (is_constant_expression(left)) {
7641 } else if (is_constant_expression(right)) {
7646 if (const_expr != NULL) {
7647 type_t *other_type = skip_typeref(other_expr->base.type);
7648 long val = fold_constant(const_expr);
7649 /* TODO: check if val can be represented by other_type */
7653 warningf(&expression->base.source_position,
7654 "comparison between signed and unsigned");
7656 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7657 expression->left = create_implicit_cast(left, arithmetic_type);
7658 expression->right = create_implicit_cast(right, arithmetic_type);
7659 expression->base.type = arithmetic_type;
7660 if (warning.float_equal &&
7661 (expression->base.kind == EXPR_BINARY_EQUAL ||
7662 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7663 is_type_float(arithmetic_type)) {
7664 warningf(&expression->base.source_position,
7665 "comparing floating point with == or != is unsafe");
7667 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7668 /* TODO check compatibility */
7669 } else if (is_type_pointer(type_left)) {
7670 expression->right = create_implicit_cast(right, type_left);
7671 } else if (is_type_pointer(type_right)) {
7672 expression->left = create_implicit_cast(left, type_right);
7673 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7674 type_error_incompatible("invalid operands in comparison",
7675 &expression->base.source_position,
7676 type_left, type_right);
7678 expression->base.type = type_int;
7682 * Checks if a compound type has constant fields.
7684 static bool has_const_fields(const compound_type_t *type)
7686 const scope_t *scope = &type->declaration->scope;
7687 const declaration_t *declaration = scope->declarations;
7689 for (; declaration != NULL; declaration = declaration->next) {
7690 if (declaration->namespc != NAMESPACE_NORMAL)
7693 const type_t *decl_type = skip_typeref(declaration->type);
7694 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7701 static bool is_valid_assignment_lhs(expression_t const* const left)
7703 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7704 type_t *const type_left = skip_typeref(orig_type_left);
7706 if (!is_lvalue(left)) {
7707 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7712 if (is_type_array(type_left)) {
7713 errorf(HERE, "cannot assign to arrays ('%E')", left);
7716 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7717 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7721 if (is_type_incomplete(type_left)) {
7722 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7723 left, orig_type_left);
7726 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7727 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7728 left, orig_type_left);
7735 static void semantic_arithmetic_assign(binary_expression_t *expression)
7737 expression_t *left = expression->left;
7738 expression_t *right = expression->right;
7739 type_t *orig_type_left = left->base.type;
7740 type_t *orig_type_right = right->base.type;
7742 if (!is_valid_assignment_lhs(left))
7745 type_t *type_left = skip_typeref(orig_type_left);
7746 type_t *type_right = skip_typeref(orig_type_right);
7748 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7749 /* TODO: improve error message */
7750 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7751 errorf(&expression->base.source_position,
7752 "operation needs arithmetic types");
7757 /* combined instructions are tricky. We can't create an implicit cast on
7758 * the left side, because we need the uncasted form for the store.
7759 * The ast2firm pass has to know that left_type must be right_type
7760 * for the arithmetic operation and create a cast by itself */
7761 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7762 expression->right = create_implicit_cast(right, arithmetic_type);
7763 expression->base.type = type_left;
7766 static void semantic_divmod_assign(binary_expression_t *expression)
7768 semantic_arithmetic_assign(expression);
7769 warn_div_by_zero(expression);
7772 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7774 expression_t *const left = expression->left;
7775 expression_t *const right = expression->right;
7776 type_t *const orig_type_left = left->base.type;
7777 type_t *const orig_type_right = right->base.type;
7778 type_t *const type_left = skip_typeref(orig_type_left);
7779 type_t *const type_right = skip_typeref(orig_type_right);
7781 if (!is_valid_assignment_lhs(left))
7784 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7785 /* combined instructions are tricky. We can't create an implicit cast on
7786 * the left side, because we need the uncasted form for the store.
7787 * The ast2firm pass has to know that left_type must be right_type
7788 * for the arithmetic operation and create a cast by itself */
7789 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7790 expression->right = create_implicit_cast(right, arithmetic_type);
7791 expression->base.type = type_left;
7792 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7793 check_pointer_arithmetic(&expression->base.source_position,
7794 type_left, orig_type_left);
7795 expression->base.type = type_left;
7796 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7797 errorf(&expression->base.source_position,
7798 "incompatible types '%T' and '%T' in assignment",
7799 orig_type_left, orig_type_right);
7804 * Check the semantic restrictions of a logical expression.
7806 static void semantic_logical_op(binary_expression_t *expression)
7808 expression_t *const left = expression->left;
7809 expression_t *const right = expression->right;
7810 type_t *const orig_type_left = left->base.type;
7811 type_t *const orig_type_right = right->base.type;
7812 type_t *const type_left = skip_typeref(orig_type_left);
7813 type_t *const type_right = skip_typeref(orig_type_right);
7815 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7816 /* TODO: improve error message */
7817 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7818 errorf(&expression->base.source_position,
7819 "operation needs scalar types");
7824 expression->base.type = type_int;
7828 * Check the semantic restrictions of a binary assign expression.
7830 static void semantic_binexpr_assign(binary_expression_t *expression)
7832 expression_t *left = expression->left;
7833 type_t *orig_type_left = left->base.type;
7835 type_t *type_left = revert_automatic_type_conversion(left);
7836 type_left = skip_typeref(orig_type_left);
7838 if (!is_valid_assignment_lhs(left))
7841 assign_error_t error = semantic_assign(orig_type_left, expression->right);
7842 report_assign_error(error, orig_type_left, expression->right,
7843 "assignment", &left->base.source_position);
7844 expression->right = create_implicit_cast(expression->right, orig_type_left);
7845 expression->base.type = orig_type_left;
7849 * Determine if the outermost operation (or parts thereof) of the given
7850 * expression has no effect in order to generate a warning about this fact.
7851 * Therefore in some cases this only examines some of the operands of the
7852 * expression (see comments in the function and examples below).
7854 * f() + 23; // warning, because + has no effect
7855 * x || f(); // no warning, because x controls execution of f()
7856 * x ? y : f(); // warning, because y has no effect
7857 * (void)x; // no warning to be able to suppress the warning
7858 * This function can NOT be used for an "expression has definitely no effect"-
7860 static bool expression_has_effect(const expression_t *const expr)
7862 switch (expr->kind) {
7863 case EXPR_UNKNOWN: break;
7864 case EXPR_INVALID: return true; /* do NOT warn */
7865 case EXPR_REFERENCE: return false;
7866 /* suppress the warning for microsoft __noop operations */
7867 case EXPR_CONST: return expr->conste.is_ms_noop;
7868 case EXPR_CHARACTER_CONSTANT: return false;
7869 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
7870 case EXPR_STRING_LITERAL: return false;
7871 case EXPR_WIDE_STRING_LITERAL: return false;
7874 const call_expression_t *const call = &expr->call;
7875 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7878 switch (call->function->builtin_symbol.symbol->ID) {
7879 case T___builtin_va_end: return true;
7880 default: return false;
7884 /* Generate the warning if either the left or right hand side of a
7885 * conditional expression has no effect */
7886 case EXPR_CONDITIONAL: {
7887 const conditional_expression_t *const cond = &expr->conditional;
7889 expression_has_effect(cond->true_expression) &&
7890 expression_has_effect(cond->false_expression);
7893 case EXPR_SELECT: return false;
7894 case EXPR_ARRAY_ACCESS: return false;
7895 case EXPR_SIZEOF: return false;
7896 case EXPR_CLASSIFY_TYPE: return false;
7897 case EXPR_ALIGNOF: return false;
7899 case EXPR_FUNCNAME: return false;
7900 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7901 case EXPR_BUILTIN_CONSTANT_P: return false;
7902 case EXPR_BUILTIN_PREFETCH: return true;
7903 case EXPR_OFFSETOF: return false;
7904 case EXPR_VA_START: return true;
7905 case EXPR_VA_ARG: return true;
7906 case EXPR_STATEMENT: return true; // TODO
7907 case EXPR_COMPOUND_LITERAL: return false;
7909 case EXPR_UNARY_NEGATE: return false;
7910 case EXPR_UNARY_PLUS: return false;
7911 case EXPR_UNARY_BITWISE_NEGATE: return false;
7912 case EXPR_UNARY_NOT: return false;
7913 case EXPR_UNARY_DEREFERENCE: return false;
7914 case EXPR_UNARY_TAKE_ADDRESS: return false;
7915 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7916 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7917 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7918 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7920 /* Treat void casts as if they have an effect in order to being able to
7921 * suppress the warning */
7922 case EXPR_UNARY_CAST: {
7923 type_t *const type = skip_typeref(expr->base.type);
7924 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7927 case EXPR_UNARY_CAST_IMPLICIT: return true;
7928 case EXPR_UNARY_ASSUME: return true;
7930 case EXPR_BINARY_ADD: return false;
7931 case EXPR_BINARY_SUB: return false;
7932 case EXPR_BINARY_MUL: return false;
7933 case EXPR_BINARY_DIV: return false;
7934 case EXPR_BINARY_MOD: return false;
7935 case EXPR_BINARY_EQUAL: return false;
7936 case EXPR_BINARY_NOTEQUAL: return false;
7937 case EXPR_BINARY_LESS: return false;
7938 case EXPR_BINARY_LESSEQUAL: return false;
7939 case EXPR_BINARY_GREATER: return false;
7940 case EXPR_BINARY_GREATEREQUAL: return false;
7941 case EXPR_BINARY_BITWISE_AND: return false;
7942 case EXPR_BINARY_BITWISE_OR: return false;
7943 case EXPR_BINARY_BITWISE_XOR: return false;
7944 case EXPR_BINARY_SHIFTLEFT: return false;
7945 case EXPR_BINARY_SHIFTRIGHT: return false;
7946 case EXPR_BINARY_ASSIGN: return true;
7947 case EXPR_BINARY_MUL_ASSIGN: return true;
7948 case EXPR_BINARY_DIV_ASSIGN: return true;
7949 case EXPR_BINARY_MOD_ASSIGN: return true;
7950 case EXPR_BINARY_ADD_ASSIGN: return true;
7951 case EXPR_BINARY_SUB_ASSIGN: return true;
7952 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7953 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7954 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7955 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7956 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7958 /* Only examine the right hand side of && and ||, because the left hand
7959 * side already has the effect of controlling the execution of the right
7961 case EXPR_BINARY_LOGICAL_AND:
7962 case EXPR_BINARY_LOGICAL_OR:
7963 /* Only examine the right hand side of a comma expression, because the left
7964 * hand side has a separate warning */
7965 case EXPR_BINARY_COMMA:
7966 return expression_has_effect(expr->binary.right);
7968 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7969 case EXPR_BINARY_ISGREATER: return false;
7970 case EXPR_BINARY_ISGREATEREQUAL: return false;
7971 case EXPR_BINARY_ISLESS: return false;
7972 case EXPR_BINARY_ISLESSEQUAL: return false;
7973 case EXPR_BINARY_ISLESSGREATER: return false;
7974 case EXPR_BINARY_ISUNORDERED: return false;
7977 internal_errorf(HERE, "unexpected expression");
7980 static void semantic_comma(binary_expression_t *expression)
7982 if (warning.unused_value) {
7983 const expression_t *const left = expression->left;
7984 if (!expression_has_effect(left)) {
7985 warningf(&left->base.source_position,
7986 "left-hand operand of comma expression has no effect");
7989 expression->base.type = expression->right->base.type;
7992 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7993 static expression_t *parse_##binexpression_type(unsigned precedence, \
7994 expression_t *left) \
7996 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7997 binexpr->base.source_position = *HERE; \
7998 binexpr->binary.left = left; \
8001 expression_t *right = parse_sub_expression(precedence + lr); \
8003 binexpr->binary.right = right; \
8004 sfunc(&binexpr->binary); \
8009 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8010 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8011 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8012 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8013 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8014 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8015 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8016 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8017 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8019 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8020 semantic_comparison, 1)
8021 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8022 semantic_comparison, 1)
8023 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8024 semantic_comparison, 1)
8025 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8026 semantic_comparison, 1)
8028 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8029 semantic_binexpr_arithmetic, 1)
8030 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8031 semantic_binexpr_arithmetic, 1)
8032 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8033 semantic_binexpr_arithmetic, 1)
8034 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8035 semantic_logical_op, 1)
8036 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8037 semantic_logical_op, 1)
8038 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8039 semantic_shift_op, 1)
8040 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8041 semantic_shift_op, 1)
8042 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8043 semantic_arithmetic_addsubb_assign, 0)
8044 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8045 semantic_arithmetic_addsubb_assign, 0)
8046 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8047 semantic_arithmetic_assign, 0)
8048 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8049 semantic_divmod_assign, 0)
8050 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8051 semantic_divmod_assign, 0)
8052 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8053 semantic_arithmetic_assign, 0)
8054 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8055 semantic_arithmetic_assign, 0)
8056 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8057 semantic_arithmetic_assign, 0)
8058 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8059 semantic_arithmetic_assign, 0)
8060 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8061 semantic_arithmetic_assign, 0)
8063 static expression_t *parse_sub_expression(unsigned precedence)
8065 if (token.type < 0) {
8066 return expected_expression_error();
8069 expression_parser_function_t *parser
8070 = &expression_parsers[token.type];
8071 source_position_t source_position = token.source_position;
8074 if (parser->parser != NULL) {
8075 left = parser->parser(parser->precedence);
8077 left = parse_primary_expression();
8079 assert(left != NULL);
8080 left->base.source_position = source_position;
8083 if (token.type < 0) {
8084 return expected_expression_error();
8087 parser = &expression_parsers[token.type];
8088 if (parser->infix_parser == NULL)
8090 if (parser->infix_precedence < precedence)
8093 left = parser->infix_parser(parser->infix_precedence, left);
8095 assert(left != NULL);
8096 assert(left->kind != EXPR_UNKNOWN);
8097 left->base.source_position = source_position;
8104 * Parse an expression.
8106 static expression_t *parse_expression(void)
8108 return parse_sub_expression(1);
8112 * Register a parser for a prefix-like operator with given precedence.
8114 * @param parser the parser function
8115 * @param token_type the token type of the prefix token
8116 * @param precedence the precedence of the operator
8118 static void register_expression_parser(parse_expression_function parser,
8119 int token_type, unsigned precedence)
8121 expression_parser_function_t *entry = &expression_parsers[token_type];
8123 if (entry->parser != NULL) {
8124 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8125 panic("trying to register multiple expression parsers for a token");
8127 entry->parser = parser;
8128 entry->precedence = precedence;
8132 * Register a parser for an infix operator with given precedence.
8134 * @param parser the parser function
8135 * @param token_type the token type of the infix operator
8136 * @param precedence the precedence of the operator
8138 static void register_infix_parser(parse_expression_infix_function parser,
8139 int token_type, unsigned precedence)
8141 expression_parser_function_t *entry = &expression_parsers[token_type];
8143 if (entry->infix_parser != NULL) {
8144 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8145 panic("trying to register multiple infix expression parsers for a "
8148 entry->infix_parser = parser;
8149 entry->infix_precedence = precedence;
8153 * Initialize the expression parsers.
8155 static void init_expression_parsers(void)
8157 memset(&expression_parsers, 0, sizeof(expression_parsers));
8159 register_infix_parser(parse_array_expression, '[', 30);
8160 register_infix_parser(parse_call_expression, '(', 30);
8161 register_infix_parser(parse_select_expression, '.', 30);
8162 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8163 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8165 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8168 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8169 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8170 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8171 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8172 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8173 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8174 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8175 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8176 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8177 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8178 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8179 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8180 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8181 T_EXCLAMATIONMARKEQUAL, 13);
8182 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8183 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8184 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8185 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8186 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8187 register_infix_parser(parse_conditional_expression, '?', 7);
8188 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8189 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8190 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8191 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8192 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8193 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8194 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8195 T_LESSLESSEQUAL, 2);
8196 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8197 T_GREATERGREATEREQUAL, 2);
8198 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8200 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8202 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8205 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8207 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8208 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8209 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8210 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8211 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8212 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8213 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8215 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8217 register_expression_parser(parse_sizeof, T_sizeof, 25);
8218 register_expression_parser(parse_alignof, T___alignof__, 25);
8219 register_expression_parser(parse_extension, T___extension__, 25);
8220 register_expression_parser(parse_builtin_classify_type,
8221 T___builtin_classify_type, 25);
8225 * Parse a asm statement arguments specification.
8227 static asm_argument_t *parse_asm_arguments(bool is_out)
8229 asm_argument_t *result = NULL;
8230 asm_argument_t *last = NULL;
8232 while (token.type == T_STRING_LITERAL || token.type == '[') {
8233 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8234 memset(argument, 0, sizeof(argument[0]));
8236 if (token.type == '[') {
8238 if (token.type != T_IDENTIFIER) {
8239 parse_error_expected("while parsing asm argument",
8240 T_IDENTIFIER, NULL);
8243 argument->symbol = token.v.symbol;
8248 argument->constraints = parse_string_literals();
8250 add_anchor_token(')');
8251 expression_t *expression = parse_expression();
8252 rem_anchor_token(')');
8254 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8255 * change size or type representation (e.g. int -> long is ok, but
8256 * int -> float is not) */
8257 if (expression->kind == EXPR_UNARY_CAST) {
8258 type_t *const type = expression->base.type;
8259 type_kind_t const kind = type->kind;
8260 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8263 if (kind == TYPE_ATOMIC) {
8264 atomic_type_kind_t const akind = type->atomic.akind;
8265 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8266 size = get_atomic_type_size(akind);
8268 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8269 size = get_atomic_type_size(get_intptr_kind());
8273 expression_t *const value = expression->unary.value;
8274 type_t *const value_type = value->base.type;
8275 type_kind_t const value_kind = value_type->kind;
8277 unsigned value_flags;
8278 unsigned value_size;
8279 if (value_kind == TYPE_ATOMIC) {
8280 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8281 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8282 value_size = get_atomic_type_size(value_akind);
8283 } else if (value_kind == TYPE_POINTER) {
8284 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8285 value_size = get_atomic_type_size(get_intptr_kind());
8290 if (value_flags != flags || value_size != size)
8294 } while (expression->kind == EXPR_UNARY_CAST);
8298 if (!is_lvalue(expression)) {
8299 errorf(&expression->base.source_position,
8300 "asm output argument is not an lvalue");
8303 argument->expression = expression;
8306 set_address_taken(expression, true);
8309 last->next = argument;
8315 if (token.type != ',')
8326 * Parse a asm statement clobber specification.
8328 static asm_clobber_t *parse_asm_clobbers(void)
8330 asm_clobber_t *result = NULL;
8331 asm_clobber_t *last = NULL;
8333 while(token.type == T_STRING_LITERAL) {
8334 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8335 clobber->clobber = parse_string_literals();
8338 last->next = clobber;
8344 if (token.type != ',')
8353 * Parse an asm statement.
8355 static statement_t *parse_asm_statement(void)
8359 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8360 statement->base.source_position = token.source_position;
8362 asm_statement_t *asm_statement = &statement->asms;
8364 if (token.type == T_volatile) {
8366 asm_statement->is_volatile = true;
8370 add_anchor_token(')');
8371 add_anchor_token(':');
8372 asm_statement->asm_text = parse_string_literals();
8374 if (token.type != ':') {
8375 rem_anchor_token(':');
8380 asm_statement->outputs = parse_asm_arguments(true);
8381 if (token.type != ':') {
8382 rem_anchor_token(':');
8387 asm_statement->inputs = parse_asm_arguments(false);
8388 if (token.type != ':') {
8389 rem_anchor_token(':');
8392 rem_anchor_token(':');
8395 asm_statement->clobbers = parse_asm_clobbers();
8398 rem_anchor_token(')');
8402 if (asm_statement->outputs == NULL) {
8403 /* GCC: An 'asm' instruction without any output operands will be treated
8404 * identically to a volatile 'asm' instruction. */
8405 asm_statement->is_volatile = true;
8410 return create_invalid_statement();
8414 * Parse a case statement.
8416 static statement_t *parse_case_statement(void)
8420 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8421 source_position_t *const pos = &statement->base.source_position;
8423 *pos = token.source_position;
8424 statement->case_label.expression = parse_expression();
8425 if (! is_constant_expression(statement->case_label.expression)) {
8426 errorf(pos, "case label does not reduce to an integer constant");
8427 statement->case_label.is_bad = true;
8429 long const val = fold_constant(statement->case_label.expression);
8430 statement->case_label.first_case = val;
8431 statement->case_label.last_case = val;
8434 if (c_mode & _GNUC) {
8435 if (token.type == T_DOTDOTDOT) {
8437 statement->case_label.end_range = parse_expression();
8438 if (! is_constant_expression(statement->case_label.end_range)) {
8439 errorf(pos, "case range does not reduce to an integer constant");
8440 statement->case_label.is_bad = true;
8442 long const val = fold_constant(statement->case_label.end_range);
8443 statement->case_label.last_case = val;
8445 if (val < statement->case_label.first_case) {
8446 statement->case_label.is_empty = true;
8447 warningf(pos, "empty range specified");
8453 PUSH_PARENT(statement);
8457 if (current_switch != NULL) {
8458 if (! statement->case_label.is_bad) {
8459 /* Check for duplicate case values */
8460 case_label_statement_t *c = &statement->case_label;
8461 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8462 if (l->is_bad || l->is_empty || l->expression == NULL)
8465 if (c->last_case < l->first_case || c->first_case > l->last_case)
8468 errorf(pos, "duplicate case value (previously used %P)",
8469 &l->base.source_position);
8473 /* link all cases into the switch statement */
8474 if (current_switch->last_case == NULL) {
8475 current_switch->first_case = &statement->case_label;
8477 current_switch->last_case->next = &statement->case_label;
8479 current_switch->last_case = &statement->case_label;
8481 errorf(pos, "case label not within a switch statement");
8484 statement_t *const inner_stmt = parse_statement();
8485 statement->case_label.statement = inner_stmt;
8486 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8487 errorf(&inner_stmt->base.source_position, "declaration after case label");
8494 return create_invalid_statement();
8498 * Parse a default statement.
8500 static statement_t *parse_default_statement(void)
8504 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8505 statement->base.source_position = token.source_position;
8507 PUSH_PARENT(statement);
8510 if (current_switch != NULL) {
8511 const case_label_statement_t *def_label = current_switch->default_label;
8512 if (def_label != NULL) {
8513 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8514 &def_label->base.source_position);
8516 current_switch->default_label = &statement->case_label;
8518 /* link all cases into the switch statement */
8519 if (current_switch->last_case == NULL) {
8520 current_switch->first_case = &statement->case_label;
8522 current_switch->last_case->next = &statement->case_label;
8524 current_switch->last_case = &statement->case_label;
8527 errorf(&statement->base.source_position,
8528 "'default' label not within a switch statement");
8531 statement_t *const inner_stmt = parse_statement();
8532 statement->case_label.statement = inner_stmt;
8533 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8534 errorf(&inner_stmt->base.source_position, "declaration after default label");
8541 return create_invalid_statement();
8545 * Return the declaration for a given label symbol or create a new one.
8547 * @param symbol the symbol of the label
8549 static declaration_t *get_label(symbol_t *symbol)
8551 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
8552 assert(current_function != NULL);
8553 /* if we found a label in the same function, then we already created the
8555 if (candidate != NULL
8556 && candidate->parent_scope == ¤t_function->scope) {
8560 /* otherwise we need to create a new one */
8561 declaration_t *const declaration = allocate_declaration_zero();
8562 declaration->namespc = NAMESPACE_LABEL;
8563 declaration->symbol = symbol;
8565 label_push(declaration);
8571 * Parse a label statement.
8573 static statement_t *parse_label_statement(void)
8575 assert(token.type == T_IDENTIFIER);
8576 symbol_t *symbol = token.v.symbol;
8579 declaration_t *label = get_label(symbol);
8581 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8582 statement->base.source_position = token.source_position;
8583 statement->label.label = label;
8585 PUSH_PARENT(statement);
8587 /* if source position is already set then the label is defined twice,
8588 * otherwise it was just mentioned in a goto so far */
8589 if (label->source_position.input_name != NULL) {
8590 errorf(HERE, "duplicate label '%Y' (declared %P)",
8591 symbol, &label->source_position);
8593 label->source_position = token.source_position;
8594 label->init.statement = statement;
8599 if (token.type == '}') {
8600 /* TODO only warn? */
8602 warningf(HERE, "label at end of compound statement");
8603 statement->label.statement = create_empty_statement();
8605 errorf(HERE, "label at end of compound statement");
8606 statement->label.statement = create_invalid_statement();
8608 } else if (token.type == ';') {
8609 /* Eat an empty statement here, to avoid the warning about an empty
8610 * statement after a label. label:; is commonly used to have a label
8611 * before a closing brace. */
8612 statement->label.statement = create_empty_statement();
8615 statement_t *const inner_stmt = parse_statement();
8616 statement->label.statement = inner_stmt;
8617 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8618 errorf(&inner_stmt->base.source_position, "declaration after label");
8622 /* remember the labels in a list for later checking */
8623 if (label_last == NULL) {
8624 label_first = &statement->label;
8626 label_last->next = &statement->label;
8628 label_last = &statement->label;
8635 * Parse an if statement.
8637 static statement_t *parse_if(void)
8641 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8642 statement->base.source_position = token.source_position;
8644 PUSH_PARENT(statement);
8647 add_anchor_token(')');
8648 statement->ifs.condition = parse_expression();
8649 rem_anchor_token(')');
8652 add_anchor_token(T_else);
8653 statement->ifs.true_statement = parse_statement();
8654 rem_anchor_token(T_else);
8656 if (token.type == T_else) {
8658 statement->ifs.false_statement = parse_statement();
8665 return create_invalid_statement();
8669 * Check that all enums are handled in a switch.
8671 * @param statement the switch statement to check
8673 static void check_enum_cases(const switch_statement_t *statement) {
8674 const type_t *type = skip_typeref(statement->expression->base.type);
8675 if (! is_type_enum(type))
8677 const enum_type_t *enumt = &type->enumt;
8679 /* if we have a default, no warnings */
8680 if (statement->default_label != NULL)
8683 /* FIXME: calculation of value should be done while parsing */
8684 const declaration_t *declaration;
8685 long last_value = -1;
8686 for (declaration = enumt->declaration->next;
8687 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8688 declaration = declaration->next) {
8689 const expression_t *expression = declaration->init.enum_value;
8690 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8692 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8693 if (l->expression == NULL)
8695 if (l->first_case <= value && value <= l->last_case) {
8701 warningf(&statement->base.source_position,
8702 "enumeration value '%Y' not handled in switch", declaration->symbol);
8709 * Parse a switch statement.
8711 static statement_t *parse_switch(void)
8715 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8716 statement->base.source_position = token.source_position;
8718 PUSH_PARENT(statement);
8721 add_anchor_token(')');
8722 expression_t *const expr = parse_expression();
8723 type_t * type = skip_typeref(expr->base.type);
8724 if (is_type_integer(type)) {
8725 type = promote_integer(type);
8726 if (warning.traditional) {
8727 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8728 warningf(&expr->base.source_position,
8729 "'%T' switch expression not converted to '%T' in ISO C",
8733 } else if (is_type_valid(type)) {
8734 errorf(&expr->base.source_position,
8735 "switch quantity is not an integer, but '%T'", type);
8736 type = type_error_type;
8738 statement->switchs.expression = create_implicit_cast(expr, type);
8740 rem_anchor_token(')');
8742 switch_statement_t *rem = current_switch;
8743 current_switch = &statement->switchs;
8744 statement->switchs.body = parse_statement();
8745 current_switch = rem;
8747 if (warning.switch_default &&
8748 statement->switchs.default_label == NULL) {
8749 warningf(&statement->base.source_position, "switch has no default case");
8751 if (warning.switch_enum)
8752 check_enum_cases(&statement->switchs);
8758 return create_invalid_statement();
8761 static statement_t *parse_loop_body(statement_t *const loop)
8763 statement_t *const rem = current_loop;
8764 current_loop = loop;
8766 statement_t *const body = parse_statement();
8773 * Parse a while statement.
8775 static statement_t *parse_while(void)
8779 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8780 statement->base.source_position = token.source_position;
8782 PUSH_PARENT(statement);
8785 add_anchor_token(')');
8786 statement->whiles.condition = parse_expression();
8787 rem_anchor_token(')');
8790 statement->whiles.body = parse_loop_body(statement);
8796 return create_invalid_statement();
8800 * Parse a do statement.
8802 static statement_t *parse_do(void)
8806 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8807 statement->base.source_position = token.source_position;
8809 PUSH_PARENT(statement)
8811 add_anchor_token(T_while);
8812 statement->do_while.body = parse_loop_body(statement);
8813 rem_anchor_token(T_while);
8817 add_anchor_token(')');
8818 statement->do_while.condition = parse_expression();
8819 rem_anchor_token(')');
8827 return create_invalid_statement();
8831 * Parse a for statement.
8833 static statement_t *parse_for(void)
8837 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
8838 statement->base.source_position = token.source_position;
8840 PUSH_PARENT(statement);
8842 int top = environment_top();
8843 scope_t *last_scope = scope;
8844 set_scope(&statement->fors.scope);
8847 add_anchor_token(')');
8849 if (token.type != ';') {
8850 if (is_declaration_specifier(&token, false)) {
8851 parse_declaration(record_declaration);
8853 add_anchor_token(';');
8854 expression_t *const init = parse_expression();
8855 statement->fors.initialisation = init;
8856 if (warning.unused_value && !expression_has_effect(init)) {
8857 warningf(&init->base.source_position,
8858 "initialisation of 'for'-statement has no effect");
8860 rem_anchor_token(';');
8867 if (token.type != ';') {
8868 add_anchor_token(';');
8869 statement->fors.condition = parse_expression();
8870 rem_anchor_token(';');
8873 if (token.type != ')') {
8874 expression_t *const step = parse_expression();
8875 statement->fors.step = step;
8876 if (warning.unused_value && !expression_has_effect(step)) {
8877 warningf(&step->base.source_position,
8878 "step of 'for'-statement has no effect");
8881 rem_anchor_token(')');
8883 statement->fors.body = parse_loop_body(statement);
8885 assert(scope == &statement->fors.scope);
8886 set_scope(last_scope);
8887 environment_pop_to(top);
8894 rem_anchor_token(')');
8895 assert(scope == &statement->fors.scope);
8896 set_scope(last_scope);
8897 environment_pop_to(top);
8899 return create_invalid_statement();
8903 * Parse a goto statement.
8905 static statement_t *parse_goto(void)
8909 if (token.type != T_IDENTIFIER) {
8910 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8914 symbol_t *symbol = token.v.symbol;
8917 declaration_t *label = get_label(symbol);
8919 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
8920 statement->base.source_position = token.source_position;
8922 statement->gotos.label = label;
8924 /* remember the goto's in a list for later checking */
8925 if (goto_last == NULL) {
8926 goto_first = &statement->gotos;
8928 goto_last->next = &statement->gotos;
8930 goto_last = &statement->gotos;
8936 return create_invalid_statement();
8940 * Parse a continue statement.
8942 static statement_t *parse_continue(void)
8944 if (current_loop == NULL) {
8945 errorf(HERE, "continue statement not within loop");
8948 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
8949 statement->base.source_position = token.source_position;
8959 * Parse a break statement.
8961 static statement_t *parse_break(void)
8963 if (current_switch == NULL && current_loop == NULL) {
8964 errorf(HERE, "break statement not within loop or switch");
8967 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
8968 statement->base.source_position = token.source_position;
8978 * Parse a __leave statement.
8980 static statement_t *parse_leave(void)
8982 if (current_try == NULL) {
8983 errorf(HERE, "__leave statement not within __try");
8986 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
8987 statement->base.source_position = token.source_position;
8997 * Check if a given declaration represents a local variable.
8999 static bool is_local_var_declaration(const declaration_t *declaration)
9001 switch ((storage_class_tag_t) declaration->storage_class) {
9002 case STORAGE_CLASS_AUTO:
9003 case STORAGE_CLASS_REGISTER: {
9004 const type_t *type = skip_typeref(declaration->type);
9005 if (is_type_function(type)) {
9017 * Check if a given declaration represents a variable.
9019 static bool is_var_declaration(const declaration_t *declaration)
9021 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9024 const type_t *type = skip_typeref(declaration->type);
9025 return !is_type_function(type);
9029 * Check if a given expression represents a local variable.
9031 static bool is_local_variable(const expression_t *expression)
9033 if (expression->base.kind != EXPR_REFERENCE) {
9036 const declaration_t *declaration = expression->reference.declaration;
9037 return is_local_var_declaration(declaration);
9041 * Check if a given expression represents a local variable and
9042 * return its declaration then, else return NULL.
9044 declaration_t *expr_is_variable(const expression_t *expression)
9046 if (expression->base.kind != EXPR_REFERENCE) {
9049 declaration_t *declaration = expression->reference.declaration;
9050 if (is_var_declaration(declaration))
9056 * Parse a return statement.
9058 static statement_t *parse_return(void)
9060 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9061 statement->base.source_position = token.source_position;
9065 expression_t *return_value = NULL;
9066 if (token.type != ';') {
9067 return_value = parse_expression();
9070 const type_t *const func_type = current_function->type;
9071 assert(is_type_function(func_type));
9072 type_t *const return_type = skip_typeref(func_type->function.return_type);
9074 if (return_value != NULL) {
9075 type_t *return_value_type = skip_typeref(return_value->base.type);
9077 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9078 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9079 warningf(&statement->base.source_position,
9080 "'return' with a value, in function returning void");
9081 return_value = NULL;
9083 assign_error_t error = semantic_assign(return_type, return_value);
9084 report_assign_error(error, return_type, return_value, "'return'",
9085 &statement->base.source_position);
9086 return_value = create_implicit_cast(return_value, return_type);
9088 /* check for returning address of a local var */
9089 if (return_value != NULL &&
9090 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9091 const expression_t *expression = return_value->unary.value;
9092 if (is_local_variable(expression)) {
9093 warningf(&statement->base.source_position,
9094 "function returns address of local variable");
9098 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9099 warningf(&statement->base.source_position,
9100 "'return' without value, in function returning non-void");
9103 statement->returns.value = return_value;
9112 * Parse a declaration statement.
9114 static statement_t *parse_declaration_statement(void)
9116 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9118 statement->base.source_position = token.source_position;
9120 declaration_t *before = last_declaration;
9121 parse_declaration(record_declaration);
9123 if (before == NULL) {
9124 statement->declaration.declarations_begin = scope->declarations;
9126 statement->declaration.declarations_begin = before->next;
9128 statement->declaration.declarations_end = last_declaration;
9134 * Parse an expression statement, ie. expr ';'.
9136 static statement_t *parse_expression_statement(void)
9138 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9140 statement->base.source_position = token.source_position;
9141 expression_t *const expr = parse_expression();
9142 statement->expression.expression = expr;
9151 * Parse a microsoft __try { } __finally { } or
9152 * __try{ } __except() { }
9154 static statement_t *parse_ms_try_statment(void)
9156 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9157 statement->base.source_position = token.source_position;
9160 PUSH_PARENT(statement);
9162 ms_try_statement_t *rem = current_try;
9163 current_try = &statement->ms_try;
9164 statement->ms_try.try_statement = parse_compound_statement(false);
9169 if (token.type == T___except) {
9172 add_anchor_token(')');
9173 expression_t *const expr = parse_expression();
9174 type_t * type = skip_typeref(expr->base.type);
9175 if (is_type_integer(type)) {
9176 type = promote_integer(type);
9177 } else if (is_type_valid(type)) {
9178 errorf(&expr->base.source_position,
9179 "__expect expression is not an integer, but '%T'", type);
9180 type = type_error_type;
9182 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9183 rem_anchor_token(')');
9185 statement->ms_try.final_statement = parse_compound_statement(false);
9186 } else if (token.type == T__finally) {
9188 statement->ms_try.final_statement = parse_compound_statement(false);
9190 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9191 return create_invalid_statement();
9195 return create_invalid_statement();
9198 static statement_t *parse_empty_statement(void)
9200 if (warning.empty_statement) {
9201 warningf(HERE, "statement is empty");
9203 statement_t *const statement = create_empty_statement();
9209 * Parse a statement.
9210 * There's also parse_statement() which additionally checks for
9211 * "statement has no effect" warnings
9213 static statement_t *intern_parse_statement(void)
9215 statement_t *statement = NULL;
9217 /* declaration or statement */
9218 add_anchor_token(';');
9219 switch (token.type) {
9220 case T_IDENTIFIER: {
9221 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9222 if (la1_type == ':') {
9223 statement = parse_label_statement();
9224 } else if (is_typedef_symbol(token.v.symbol)) {
9225 statement = parse_declaration_statement();
9226 } else switch (la1_type) {
9230 statement = parse_declaration_statement();
9234 statement = parse_expression_statement();
9240 case T___extension__:
9241 /* This can be a prefix to a declaration or an expression statement.
9242 * We simply eat it now and parse the rest with tail recursion. */
9245 } while (token.type == T___extension__);
9246 statement = parse_statement();
9250 statement = parse_declaration_statement();
9253 case ';': statement = parse_empty_statement(); break;
9254 case '{': statement = parse_compound_statement(false); break;
9255 case T___leave: statement = parse_leave(); break;
9256 case T___try: statement = parse_ms_try_statment(); break;
9257 case T_asm: statement = parse_asm_statement(); break;
9258 case T_break: statement = parse_break(); break;
9259 case T_case: statement = parse_case_statement(); break;
9260 case T_continue: statement = parse_continue(); break;
9261 case T_default: statement = parse_default_statement(); break;
9262 case T_do: statement = parse_do(); break;
9263 case T_for: statement = parse_for(); break;
9264 case T_goto: statement = parse_goto(); break;
9265 case T_if: statement = parse_if (); break;
9266 case T_return: statement = parse_return(); break;
9267 case T_switch: statement = parse_switch(); break;
9268 case T_while: statement = parse_while(); break;
9269 default: statement = parse_expression_statement(); break;
9271 rem_anchor_token(';');
9273 assert(statement != NULL
9274 && statement->base.source_position.input_name != NULL);
9280 * parse a statement and emits "statement has no effect" warning if needed
9281 * (This is really a wrapper around intern_parse_statement with check for 1
9282 * single warning. It is needed, because for statement expressions we have
9283 * to avoid the warning on the last statement)
9285 static statement_t *parse_statement(void)
9287 statement_t *statement = intern_parse_statement();
9289 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9290 expression_t *expression = statement->expression.expression;
9291 if (!expression_has_effect(expression)) {
9292 warningf(&expression->base.source_position,
9293 "statement has no effect");
9301 * Parse a compound statement.
9303 static statement_t *parse_compound_statement(bool inside_expression_statement)
9305 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9306 statement->base.source_position = token.source_position;
9308 PUSH_PARENT(statement);
9311 add_anchor_token('}');
9313 int top = environment_top();
9314 scope_t *last_scope = scope;
9315 set_scope(&statement->compound.scope);
9317 statement_t **anchor = &statement->compound.statements;
9318 bool only_decls_so_far = true;
9319 while (token.type != '}' && token.type != T_EOF) {
9320 statement_t *sub_statement = intern_parse_statement();
9321 if (is_invalid_statement(sub_statement)) {
9322 /* an error occurred. if we are at an anchor, return */
9328 if (warning.declaration_after_statement) {
9329 if (sub_statement->kind != STATEMENT_DECLARATION) {
9330 only_decls_so_far = false;
9331 } else if (!only_decls_so_far) {
9332 warningf(&sub_statement->base.source_position,
9333 "ISO C90 forbids mixed declarations and code");
9337 *anchor = sub_statement;
9339 while (sub_statement->base.next != NULL)
9340 sub_statement = sub_statement->base.next;
9342 anchor = &sub_statement->base.next;
9345 if (token.type == '}') {
9348 errorf(&statement->base.source_position,
9349 "end of file while looking for closing '}'");
9352 /* look over all statements again to produce no effect warnings */
9353 if (warning.unused_value) {
9354 statement_t *sub_statement = statement->compound.statements;
9355 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9356 if (sub_statement->kind != STATEMENT_EXPRESSION)
9358 /* don't emit a warning for the last expression in an expression
9359 * statement as it has always an effect */
9360 if (inside_expression_statement && sub_statement->base.next == NULL)
9363 expression_t *expression = sub_statement->expression.expression;
9364 if (!expression_has_effect(expression)) {
9365 warningf(&expression->base.source_position,
9366 "statement has no effect");
9372 rem_anchor_token('}');
9373 assert(scope == &statement->compound.scope);
9374 set_scope(last_scope);
9375 environment_pop_to(top);
9382 * Initialize builtin types.
9384 static void initialize_builtin_types(void)
9386 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9387 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9388 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9389 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9390 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9391 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9392 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9393 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9395 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9396 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9397 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9398 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9400 /* const version of wchar_t */
9401 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9402 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9403 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9405 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9409 * Check for unused global static functions and variables
9411 static void check_unused_globals(void)
9413 if (!warning.unused_function && !warning.unused_variable)
9416 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9418 decl->modifiers & DM_UNUSED ||
9419 decl->modifiers & DM_USED ||
9420 decl->storage_class != STORAGE_CLASS_STATIC)
9423 type_t *const type = decl->type;
9425 if (is_type_function(skip_typeref(type))) {
9426 if (!warning.unused_function || decl->is_inline)
9429 s = (decl->init.statement != NULL ? "defined" : "declared");
9431 if (!warning.unused_variable)
9437 warningf(&decl->source_position, "'%#T' %s but not used",
9438 type, decl->symbol, s);
9442 static void parse_global_asm(void)
9447 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9448 statement->base.source_position = token.source_position;
9449 statement->asms.asm_text = parse_string_literals();
9450 statement->base.next = unit->global_asm;
9451 unit->global_asm = statement;
9460 * Parse a translation unit.
9462 static void parse_translation_unit(void)
9464 for (;;) switch (token.type) {
9467 case T___extension__:
9468 parse_external_declaration();
9479 /* TODO error in strict mode */
9480 warningf(HERE, "stray ';' outside of function");
9485 errorf(HERE, "stray %K outside of function", &token);
9486 if (token.type == '(' || token.type == '{' || token.type == '[')
9487 eat_until_matching_token(token.type);
9496 * @return the translation unit or NULL if errors occurred.
9498 void start_parsing(void)
9500 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9501 label_stack = NEW_ARR_F(stack_entry_t, 0);
9502 diagnostic_count = 0;
9506 type_set_output(stderr);
9507 ast_set_output(stderr);
9509 assert(unit == NULL);
9510 unit = allocate_ast_zero(sizeof(unit[0]));
9512 assert(global_scope == NULL);
9513 global_scope = &unit->scope;
9515 assert(scope == NULL);
9516 set_scope(&unit->scope);
9518 initialize_builtin_types();
9521 translation_unit_t *finish_parsing(void)
9523 assert(scope == &unit->scope);
9525 last_declaration = NULL;
9527 assert(global_scope == &unit->scope);
9528 check_unused_globals();
9529 global_scope = NULL;
9531 DEL_ARR_F(environment_stack);
9532 DEL_ARR_F(label_stack);
9534 translation_unit_t *result = unit;
9541 lookahead_bufpos = 0;
9542 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9545 parse_translation_unit();
9549 * Initialize the parser.
9551 void init_parser(void)
9554 /* add predefined symbols for extended-decl-modifier */
9555 sym_align = symbol_table_insert("align");
9556 sym_allocate = symbol_table_insert("allocate");
9557 sym_dllimport = symbol_table_insert("dllimport");
9558 sym_dllexport = symbol_table_insert("dllexport");
9559 sym_naked = symbol_table_insert("naked");
9560 sym_noinline = symbol_table_insert("noinline");
9561 sym_noreturn = symbol_table_insert("noreturn");
9562 sym_nothrow = symbol_table_insert("nothrow");
9563 sym_novtable = symbol_table_insert("novtable");
9564 sym_property = symbol_table_insert("property");
9565 sym_get = symbol_table_insert("get");
9566 sym_put = symbol_table_insert("put");
9567 sym_selectany = symbol_table_insert("selectany");
9568 sym_thread = symbol_table_insert("thread");
9569 sym_uuid = symbol_table_insert("uuid");
9570 sym_deprecated = symbol_table_insert("deprecated");
9571 sym_restrict = symbol_table_insert("restrict");
9572 sym_noalias = symbol_table_insert("noalias");
9574 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9576 init_expression_parsers();
9577 obstack_init(&temp_obst);
9579 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9580 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9584 * Terminate the parser.
9586 void exit_parser(void)
9588 obstack_free(&temp_obst, NULL);